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 |
|---|---|---|---|---|---|---|---|---|
// 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;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification
{
internal sealed class ClassificationTypeFormatDefinitions
{
#region Preprocessor Text
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.PreprocessorText)]
[Name(ClassificationTypeNames.PreprocessorText)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class PreprocessorTextFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreprocessorTextFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Preprocessor_Text;
this.ForegroundColor = Colors.Black;
}
}
#endregion
#region Punctuation
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.Punctuation)]
[Name(ClassificationTypeNames.Punctuation)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class PunctuationFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PunctuationFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Punctuation;
this.ForegroundColor = Colors.Black;
}
}
#endregion
#region String - Verbatim
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.VerbatimStringLiteral)]
[Name(ClassificationTypeNames.VerbatimStringLiteral)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class StringVerbatimFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StringVerbatimFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.String_Verbatim;
this.ForegroundColor = Colors.Maroon;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StringEscapeCharacter)]
[Name(ClassificationTypeNames.StringEscapeCharacter)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class StringEscapeCharacterFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StringEscapeCharacterFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.String_Escape_Character;
this.ForegroundColor = Color.FromRgb(0x9e, 0x5b, 0x71);
}
}
#endregion
#region Keyword - Control
// Keyword - Control is ordered after Keyword to ensure this more specific
// classification will take precedence.
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ControlKeyword)]
[Name(ClassificationTypeNames.ControlKeyword)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class ControlKeywordFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ControlKeywordFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.Keyword_Control;
}
#endregion
#region Operator - Overloaded
// Operator - Overloaded is ordered after Operator to ensure this more specific
// classification will take precedence.
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.OperatorOverloaded)]
[Name(ClassificationTypeNames.OperatorOverloaded)]
[Order(After = PredefinedClassificationTypeNames.Operator)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class OperatorOverloadedFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public OperatorOverloadedFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.Operator_Overloaded;
}
#endregion
#region Symbol - Static
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StaticSymbol)]
[Name(ClassificationTypeNames.StaticSymbol)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class SymbolStaticFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SymbolStaticFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Symbol_Static;
// The static classification is intended to be an additive classification
// that simply changes the font's styling (bold or not). Allowing
// customization of the foreground color would cause issues with
// TaggedText as it is currently implemented, since any particular
// span can only be tagged with a single TextTag.
// By restricting to only font style, the QuickInfo and FAR render with the
// colors the user would expect. The missing font style is not an problem
// for these experiences because the QuickInfo already renders the static
// modifier as part of its text and the FAR window already applies its
// own bolding to the rendered output.
this.BackgroundCustomizable = false;
this.ForegroundCustomizable = false;
}
}
#endregion
// User Types - * and User Members - * are ordered after Keyword
// so that, in the case both classifications are applied to the same
// span, the styling for the identifier type would be chosen.
// User Types - * and User Members - * are ordered before Symbol - Static
// so that the font styling chosen for static symbols would override the
// styling chosen for specific identifier types.
#region User Types - Classes
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ClassName)]
[Name(ClassificationTypeNames.ClassName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeClassesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeClassesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Classes;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Delegates
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.DelegateName)]
[Name(ClassificationTypeNames.DelegateName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeDelegatesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeDelegatesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Delegates;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Enums
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.EnumName)]
[Name(ClassificationTypeNames.EnumName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeEnumsFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeEnumsFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Enums;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Interfaces
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.InterfaceName)]
[Name(ClassificationTypeNames.InterfaceName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeInterfacesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeInterfacesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Interfaces;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Modules
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ModuleName)]
[Name(ClassificationTypeNames.ModuleName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
private class UserTypeModulesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeModulesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Modules;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Structures
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.StructName)]
[Name(ClassificationTypeNames.StructName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeStructuresFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeStructuresFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Structures;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Types - Type Parameters
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.TypeParameterName)]
[Name(ClassificationTypeNames.TypeParameterName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserTypeTypeParametersFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserTypeTypeParametersFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.User_Types_Type_Parameters;
this.ForegroundColor = Color.FromRgb(0x2B, 0x91, 0xAF);
}
}
#endregion
#region User Members - Fields
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.FieldName)]
[Name(ClassificationTypeNames.FieldName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersFieldNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersFieldNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Fields;
}
#endregion
#region User Members - Enum Members
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.EnumMemberName)]
[Name(ClassificationTypeNames.EnumMemberName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersEnumMemberNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersEnumMemberNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Enum_Members;
}
#endregion
#region User Members - Constants
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ConstantName)]
[Name(ClassificationTypeNames.ConstantName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersConstantNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersConstantNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Constants;
}
#endregion
#region User Members - Locals
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.LocalName)]
[Name(ClassificationTypeNames.LocalName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersLocalNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersLocalNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Locals;
}
#endregion
#region User Members - Parameters
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ParameterName)]
[Name(ClassificationTypeNames.ParameterName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersParameterNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersParameterNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Parameters;
}
#endregion
#region User Members - Methods
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.MethodName)]
[Name(ClassificationTypeNames.MethodName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersMethodNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersMethodNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Methods;
}
#endregion
#region User Members - Extension Methods
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.ExtensionMethodName)]
[Name(ClassificationTypeNames.ExtensionMethodName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersExtensionMethodNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersExtensionMethodNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Extension_Methods;
}
#endregion
#region User Members - Properties
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.PropertyName)]
[Name(ClassificationTypeNames.PropertyName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersPropertyNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersPropertyNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Properties;
}
#endregion
#region User Members - Events
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.EventName)]
[Name(ClassificationTypeNames.EventName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersEventNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersEventNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Events;
}
#endregion
#region User Members - Namespaces
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.NamespaceName)]
[Name(ClassificationTypeNames.NamespaceName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersNamespaceNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersNamespaceNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Namespaces;
}
#endregion
#region User Members - Labels
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.LabelName)]
[Name(ClassificationTypeNames.LabelName)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
[Order(Before = ClassificationTypeNames.StaticSymbol)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class UserMembersLabelNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UserMembersLabelNameFormatDefinition()
=> this.DisplayName = EditorFeaturesResources.User_Members_Labels;
}
#endregion
#region XML Doc Comments - Attribute Name
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeName)]
[Name(ClassificationTypeNames.XmlDocCommentAttributeName)]
[Order(After = Priority.Default, Before = Priority.High)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentAttributeNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentAttributeNameFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Name;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Attribute Quotes
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeQuotes)]
[Name(ClassificationTypeNames.XmlDocCommentAttributeQuotes)]
[Order(After = Priority.Default, Before = Priority.High)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentAttributeQuotesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentAttributeQuotesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Quotes;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Attribute Value
// definition of how format is represented in tools options.
// also specifies the default format.
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentAttributeValue)]
[Name(ClassificationTypeNames.XmlDocCommentAttributeValue)]
[Order(After = Priority.Default, Before = Priority.High)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentAttributeValueFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentAttributeValueFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Attribute_Value;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - CData Section
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentCDataSection)]
[Name(ClassificationTypeNames.XmlDocCommentCDataSection)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentCDataSectionFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentCDataSectionFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_CData_Section;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Comment
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentComment)]
[Name(ClassificationTypeNames.XmlDocCommentComment)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentCommentFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentCommentFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Comment;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Delimiter
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentDelimiter)]
[Name(ClassificationTypeNames.XmlDocCommentDelimiter)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentDelimiterFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentDelimiterFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Delimiter;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Entity Reference
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentEntityReference)]
[Name(ClassificationTypeNames.XmlDocCommentEntityReference)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentEntityReferenceFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentEntityReferenceFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Entity_Reference;
this.ForegroundColor = Colors.Green;
}
}
#endregion
#region XML Doc Comments - Name
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentName)]
[Name(ClassificationTypeNames.XmlDocCommentName)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentNameFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Name;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Processing Instruction
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentProcessingInstruction)]
[Name(ClassificationTypeNames.XmlDocCommentProcessingInstruction)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentProcessingInstructionFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentProcessingInstructionFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Processing_Instruction;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region XML Doc Comments - Text
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlDocCommentText)]
[Name(ClassificationTypeNames.XmlDocCommentText)]
[Order(After = Priority.Default, Before = Priority.High)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class XmlDocCommentTextFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlDocCommentTextFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.XML_Doc_Comments_Text;
this.ForegroundColor = Colors.Green;
}
}
#endregion
#region Regex
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexComment)]
[Name(ClassificationTypeNames.RegexComment)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexCommentFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexCommentFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Comment;
this.ForegroundColor = Color.FromRgb(0x00, 0x80, 0x00);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexCharacterClass)]
[Name(ClassificationTypeNames.RegexCharacterClass)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexCharacterClassFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexCharacterClassFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Character_Class;
this.ForegroundColor = Color.FromRgb(0x00, 0x73, 0xff);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAnchor)]
[Name(ClassificationTypeNames.RegexAnchor)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexAnchorFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexAnchorFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Anchor;
this.ForegroundColor = Color.FromRgb(0xff, 0x00, 0xc1);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexQuantifier)]
[Name(ClassificationTypeNames.RegexQuantifier)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexQuantifierFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexQuantifierFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Quantifier;
this.ForegroundColor = Color.FromRgb(0xff, 0x00, 0xc1);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexGrouping)]
[Name(ClassificationTypeNames.RegexGrouping)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexGroupingFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexGroupingFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Grouping;
this.ForegroundColor = Color.FromRgb(0x05, 0xc3, 0xba);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexAlternation)]
[Name(ClassificationTypeNames.RegexAlternation)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexAlternationFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexAlternationFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Alternation;
this.ForegroundColor = Color.FromRgb(0x05, 0xc3, 0xba);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexText)]
[Name(ClassificationTypeNames.RegexText)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexTextFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexTextFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_Text;
this.ForegroundColor = Color.FromRgb(0x80, 0x00, 0x00);
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexSelfEscapedCharacter)]
[Name(ClassificationTypeNames.RegexSelfEscapedCharacter)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexSelfEscapedCharacterFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexSelfEscapedCharacterFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_SelfEscapedCharacter;
// by default, we make a self-escaped character just the bolded form of the normal
// text color.
this.ForegroundColor = Color.FromRgb(0x80, 0x00, 0x00);
this.IsBold = true;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.RegexOtherEscape)]
[Name(ClassificationTypeNames.RegexOtherEscape)]
[Order(After = ClassificationTypeNames.StringLiteral)]
[Order(After = ClassificationTypeNames.VerbatimStringLiteral)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
private class RegexOtherEscapeFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RegexOtherEscapeFormatDefinition()
{
this.DisplayName = EditorFeaturesWpfResources.Regex_OtherEscape;
this.ForegroundColor = Color.FromRgb(0x9e, 0x5b, 0x71);
}
}
#endregion
#region VB XML Literals - Attribute Name
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeName)]
[Name(ClassificationTypeNames.XmlLiteralAttributeName)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralAttributeNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralAttributeNameFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Name;
this.ForegroundColor = Color.FromRgb(0xB9, 0x64, 0x64); // HC_LIGHTRED
}
}
#endregion
#region VB XML Literals - Attribute Quotes
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeQuotes)]
[Name(ClassificationTypeNames.XmlLiteralAttributeQuotes)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralAttributeQuotesFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralAttributeQuotesFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Quotes;
this.ForegroundColor = Color.FromRgb(0x55, 0x55, 0x55); // HC_LIGHTBLACK
}
}
#endregion
#region VB XML Literals - Attribute Value
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralAttributeValue)]
[Name(ClassificationTypeNames.XmlLiteralAttributeValue)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralAttributeValueFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralAttributeValueFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Attribute_Value;
this.ForegroundColor = Color.FromRgb(0x64, 0x64, 0xB9); // HC_LIGHTBLUE
}
}
#endregion
#region VB XML Literals - CData Section
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralCDataSection)]
[Name(ClassificationTypeNames.XmlLiteralCDataSection)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralCDataSectionFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralCDataSectionFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_CData_Section;
this.ForegroundColor = Color.FromRgb(0x80, 0x80, 0x80); // CIDARKGRAY
}
}
#endregion
#region VB XML Literals - Comment
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralComment)]
[Name(ClassificationTypeNames.XmlLiteralComment)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralCommentFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralCommentFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Comment;
this.ForegroundColor = Color.FromRgb(0x62, 0x97, 0x55); // HC_LIGHTGREEN
}
}
#endregion
#region VB XML Literals - Delimiter
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralDelimiter)]
[Name(ClassificationTypeNames.XmlLiteralDelimiter)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralDelimiterFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralDelimiterFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Delimiter;
this.ForegroundColor = Color.FromRgb(0x64, 0x64, 0xB9); // HC_LIGHTBLUE
}
}
#endregion
#region VB XML Literals - Embedded Expression
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEmbeddedExpression)]
[Name(ClassificationTypeNames.XmlLiteralEmbeddedExpression)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralEmbeddedExpressionFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralEmbeddedExpressionFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Embedded_Expression;
this.ForegroundColor = Color.FromRgb(0x55, 0x55, 0x55); // HC_LIGHTBLACK
this.BackgroundColor = Color.FromRgb(0xFF, 0xFE, 0xBF); // HC_LIGHTYELLOW
}
}
#endregion
#region VB XML Literals - Entity Reference
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralEntityReference)]
[Name(ClassificationTypeNames.XmlLiteralEntityReference)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralEntityReferenceFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralEntityReferenceFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Entity_Reference;
this.ForegroundColor = Color.FromRgb(0xB9, 0x64, 0x64); // HC_LIGHTRED
}
}
#endregion
#region VB XML Literals - Name
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralName)]
[Name(ClassificationTypeNames.XmlLiteralName)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralNameFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralNameFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Name;
this.ForegroundColor = Color.FromRgb(0x84, 0x46, 0x46); // HC_LIGHTMAROON
}
}
#endregion
#region VB XML Literals - Processing Instruction
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralProcessingInstruction)]
[Name(ClassificationTypeNames.XmlLiteralProcessingInstruction)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralProcessingInstructionFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralProcessingInstructionFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Processing_Instruction;
this.ForegroundColor = Color.FromRgb(0xC0, 0xC0, 0xC0); // HC_LIGHTGRAY
}
}
#endregion
#region VB XML Literals - Text
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeNames.XmlLiteralText)]
[Name(ClassificationTypeNames.XmlLiteralText)]
[Order(After = LanguagePriority.NaturalLanguage, Before = LanguagePriority.FormalLanguage)]
[UserVisible(true)]
private class XmlLiteralTextFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public XmlLiteralTextFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.VB_XML_Literals_Text;
this.ForegroundColor = Color.FromRgb(0x55, 0x55, 0x55); // HC_LIGHTBLACK
}
}
#endregion
}
}
| 50.071429 | 114 | 0.689652 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/EditorFeatures/Core.Wpf/Classification/ClassificationTypeFormatDefinitions.cs | 51,876 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using System;
using System.Reactive;
#if WINDOWS_UWP
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
#else
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
#endif
namespace ReactNative.UIManager.LayoutAnimation
{
/// <summary>
/// Defines which <see cref="Storyboard"/> should be used for animating
/// layout updates for <see cref="FrameworkElement"/>.
/// </summary>
class LayoutUpdateAnimation : LayoutAnimation
{
/// <summary>
/// Signals if the animation configuration is valid.
/// </summary>
protected override bool IsValid
{
get
{
return Duration > TimeSpan.Zero;
}
}
/// <summary>
/// Create a <see cref="Storyboard"/> to be used to animate the view,
/// based on the animation configuration supplied at initialization
/// time and the new view position and size.
/// </summary>
/// <param name="viewManager">The view manager for the view.</param>
/// <param name="view">The view to create the animation for.</param>
/// <param name="dimensions">The view dimensions.</param>
/// <returns>The storyboard.</returns>
protected override IObservable<Unit> CreateAnimationCore(IViewManager viewManager, object view, Dimensions dimensions)
{
var currentDimensions = viewManager.GetDimensions(view);
var animateLocation = dimensions.X != currentDimensions.X || dimensions.Y != currentDimensions.Y;
var animateSize = dimensions.Width != currentDimensions.Width || dimensions.Height != currentDimensions.Height;
if (!animateLocation && !animateSize)
{
return null;
}
var element = ViewConversion.GetDependencyObject(view);
var storyboard = new Storyboard();
if (currentDimensions.X != dimensions.X)
{
storyboard.Children.Add(
CreateTimeline(element, "(Canvas.Left)", currentDimensions.X, dimensions.X));
}
if (currentDimensions.Y != dimensions.Y)
{
storyboard.Children.Add(
CreateTimeline(element, "(Canvas.Top)", currentDimensions.Y, dimensions.Y));
}
if (currentDimensions.Width != dimensions.Width)
{
var timeline = CreateTimeline(element, "Width", currentDimensions.Width, dimensions.Width);
#if WINDOWS_UWP
timeline.EnableDependentAnimation = true;
#endif
storyboard.Children.Add(timeline);
}
if (currentDimensions.Height != dimensions.Height)
{
var timeline = CreateTimeline(element, "Height", currentDimensions.Height, dimensions.Height);
#if WINDOWS_UWP
timeline.EnableDependentAnimation = true;
#endif
storyboard.Children.Add(timeline);
}
return new StoryboardObservable(storyboard, () =>
{
viewManager.SetDimensions(element, dimensions);
});
}
private DoubleAnimation CreateTimeline(DependencyObject view, string path, double from, double to)
{
var timeline = new DoubleAnimation
{
From = from,
To = to,
EasingFunction = Interpolator,
Duration = Duration,
BeginTime = Delay,
};
Storyboard.SetTarget(timeline, view);
#if WINDOWS_UWP
Storyboard.SetTargetProperty(timeline, path);
#else
Storyboard.SetTargetProperty(timeline, new PropertyPath(path));
#endif
return timeline;
}
}
}
| 34.389831 | 126 | 0.598078 | [
"MIT"
] | 05340836108/react-native-windows | current/ReactWindows/ReactNative.Shared/UIManager/LayoutAnimation/LayoutUpdateAnimation.cs | 4,058 | C# |
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters.MessageBodyFormatters;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 查询终端属性应答
/// </summary>
[JT808Formatter(typeof(JT808_0x0107_Formatter))]
public class JT808_0x0107 : JT808Bodies
{
/// <summary>
/// 终端类型
/// bit0,0:不适用客运车辆,1:适用客运车辆;
/// bit1,0:不适用危险品车辆,1:适用危险品车辆;
/// bit2,0:不适用普通货运车辆,1:适用普通货运车辆;
/// bit3,0:不适用出租车辆,1:适用出租车辆;
/// bit6,0:不支持硬盘录像,1:支持硬盘录像;
/// bit7,0:一体机,1:分体机
/// </summary>
public ushort TerminalType { get; set; }
/// <summary>
/// 制造商 ID
/// 5 个字节,终端制造商编码
/// </summary>
public string MakerId { get; set; }
/// <summary>
/// 终端型号
/// BYTE[20]
/// 20 个字节,此终端型号由制造商自行定义,位数不足时,后补“0X00”。
/// </summary>
public string TerminalModel { get; set; }
/// <summary>
/// 终端ID
/// BYTE[7]
/// 7 个字节,由大写字母和数字组成,此终端 ID 由制造商自行定义,位数不足时,后补“0X00”
/// </summary>
public string TerminalId { get; set; }
/// <summary>
/// 终端 SIM 卡 ICCID
/// BCD[10]
/// </summary>
public string Terminal_SIM_ICCID { get; set; }
/// <summary>
/// 终端硬件版本号长度
/// </summary>
public byte Terminal_Hardware_Version_Length { get; set; }
/// <summary>
/// 终端硬件版本号
/// </summary>
public string Terminal_Hardware_Version_Num { get; set; }
/// <summary>
/// 终端固件版本号长度
/// </summary>
public byte Terminal_Firmware_Version_Length { get; set; }
/// <summary>
/// 终端固件版本号
/// </summary>
public string Terminal_Firmware_Version_Num { get; set; }
/// <summary>
/// GNSS 模块属性
/// bit0,0:不支持 GPS 定位, 1:支持 GPS 定位;
/// bit1,0:不支持北斗定位, 1:支持北斗定位;
/// bit2,0:不支持 GLONASS 定位, 1:支持 GLONASS 定位;
/// bit3,0:不支持 Galileo 定位, 1:支持 Galileo 定位
/// </summary>
public byte GNSSModule { get; set; }
/// <summary>
/// 通信模块属性
/// bit0,0:不支持GPRS通信, 1:支持GPRS通信;
/// bit1,0:不支持CDMA通信, 1:支持CDMA通信;
/// bit2,0:不支持TD-SCDMA通信, 1:支持TD-SCDMA通信;
/// bit3,0:不支持WCDMA通信, 1:支持WCDMA通信;
/// bit4,0:不支持CDMA2000通信, 1:支持CDMA2000通信。
/// bit5,0:不支持TD-LTE通信, 1:支持TD-LTE通信;
/// bit7,0:不支持其他通信方式, 1:支持其他通信方式
/// </summary>
public byte CommunicationModule { get; set; }
}
}
| 31.345679 | 66 | 0.520284 | [
"MIT"
] | HengCC/JT808-1 | src/JT808.Protocol/MessageBody/JT808_0x0107.cs | 3,367 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Noord.Hollands.Archief.Preingest.WorkerService.Entities
{
public class AppSettings
{
public String EventHubUrl { get; set; }
public String WebApiUrl { get; set; }
}
}
| 21.533333 | 65 | 0.718266 | [
"MIT"
] | noord-hollandsarchief/preingest | preingest/Noord.Hollands.Archief.Preingest.WorkerService/Entities/AppSettings.cs | 325 | C# |
using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions;
using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext;
using Enmeshed.DevelopmentKit.Identity.ValueObjects;
using Enmeshed.Tooling;
using Enmeshed.UnitTestTools.BaseClasses;
using FakeItEasy;
using FluentAssertions;
using Synchronization.Application.SyncRuns.Commands.RefreshExpirationTimeOfSyncRun;
using Synchronization.Infrastructure.Persistence.Database;
using Xunit;
namespace Synchronization.Application.Tests.Tests.SyncRuns.Commands.RefreshExpirationTimeOfSyncRun;
public class HandlerTests : RequestHandlerTestsBase<ApplicationDbContext>
{
[Fact]
public async Task Cannot_refresh_expiration_time_of_sync_run_created_by_other_device()
{
// Arrange
var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress();
var activeDevice = TestDataGenerator.CreateRandomDeviceId();
var handler = CreateHandler(activeIdentity, activeDevice);
var syncRun = SyncRunBuilder.Build().CreatedBy(activeIdentity).CreatedByDevice(TestDataGenerator.CreateRandomDeviceId()).Create();
_arrangeContext.SaveEntity(syncRun);
// Act
Func<Task> acting = async () => await handler.Handle(new RefreshExpirationTimeOfSyncRunCommand(syncRun.Id), CancellationToken.None);
// Assert
await acting.Should().ThrowAsync<OperationFailedException>().WithErrorCode("error.platform.validation.syncRun.cannotRefreshExpirationTimeOfSyncRunStartedByAnotherDevice");
}
[Fact]
public async Task Cannot_refresh_expiration_time_of_sync_run_created_by_other_identity()
{
// Arrange
var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress();
var activeDevice = TestDataGenerator.CreateRandomDeviceId();
var handler = CreateHandler(activeIdentity, activeDevice);
var syncRun = SyncRunBuilder.Build().CreatedBy(TestDataGenerator.CreateRandomIdentityAddress()).CreatedByDevice(TestDataGenerator.CreateRandomDeviceId()).Create();
_arrangeContext.SaveEntity(syncRun);
// Act
Func<Task> acting = async () => await handler.Handle(new RefreshExpirationTimeOfSyncRunCommand(syncRun.Id), CancellationToken.None);
// Assert
await acting.Should().ThrowAsync<NotFoundException>().WithMessage("*SyncRun*");
}
[Fact]
public async Task Refresh_expiration_time()
{
// Arrange
var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress();
var activeDevice = TestDataGenerator.CreateRandomDeviceId();
var handler = CreateHandler(activeIdentity, activeDevice);
var syncRun = SyncRunBuilder.Build().CreatedBy(activeIdentity).CreatedByDevice(activeDevice).Create();
_arrangeContext.SaveEntity(syncRun);
var utcNow = DateTime.UtcNow;
SystemTime.Set(utcNow);
// Act
var response = await handler.Handle(new RefreshExpirationTimeOfSyncRunCommand(syncRun.Id), CancellationToken.None);
// Assert
response.ExpiresAt.Should().BeAfter(utcNow);
}
[Fact]
public async Task Refresh_expiration_time_of_expired_sync_run()
{
// Arrange
var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress();
var activeDevice = TestDataGenerator.CreateRandomDeviceId();
var handler = CreateHandler(activeIdentity, activeDevice);
var utcNow = DateTime.UtcNow;
SystemTime.Set(utcNow);
var syncRun = SyncRunBuilder.Build().CreatedBy(activeIdentity).ExpiresAt(utcNow.AddDays(-5)).CreatedByDevice(activeDevice).Create();
_arrangeContext.SaveEntity(syncRun);
// Act
var response = await handler.Handle(new RefreshExpirationTimeOfSyncRunCommand(syncRun.Id), CancellationToken.None);
// Assert
response.ExpiresAt.Should().BeAfter(utcNow);
}
#region CreateHandler
private Handler CreateHandler(IdentityAddress activeIdentity, DeviceId createdByDevice)
{
var userContext = A.Fake<IUserContext>();
A.CallTo(() => userContext.GetAddress()).Returns(activeIdentity);
A.CallTo(() => userContext.GetDeviceId()).Returns(createdByDevice);
return new Handler(_actContext, userContext);
}
#endregion
}
| 37.556522 | 179 | 0.738365 | [
"MIT"
] | nmshd/bkb-synchronization | Synchronization.Application.Tests/Tests/SyncRuns/Commands/RefreshExpirationTimeOfSyncRun/HandlerTests.cs | 4,321 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using CommandLine;
using Grynwald.MdDocs.ApiReference.Commands;
using Grynwald.MdDocs.ApiReference.Configuration;
using Grynwald.MdDocs.CommandLineHelp.Commands;
using Grynwald.MdDocs.CommandLineHelp.Configuration;
using Grynwald.MdDocs.Common.Configuration;
using Grynwald.Utilities.Logging;
using Microsoft.Extensions.Logging;
namespace Grynwald.MdDocs
{
internal static class Program
{
private static int Main(string[] args)
{
var parser = new Parser(opts =>
{
opts.CaseInsensitiveEnumValues = true;
opts.CaseSensitive = false;
opts.HelpWriter = Console.Out;
});
// Parser needs at least two option classes, otherwise it
// will not include the verb for the commands in the help output.
var success = parser
.ParseArguments<ApiReferenceOptions, CommandLineHelpOptions>(args)
.MapResult(
(ApiReferenceOptions opts) => OnApiReferenceCommand(GetLogger(opts), opts),
(CommandLineHelpOptions opts) => OnCommandLineHelpCommand(GetLogger(opts), opts),
(IEnumerable<Error> errors) => OnError(errors));
return success ? 0 : 1;
}
private static bool OnError(IEnumerable<Error> errors)
{
// if help or version was requests, the help/version was already
// written to the output by the parser.
// There errors can be ignored.
if (errors.All(e => e is HelpRequestedError || e is HelpVerbRequestedError || e is VersionRequestedError))
{
return true;
}
else
{
Console.Error.WriteLine("Invalid arguments.");
return false;
}
}
private static bool OnApiReferenceCommand(ILogger logger, ApiReferenceOptions opts)
{
var configurationProvider = GetConfigurationProvider(opts);
var command = new ApiReferenceCommand(logger, configurationProvider.GetApiReferenceConfiguration());
return command.Execute();
}
private static bool OnCommandLineHelpCommand(ILogger logger, CommandLineHelpOptions opts)
{
var configurationProvider = GetConfigurationProvider(opts);
var command = new CommandLineHelpCommand(logger, configurationProvider.GetCommandLineHelpConfiguration());
return command.Execute();
}
private static ILogger GetLogger(OptionsBase opts)
{
var loggerConfiguration = new SimpleConsoleLoggerConfiguration(
minimumLogLevel: opts.Verbose ? LogLevel.Debug : LogLevel.Information,
showCategoryName: false,
enabledColoredOutput: true);
return new SimpleConsoleLogger(loggerConfiguration, "");
}
private static ConfigurationProvider GetConfigurationProvider(OptionsBase commandlineParameters) =>
new ConfigurationProvider(commandlineParameters.ConfigurationFilePath ?? "", commandlineParameters);
}
}
| 38.082353 | 118 | 0.641335 | [
"MIT"
] | ap0llo/mddocs | src/MdDocs/Program.cs | 3,239 | C# |
/*
Copyright (c) 2013, 2014 Paolo Patierno
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Paolo Patierno - initial API and implementation and/or initial documentation
.NET Foundation and Contributors - nanoFramework support
*/
using nanoFramework.M2Mqtt.Exceptions;
using nanoFramework.M2Mqtt.Utility;
using System;
using System.Text;
namespace nanoFramework.M2Mqtt.Messages
{
/// <summary>
/// Class for PUBACK message from broker to client
/// </summary>
public class MqttMsgPuback : MqttMsgBase
{
/// <summary>
/// Return Code, v5.0 only
/// </summary>
public MqttReasonCode ReasonCode { get; set; }
/// <summary>
/// The Reason as a string, v5.0 only
/// </summary>
public string Reason { get; set; }
/// <summary>
/// Constructor
/// </summary>
public MqttMsgPuback()
{
Type = MqttMessageType.PublishAck;
}
/// <summary>
/// Returns the bytes that represents the current object.
/// </summary>
/// <param name="protocolVersion">MQTT protocol version</param>
/// <returns>An array of bytes that represents the current object.</returns>
public override byte[] GetBytes(MqttProtocolVersion protocolVersion)
{
int fixedHeaderSize;
int varHeaderSize = 0;
int remainingLength = 0;
byte[] buffer;
int indexPuback = 0;
int varHeaderPropSize = 0;
byte[] reason = null;
byte[] userProperties = null;
// message identifier
varHeaderSize += MESSAGE_ID_SIZE;
if (protocolVersion == MqttProtocolVersion.Version_5)
{
// Puback code
varHeaderSize += 1;
if (!string.IsNullOrEmpty(Reason))
{
reason = Encoding.UTF8.GetBytes(Reason);
// Check if we are over the Maximum size
if ((MaximumPacketSize > 0) && (reason.Length + varHeaderSize > MaximumPacketSize))
{
reason = null;
}
else
{
varHeaderPropSize += ENCODING_UTF8_SIZE + reason.Length;
}
}
if (UserProperties.Count > 0)
{
userProperties = EncodeDecodeHelper.EncodeUserProperties(UserProperties);
// Check if we are over the Maximum size
if ((MaximumPacketSize > 0) && (userProperties.Length + varHeaderSize > MaximumPacketSize))
{
userProperties = null;
}
else
{
varHeaderPropSize += userProperties.Length;
}
}
varHeaderSize += varHeaderPropSize + EncodeDecodeHelper.EncodeLength(varHeaderPropSize);
}
remainingLength += varHeaderSize;
// first byte of fixed header
fixedHeaderSize = 1;
int temp = remainingLength;
// increase fixed header size based on remaining length
// (each remaining length byte can encode until 128)
do
{
fixedHeaderSize++;
temp /= 128;
} while (temp > 0);
// allocate buffer for message
buffer = new byte[fixedHeaderSize + varHeaderSize];
// first fixed header byte
buffer[indexPuback++] = (byte)MqttMessageType.PublishAck << MSG_TYPE_OFFSET;
// encode remaining length
indexPuback = EncodeVariableByte(remainingLength, buffer, indexPuback);
// get message identifier
buffer[indexPuback++] = (byte)((MessageId >> 8) & 0x00FF); // MSB
buffer[indexPuback++] = (byte)(MessageId & 0x00FF); // LSB
// v5 specific
if (protocolVersion == MqttProtocolVersion.Version_5)
{
// ReasonCode
buffer[indexPuback++] = (byte)ReasonCode;
// Encode length and the properties
indexPuback = EncodeVariableByte(varHeaderPropSize, buffer, indexPuback);
if (reason != null)
{
EncodeDecodeHelper.EncodeUTF8FromBuffer(MqttProperty.ReasonString, reason, buffer, ref indexPuback);
}
if (userProperties != null)
{
Array.Copy(userProperties, 0, buffer, indexPuback, userProperties.Length);
}
}
return buffer;
}
/// <summary>
/// Parse bytes for a PUBACK message
/// </summary>
/// <param name="fixedHeaderFirstByte">First fixed header byte</param>
/// <param name="protocolVersion">MQTT Protocol Version</param>
/// <param name="channel">Channel connected to the broker</param>
/// <returns>PUBACK message instance</returns>
public static MqttMsgPuback Parse(byte fixedHeaderFirstByte, MqttProtocolVersion protocolVersion, IMqttNetworkChannel channel)
{
byte[] buffer;
int index = 0;
MqttMsgPuback msg = new MqttMsgPuback();
if ((protocolVersion == MqttProtocolVersion.Version_3_1_1) || (protocolVersion == MqttProtocolVersion.Version_5))
{
// [v3.1.1] check flag bits
if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PUBACK_FLAG_BITS)
{
throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
}
}
// get remaining length and allocate buffer
int remainingLength = DecodeVariableByte(channel);
buffer = new byte[remainingLength];
// read bytes from socket...
channel.Receive(buffer);
// message id
msg.MessageId = (ushort)((buffer[index++] << 8) & 0xFF00);
msg.MessageId |= (buffer[index++]);
if ((protocolVersion == MqttProtocolVersion.Version_5) && (index < buffer.Length))
{
msg.ReasonCode = (MqttReasonCode)buffer[index++];
// size of the properties
int propSize = EncodeDecodeHelper.GetPropertySize(buffer, ref index);
propSize += index;
MqttProperty prop;
while (propSize > index)
{
prop = (MqttProperty)buffer[index++];
switch (prop)
{
case MqttProperty.ReasonString:
// UTF8 encoded
msg.Reason = EncodeDecodeHelper.GetUTF8FromBuffer(buffer, ref index);
break;
case MqttProperty.UserProperty:
// UTF8 key value encoding, so 2 strings in a raw
string key = EncodeDecodeHelper.GetUTF8FromBuffer(buffer, ref index);
string value = EncodeDecodeHelper.GetUTF8FromBuffer(buffer, ref index);
msg.UserProperties.Add(new UserProperty(key, value));
break;
default:
// non supported property
index = propSize;
break;
}
}
}
return msg;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
#if DEBUG
return this.GetTraceString(
"PUBACK",
new object[] { "messageId" },
new object[] { MessageId });
#else
return base.ToString();
#endif
}
}
}
| 36.189873 | 134 | 0.530139 | [
"EPL-1.0"
] | aromaa/nanoFramework.m2mqtt | M2Mqtt/Messages/MqttMsgPuback.cs | 8,577 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.Azure.WebJobs
{
/// <summary>Provides extension methods for the <see cref="IBinder"/> interface.</summary>
public static class BinderExtensions
{
/// <summary>Binds the specified attribute.</summary>
/// <typeparam name="T">The type to which to bind.</typeparam>
/// <param name="binder">The binder to use to bind.</param>
/// <param name="attribute">The attribute to bind.</param>
/// <returns>The value bound.</returns>
public static T Bind<T>(this IBinder binder, Attribute attribute)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
return binder.BindAsync<T>(attribute).GetAwaiter().GetResult();
}
}
}
| 36.777778 | 111 | 0.629406 | [
"Apache-2.0"
] | alpaix/azure-jobs | src/Microsoft.Azure.WebJobs/BinderExtensions.cs | 995 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using NAudio.Utils;
namespace NAudioTests.WaveStreams
{
[TestFixture]
[Category("UnitTest")]
public class CircularBufferTests
{
[Test]
public void CircularBufferHasMaxLengthAndCount()
{
CircularBuffer circularBuffer = new CircularBuffer(1024);
Assert.AreEqual(1024, circularBuffer.MaxLength);
Assert.AreEqual(0, circularBuffer.Count);
}
[Test]
public void ReadFromEmptyBufferReturnsNothing()
{
CircularBuffer circularBuffer = new CircularBuffer(1024);
byte[] buffer = new byte[1024];
int read = circularBuffer.Read(buffer, 0, 1024);
Assert.AreEqual(0, read);
}
[Test]
public void CanWriteToBuffer()
{
CircularBuffer circularBuffer = new CircularBuffer(1024);
byte[] buffer = new byte[100];
circularBuffer.Write(buffer, 0, 100);
Assert.AreEqual(100, circularBuffer.Count);
circularBuffer.Write(buffer, 0, 50);
Assert.AreEqual(150, circularBuffer.Count);
}
[Test]
public void BufferReturnsAsMuchAsIsAvailable()
{
CircularBuffer circularBuffer = new CircularBuffer(1024);
byte[] buffer = new byte[100];
circularBuffer.Write(buffer, 0, 100);
Assert.AreEqual(100, circularBuffer.Count);
byte[] readBuffer = new byte[1000];
int read = circularBuffer.Read(readBuffer, 0, 1000);
Assert.AreEqual(100, read);
}
[Test]
public void RejectsTooMuchData()
{
CircularBuffer circularBuffer = new CircularBuffer(100);
byte[] buffer = new byte[200];
int written = circularBuffer.Write(buffer, 0, 200);
Assert.AreEqual(100, written, "Wrote the wrong amount");
}
[Test]
public void RejectsWhenFull()
{
CircularBuffer circularBuffer = new CircularBuffer(100);
byte[] buffer = new byte[200];
circularBuffer.Write(buffer, 0, 75);
int written = circularBuffer.Write(buffer, 0, 50);
Assert.AreEqual(25, written, "Wrote the wrong amount");
}
[Test]
public void RejectsWhenExactlyFull()
{
CircularBuffer circularBuffer = new CircularBuffer(100);
byte[] buffer = new byte[200];
circularBuffer.Write(buffer, 0, 100);
int written = circularBuffer.Write(buffer, 0, 50);
Assert.AreEqual(0, written, "Wrote the wrong amount");
}
[Test]
public void CanWritePastEnd()
{
CircularBuffer circularBuffer = new CircularBuffer(100);
byte[] buffer = new byte[200];
circularBuffer.Write(buffer, 0, 75);
Assert.AreEqual(75, circularBuffer.Count, "Initial count");
int read = circularBuffer.Read(buffer, 0, 75);
Assert.AreEqual(0, circularBuffer.Count, "Count after read");
Assert.AreEqual(75, read, "Bytes read");
// write wraps round
circularBuffer.Write(buffer, 0, 50);
Assert.AreEqual(50, circularBuffer.Count, "Count after wrap round");
// read wraps round
read = circularBuffer.Read(buffer, 0, 75);
Assert.AreEqual(50, read, "Bytes Read 2");
Assert.AreEqual(0, circularBuffer.Count, "Final Count");
}
[Test]
public void DataIntegrityTest()
{
byte[] numbers = new byte[256];
byte[] readBuffer = new byte[256];
for (int n = 0; n < 256; n++)
{
numbers[n] = (byte)n;
}
CircularBuffer circularBuffer = new CircularBuffer(300);
circularBuffer.Write(numbers, 0, 200);
Array.Clear(readBuffer, 0, readBuffer.Length);
int read = circularBuffer.Read(readBuffer, 0, 200);
Assert.AreEqual(200, read);
CheckBuffer(readBuffer, 0, read);
// now write past the end
circularBuffer.Write(numbers, 0, 200);
Array.Clear(readBuffer, 0, readBuffer.Length);
// now read past the end
read = circularBuffer.Read(readBuffer, 0, 200);
Assert.AreEqual(200, read);
CheckBuffer(readBuffer, 0, read);
}
public void CheckBuffer(byte[] buffer, int startNumber, int length)
{
for (int n = 0; n < length; n++)
{
Assert.AreEqual(startNumber + n, buffer[n], "Byte mismatch at offset {0}", n);
}
}
}
}
| 35.217391 | 94 | 0.561111 | [
"MIT"
] | skor98/DtWPF | speechKit/NAudio-master/NAudioTests/WaveStreams/CircularBufferTests.cs | 4,862 | C# |
//
// generic.cs: Generics support
//
// Authors: Martin Baulig (martin@ximian.com)
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
#if STATIC
using MetaType = IKVM.Reflection.Type;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using MetaType = System.Type;
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
public enum Variance
{
//
// Don't add or modify internal values, they are used as -/+ calculation signs
//
None = 0,
Covariant = 1,
Contravariant = -1
}
[Flags]
public enum SpecialConstraint
{
None = 0,
Constructor = 1 << 2,
Class = 1 << 3,
Struct = 1 << 4
}
public class SpecialContraintExpr : FullNamedExpression
{
public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
{
this.loc = loc;
this.Constraint = constraint;
}
public SpecialConstraint Constraint { get; private set; }
protected override Expression DoResolve (ResolveContext rc)
{
throw new NotImplementedException ();
}
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
{
throw new NotImplementedException ();
}
}
//
// A set of parsed constraints for a type parameter
//
public class Constraints
{
SimpleMemberName tparam;
List<FullNamedExpression> constraints;
Location loc;
bool resolved;
bool resolving;
public IEnumerable<FullNamedExpression> ConstraintExpressions {
get {
return constraints;
}
}
public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
{
this.tparam = tparam;
this.constraints = constraints;
this.loc = loc;
}
#region Properties
public List<FullNamedExpression> TypeExpressions {
get {
return constraints;
}
}
public Location Location {
get {
return loc;
}
}
public SimpleMemberName TypeParameter {
get {
return tparam;
}
}
#endregion
public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
{
if (spec.HasSpecialClass && bb.IsStruct) {
context.Module.Compiler.Report.Error (455, loc,
"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
spec.Name, "class", bb.GetSignatureForError ());
return false;
}
return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
}
static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
{
if (ba == bb)
return true;
if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
return true;
Error_ConflictingConstraints (context, spec, ba, bb, loc);
return false;
}
public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
{
context.Module.Compiler.Report.Error (455, loc,
"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
}
public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
{
foreach (var c in constraints) {
if (c == null)
continue;
var t = c.Type;
if (t == null)
continue;
if (obsoleteCheck) {
ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
if (obsolete_attr != null)
AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
}
ConstraintChecker.Check (context, t, c.Location);
}
}
//
// Resolve the constraints types with only possible early checks, return
// value `false' is reserved for recursive failure
//
public bool Resolve (IMemberContext context, TypeParameter tp)
{
if (resolved)
return true;
if (resolving)
return false;
resolving = true;
var spec = tp.Type;
List<TypeParameterSpec> tparam_types = null;
bool iface_found = false;
spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
for (int i = 0; i < constraints.Count; ++i) {
var constraint = constraints[i];
if (constraint is SpecialContraintExpr) {
spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
if (spec.HasSpecialStruct)
spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
// Set to null as it does not have a type
constraints[i] = null;
continue;
}
var type = constraint.ResolveAsType (context);
if (type == null)
continue;
if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
context.Module.Compiler.Report.Error (1968, constraint.Location,
"A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
continue;
}
if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
context.Module.Compiler.Report.Error (703, loc,
"Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
type.GetSignatureForError (), context.GetSignatureForError ());
}
if (type.IsInterface) {
if (!spec.AddInterface (type)) {
context.Module.Compiler.Report.Error (405, constraint.Location,
"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
}
iface_found = true;
continue;
}
var constraint_tp = type as TypeParameterSpec;
if (constraint_tp != null) {
if (tparam_types == null) {
tparam_types = new List<TypeParameterSpec> (2);
} else if (tparam_types.Contains (constraint_tp)) {
context.Module.Compiler.Report.Error (405, constraint.Location,
"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
continue;
}
//
// Checks whether each generic method parameter constraint type
// is valid with respect to T
//
if (tp.IsMethodTypeParameter) {
TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
}
var tp_def = constraint_tp.MemberDefinition as TypeParameter;
if (tp_def != null && !tp_def.ResolveConstraints (context)) {
context.Module.Compiler.Report.Error (454, constraint.Location,
"Circular constraint dependency involving `{0}' and `{1}'",
constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
continue;
}
//
// Checks whether there are no conflicts between type parameter constraints
//
// class Foo<T, U>
// where T : A
// where U : B, T
//
// A and B are not convertible and only 1 class constraint is allowed
//
if (constraint_tp.HasTypeConstraint) {
if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
continue;
} else {
for (int ii = 0; ii < tparam_types.Count; ++ii) {
if (!tparam_types[ii].HasTypeConstraint)
continue;
if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
break;
}
}
}
if (constraint_tp.HasSpecialStruct) {
context.Module.Compiler.Report.Error (456, constraint.Location,
"Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
continue;
}
tparam_types.Add (constraint_tp);
continue;
}
if (iface_found || spec.HasTypeConstraint) {
context.Module.Compiler.Report.Error (406, constraint.Location,
"The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
type.GetSignatureForError ());
}
if (spec.HasSpecialStruct || spec.HasSpecialClass) {
context.Module.Compiler.Report.Error (450, constraint.Location,
"`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
type.GetSignatureForError ());
}
switch (type.BuiltinType) {
case BuiltinTypeSpec.Type.Array:
case BuiltinTypeSpec.Type.Delegate:
case BuiltinTypeSpec.Type.MulticastDelegate:
case BuiltinTypeSpec.Type.Enum:
case BuiltinTypeSpec.Type.ValueType:
case BuiltinTypeSpec.Type.Object:
context.Module.Compiler.Report.Error (702, constraint.Location,
"A constraint cannot be special class `{0}'", type.GetSignatureForError ());
continue;
case BuiltinTypeSpec.Type.Dynamic:
context.Module.Compiler.Report.Error (1967, constraint.Location,
"A constraint cannot be the dynamic type");
continue;
}
if (type.IsSealed || !type.IsClass) {
context.Module.Compiler.Report.Error (701, loc,
"`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
TypeManager.CSharpName (type));
continue;
}
if (type.IsStatic) {
context.Module.Compiler.Report.Error (717, constraint.Location,
"`{0}' is not a valid constraint. Static classes cannot be used as constraints",
type.GetSignatureForError ());
}
spec.BaseType = type;
}
if (tparam_types != null)
spec.TypeArguments = tparam_types.ToArray ();
resolving = false;
resolved = true;
return true;
}
public void VerifyClsCompliance (Report report)
{
foreach (var c in constraints)
{
if (c == null)
continue;
if (!c.Type.IsCLSCompliant ()) {
report.SymbolRelatedToPreviousError (c.Type);
report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
c.Type.GetSignatureForError ());
}
}
}
}
//
// A type parameter for a generic type or generic method definition
//
public class TypeParameter : MemberCore, ITypeDefinition
{
static readonly string[] attribute_target = new string [] { "type parameter" };
Constraints constraints;
GenericTypeParameterBuilder builder;
TypeParameterSpec spec;
public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
: base (null, name, attrs)
{
this.constraints = constraints;
this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
}
//
// Used by parser
//
public TypeParameter (MemberName name, Attributes attrs, Variance variance)
: base (null, name, attrs)
{
this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, variance, null);
}
public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
: base (null, name, attrs)
{
this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
BaseType = spec.BaseType,
InterfacesDefined = spec.InterfacesDefined,
TypeArguments = spec.TypeArguments
};
}
#region Properties
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.GenericParameter;
}
}
public Constraints Constraints {
get {
return constraints;
}
set {
constraints = value;
}
}
public IAssemblyDefinition DeclaringAssembly {
get {
return Module.DeclaringAssembly;
}
}
public override string DocCommentHeader {
get {
throw new InvalidOperationException (
"Unexpected attempt to get doc comment from " + this.GetType ());
}
}
bool ITypeDefinition.IsPartial {
get {
return false;
}
}
public bool IsMethodTypeParameter {
get {
return spec.IsMethodOwned;
}
}
public string Name {
get {
return MemberName.Name;
}
}
public string Namespace {
get {
return null;
}
}
public TypeParameterSpec Type {
get {
return spec;
}
}
public int TypeParametersCount {
get {
return 0;
}
}
public TypeParameterSpec[] TypeParameters {
get {
return null;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_target;
}
}
public Variance Variance {
get {
return spec.Variance;
}
}
#endregion
//
// This is called for each part of a partial generic type definition.
//
// If partial type parameters constraints are not null and we don't
// already have constraints they become our constraints. If we already
// have constraints, we must check that they're the same.
//
public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
{
if (builder == null)
throw new InvalidOperationException ();
var new_constraints = tp.constraints;
if (new_constraints == null)
return true;
// TODO: could create spec only
//tp.Define (null, -1, part.Definition);
tp.spec.DeclaringType = part.Definition;
if (!tp.ResolveConstraints (part))
return false;
if (constraints != null)
return spec.HasSameConstraintsDefinition (tp.Type);
// Copy constraint from resolved part to partial container
spec.SpecialConstraint = tp.spec.SpecialConstraint;
spec.InterfacesDefined = tp.spec.InterfacesDefined;
spec.TypeArguments = tp.spec.TypeArguments;
spec.BaseType = tp.spec.BaseType;
return true;
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
}
public void CheckGenericConstraints (bool obsoleteCheck)
{
if (constraints != null)
constraints.CheckGenericConstraints (this, obsoleteCheck);
}
public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
{
return new TypeParameter (spec, declaringSpec, MemberName, null);
}
public override bool Define ()
{
return true;
}
//
// This is the first method which is called during the resolving
// process; we're called immediately after creating the type parameters
// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
// MethodBuilder).
//
public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
{
if (builder != null)
throw new InternalErrorException ();
// Needed to get compiler reference
this.Parent = parent;
this.builder = type;
spec.DeclaringType = declaringType;
spec.SetMetaInfo (type);
}
public void EmitConstraints (GenericTypeParameterBuilder builder)
{
var attr = GenericParameterAttributes.None;
if (spec.Variance == Variance.Contravariant)
attr |= GenericParameterAttributes.Contravariant;
else if (spec.Variance == Variance.Covariant)
attr |= GenericParameterAttributes.Covariant;
if (spec.HasSpecialClass)
attr |= GenericParameterAttributes.ReferenceTypeConstraint;
else if (spec.HasSpecialStruct)
attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
if (spec.HasSpecialConstructor)
attr |= GenericParameterAttributes.DefaultConstructorConstraint;
if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
if (spec.InterfacesDefined != null)
builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
if (spec.TypeArguments != null)
builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
builder.SetGenericParameterAttributes (attr);
}
public override void Emit ()
{
EmitConstraints (builder);
if (OptAttributes != null)
OptAttributes.Emit ();
base.Emit ();
}
public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
{
Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
string gtype_variance;
switch (expected) {
case Variance.Contravariant: gtype_variance = "contravariantly"; break;
case Variance.Covariant: gtype_variance = "covariantly"; break;
default: gtype_variance = "invariantly"; break;
}
Delegate d = mc as Delegate;
string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
Report.Error (1961, Location,
"The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
}
public TypeSpec GetAttributeCoClass ()
{
return null;
}
public string GetAttributeDefaultMember ()
{
throw new NotSupportedException ();
}
public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
{
throw new NotSupportedException ();
}
public override string GetSignatureForDocumentation ()
{
throw new NotImplementedException ();
}
public override string GetSignatureForError ()
{
return MemberName.Name;
}
bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
{
return spec.MemberDefinition.DeclaringAssembly == assembly;
}
public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
{
throw new NotSupportedException ("Not supported for compiled definition");
}
//
// Resolves all type parameter constraints
//
public bool ResolveConstraints (IMemberContext context)
{
if (constraints != null)
return constraints.Resolve (context, this);
if (spec.BaseType == null)
spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
return true;
}
public override bool IsClsComplianceRequired ()
{
return false;
}
public new void VerifyClsCompliance ()
{
if (constraints != null)
constraints.VerifyClsCompliance (Report);
}
public void WarningParentNameConflict (TypeParameter conflict)
{
conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
conflict.Report.Warning (693, 3, Location,
"Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
}
}
[System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
public class TypeParameterSpec : TypeSpec
{
public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
Variance variance;
SpecialConstraint spec;
int tp_pos;
TypeSpec[] targs;
TypeSpec[] ifaces_defined;
//
// Creates type owned type parameter
//
public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
: base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
{
this.variance = variance;
this.spec = spec;
state &= ~StateFlags.Obsolete_Undetected;
tp_pos = index;
}
//
// Creates method owned type parameter
//
public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
: this (null, index, definition, spec, variance, info)
{
}
#region Properties
public int DeclaredPosition {
get {
return tp_pos;
}
set {
tp_pos = value;
}
}
public bool HasSpecialConstructor {
get {
return (spec & SpecialConstraint.Constructor) != 0;
}
}
public bool HasSpecialClass {
get {
return (spec & SpecialConstraint.Class) != 0;
}
}
public bool HasSpecialStruct {
get {
return (spec & SpecialConstraint.Struct) != 0;
}
}
public bool HasAnyTypeConstraint {
get {
return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
}
}
public bool HasTypeConstraint {
get {
var bt = BaseType.BuiltinType;
return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
}
}
public override IList<TypeSpec> Interfaces {
get {
if ((state & StateFlags.InterfacesExpanded) == 0) {
if (ifaces != null) {
for (int i = 0; i < ifaces.Count; ++i ) {
var iface_type = ifaces[i];
if (iface_type.Interfaces != null) {
if (ifaces_defined == null)
ifaces_defined = ifaces.ToArray ();
for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
var ii_iface_type = iface_type.Interfaces [ii];
AddInterface (ii_iface_type);
}
}
}
}
if (ifaces_defined == null)
ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
state |= StateFlags.InterfacesExpanded;
}
return ifaces;
}
}
//
// Unexpanded interfaces list
//
public TypeSpec[] InterfacesDefined {
get {
if (ifaces_defined == null) {
if (ifaces == null)
return null;
ifaces_defined = ifaces.ToArray ();
}
return ifaces_defined.Length == 0 ? null : ifaces_defined;
}
set {
ifaces_defined = value;
if (value != null && value.Length != 0)
ifaces = value;
}
}
public bool IsConstrained {
get {
return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
}
}
//
// Returns whether the type parameter is known to be a reference type
//
public new bool IsReferenceType {
get {
if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
return (spec & SpecialConstraint.Class) != 0;
//
// Full check is needed (see IsValueType for details)
//
if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
return true;
if (targs != null) {
foreach (var ta in targs) {
//
// Secondary special constraints are ignored (I am not sure why)
//
var tp = ta as TypeParameterSpec;
if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
continue;
if (TypeSpec.IsReferenceType (ta))
return true;
}
}
return false;
}
}
//
// Returns whether the type parameter is known to be a value type
//
public new bool IsValueType {
get {
//
// Even if structs/enums cannot be used directly as constraints
// they can apear as constraint type when inheriting base constraint
// which has dependant type parameter constraint which has been
// inflated using value type
//
// class A : B<int> { override void Foo<U> () {} }
// class B<T> { virtual void Foo<U> () where U : T {} }
//
if (HasSpecialStruct)
return true;
if (targs != null) {
foreach (var ta in targs) {
if (TypeSpec.IsValueType (ta))
return true;
}
}
return false;
}
}
public override string Name {
get {
return definition.Name;
}
}
public bool IsMethodOwned {
get {
return DeclaringType == null;
}
}
public SpecialConstraint SpecialConstraint {
get {
return spec;
}
set {
spec = value;
}
}
//
// Types used to inflate the generic type
//
public new TypeSpec[] TypeArguments {
get {
return targs;
}
set {
targs = value;
}
}
public Variance Variance {
get {
return variance;
}
}
#endregion
public string DisplayDebugInfo ()
{
var s = GetSignatureForError ();
return IsMethodOwned ? s + "!!" : s + "!";
}
//
// Finds effective base class. The effective base class is always a class-type
//
public TypeSpec GetEffectiveBase ()
{
if (HasSpecialStruct)
return BaseType;
//
// If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
//
if (BaseType != null && targs == null) {
//
// If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
//
// LAMESPEC: Is System.ValueType always the most specific base type in this case?
//
// Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
// are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
//
return BaseType.IsStruct ? BaseType.BaseType : BaseType;
}
var types = targs;
if (HasTypeConstraint) {
Array.Resize (ref types, types.Length + 1);
for (int i = 0; i < types.Length - 1; ++i) {
types[i] = types[i].BaseType;
}
types[types.Length - 1] = BaseType;
} else {
types = types.Select (l => l.BaseType).ToArray ();
}
if (types != null)
return Convert.FindMostEncompassedType (types);
return BaseType;
}
public override string GetSignatureForDocumentation ()
{
var prefix = IsMethodOwned ? "``" : "`";
return prefix + DeclaredPosition;
}
public override string GetSignatureForError ()
{
return Name;
}
//
// Constraints have to match by definition but not position, used by
// partial classes or methods
//
public bool HasSameConstraintsDefinition (TypeParameterSpec other)
{
if (spec != other.spec)
return false;
if (BaseType != other.BaseType)
return false;
if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
return false;
if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
return false;
return true;
}
//
// Constraints have to match by using same set of types, used by
// implicit interface implementation
//
public bool HasSameConstraintsImplementation (TypeParameterSpec other)
{
if (spec != other.spec)
return false;
//
// It can be same base type or inflated type parameter
//
// interface I<T> { void Foo<U> where U : T; }
// class A : I<int> { void Foo<X> where X : int {} }
//
bool found;
if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
if (other.targs == null)
return false;
found = false;
foreach (var otarg in other.targs) {
if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
found = true;
break;
}
}
if (!found)
return false;
}
// Check interfaces implementation -> definition
if (InterfacesDefined != null) {
//
// Iterate over inflated interfaces
//
foreach (var iface in Interfaces) {
found = false;
if (other.InterfacesDefined != null) {
foreach (var oiface in other.Interfaces) {
if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
found = true;
break;
}
}
}
if (found)
continue;
if (other.targs != null) {
foreach (var otarg in other.targs) {
if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
found = true;
break;
}
}
}
if (!found)
return false;
}
}
// Check interfaces implementation <- definition
if (other.InterfacesDefined != null) {
if (InterfacesDefined == null)
return false;
//
// Iterate over inflated interfaces
//
foreach (var oiface in other.Interfaces) {
found = false;
foreach (var iface in Interfaces) {
if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
found = true;
break;
}
}
if (!found)
return false;
}
}
// Check type parameters implementation -> definition
if (targs != null) {
if (other.targs == null)
return false;
foreach (var targ in targs) {
found = false;
foreach (var otarg in other.targs) {
if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
found = true;
break;
}
}
if (!found)
return false;
}
}
// Check type parameters implementation <- definition
if (other.targs != null) {
foreach (var otarg in other.targs) {
// Ignore inflated type arguments, were checked above
if (!otarg.IsGenericParameter)
continue;
if (targs == null)
return false;
found = false;
foreach (var targ in targs) {
if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
found = true;
break;
}
}
if (!found)
return false;
}
}
return true;
}
public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
{
return InflateConstraints (tparams, l => l, inflator);
}
public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
{
TypeParameterSpec[] constraints = null;
TypeParameterInflator? inflator = null;
for (int i = 0; i < tparams.Length; ++i) {
var tp = tparams[i];
if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
if (constraints == null) {
constraints = new TypeParameterSpec[tparams.Length];
Array.Copy (tparams, constraints, constraints.Length);
}
//
// Using a factory to avoid possibly expensive inflator build up
//
if (inflator == null)
inflator = inflatorFactory (arg);
constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
}
}
if (constraints == null)
constraints = tparams;
return constraints;
}
public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
{
tps.BaseType = inflator.Inflate (BaseType);
if (ifaces != null) {
tps.ifaces = new List<TypeSpec> (ifaces.Count);
for (int i = 0; i < ifaces.Count; ++i)
tps.ifaces.Add (inflator.Inflate (ifaces[i]));
}
if (targs != null) {
tps.targs = new TypeSpec[targs.Length];
for (int i = 0; i < targs.Length; ++i)
tps.targs[i] = inflator.Inflate (targs[i]);
}
}
public override MemberSpec InflateMember (TypeParameterInflator inflator)
{
var tps = (TypeParameterSpec) MemberwiseClone ();
InflateConstraints (inflator, tps);
return tps;
}
//
// Populates type parameter members using type parameter constraints
// The trick here is to be called late enough but not too late to
// populate member cache with all members from other types
//
protected override void InitializeMemberCache (bool onlyTypes)
{
cache = new MemberCache ();
//
// For a type parameter the membercache is the union of the sets of members of the types
// specified as a primary constraint or secondary constraint
//
if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
cache.AddBaseType (BaseType);
if (ifaces != null) {
foreach (var iface_type in Interfaces) {
cache.AddInterface (iface_type);
}
}
if (targs != null) {
foreach (var ta in targs) {
var b_type = ta.BaseType;
if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
cache.AddBaseType (b_type);
if (ta.Interfaces != null) {
foreach (var iface_type in ta.Interfaces) {
cache.AddInterface (iface_type);
}
}
}
}
}
public bool IsConvertibleToInterface (TypeSpec iface)
{
if (Interfaces != null) {
foreach (var t in Interfaces) {
if (t == iface)
return true;
}
}
if (TypeArguments != null) {
foreach (var t in TypeArguments) {
if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
return true;
}
}
return false;
}
public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
{
var tps = md.TypeParameters;
for (int i = 0; i < md.TypeParametersCount; ++i) {
if (tps[i].HasAnyTypeConstraint) {
return true;
}
}
return false;
}
public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
{
var tps = md.TypeParameters;
for (int i = 0; i < md.TypeParametersCount; ++i) {
if (tps[i].IsConstrained) {
return true;
}
}
return false;
}
public override TypeSpec Mutate (TypeParameterMutator mutator)
{
return mutator.Mutate (this);
}
}
public struct TypeParameterInflator
{
readonly TypeSpec type;
readonly TypeParameterSpec[] tparams;
readonly TypeSpec[] targs;
readonly IModuleContext context;
public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
: this (nested.context, type, nested.tparams, nested.targs)
{
}
public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
{
if (tparams.Length != targs.Length)
throw new ArgumentException ("Invalid arguments");
this.context = context;
this.tparams = tparams;
this.targs = targs;
this.type = type;
}
#region Properties
public IModuleContext Context {
get {
return context;
}
}
public TypeSpec TypeInstance {
get {
return type;
}
}
//
// Type parameters to inflate
//
public TypeParameterSpec[] TypeParameters {
get {
return tparams;
}
}
#endregion
public TypeSpec Inflate (TypeSpec type)
{
var tp = type as TypeParameterSpec;
if (tp != null)
return Inflate (tp);
var ac = type as ArrayContainer;
if (ac != null) {
var et = Inflate (ac.Element);
if (et != ac.Element)
return ArrayContainer.MakeType (context.Module, et, ac.Rank);
return ac;
}
//
// When inflating a nested type, inflate its parent first
// in case it's using same type parameters (was inflated within the type)
//
TypeSpec[] targs;
int i = 0;
if (type.IsNested) {
var parent = Inflate (type.DeclaringType);
//
// Keep the inflated type arguments
//
targs = type.TypeArguments;
//
// When inflating imported nested type used inside same declaring type, we get TypeSpec
// because the import cache helps us to catch it. However, that means we have to look at
// type definition to get type argument (they are in fact type parameter in this case)
//
if (targs.Length == 0 && type.Arity > 0)
targs = type.MemberDefinition.TypeParameters;
//
// Parent was inflated, find the same type on inflated type
// to use same cache for nested types on same generic parent
//
type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
//
// Handle the tricky case where parent shares local type arguments
// which means inflating inflated type
//
// class Test<T> {
// public static Nested<T> Foo () { return null; }
//
// public class Nested<U> {}
// }
//
// return type of Test<string>.Foo() has to be Test<string>.Nested<string>
//
if (targs.Length > 0) {
var inflated_targs = new TypeSpec[targs.Length];
for (; i < targs.Length; ++i)
inflated_targs[i] = Inflate (targs[i]);
type = type.MakeGenericType (context, inflated_targs);
}
return type;
}
// Nothing to do for non-generic type
if (type.Arity == 0)
return type;
targs = new TypeSpec[type.Arity];
//
// Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
//
if (type is InflatedTypeSpec) {
for (; i < targs.Length; ++i)
targs[i] = Inflate (type.TypeArguments[i]);
type = type.GetDefinition ();
} else {
//
// Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
//
var args = type.MemberDefinition.TypeParameters;
foreach (var ds_tp in args)
targs[i++] = Inflate (ds_tp);
}
return type.MakeGenericType (context, targs);
}
public TypeSpec Inflate (TypeParameterSpec tp)
{
for (int i = 0; i < tparams.Length; ++i)
if (tparams [i] == tp)
return targs[i];
// This can happen when inflating nested types
// without type arguments specified
return tp;
}
}
//
// Before emitting any code we have to change all MVAR references to VAR
// when the method is of generic type and has hoisted variables
//
public class TypeParameterMutator
{
readonly TypeParameters mvar;
readonly TypeParameters var;
Dictionary<TypeSpec, TypeSpec> mutated_typespec;
public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
{
if (mvar.Count != var.Count)
throw new ArgumentException ();
this.mvar = mvar;
this.var = var;
}
#region Properties
public TypeParameters MethodTypeParameters {
get {
return mvar;
}
}
#endregion
public static TypeSpec GetMemberDeclaringType (TypeSpec type)
{
if (type is InflatedTypeSpec) {
if (type.DeclaringType == null)
return type.GetDefinition ();
var parent = GetMemberDeclaringType (type.DeclaringType);
type = MemberCache.GetMember<TypeSpec> (parent, type);
}
return type;
}
public TypeSpec Mutate (TypeSpec ts)
{
TypeSpec value;
if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
return value;
value = ts.Mutate (this);
if (mutated_typespec == null)
mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
mutated_typespec.Add (ts, value);
return value;
}
public TypeParameterSpec Mutate (TypeParameterSpec tp)
{
for (int i = 0; i < mvar.Count; ++i) {
if (mvar[i].Type == tp)
return var[i].Type;
}
return tp;
}
public TypeSpec[] Mutate (TypeSpec[] targs)
{
TypeSpec[] mutated = new TypeSpec[targs.Length];
bool changed = false;
for (int i = 0; i < targs.Length; ++i) {
mutated[i] = Mutate (targs[i]);
changed |= targs[i] != mutated[i];
}
return changed ? mutated : targs;
}
}
/// <summary>
/// A TypeExpr which already resolved to a type parameter.
/// </summary>
public class TypeParameterExpr : TypeExpression
{
public TypeParameterExpr (TypeParameter type_parameter, Location loc)
: base (type_parameter.Type, loc)
{
this.eclass = ExprClass.TypeParameter;
}
}
public class InflatedTypeSpec : TypeSpec
{
TypeSpec[] targs;
TypeParameterSpec[] constraints;
readonly TypeSpec open_type;
readonly IModuleContext context;
public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
: base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
{
if (targs == null)
throw new ArgumentNullException ("targs");
this.state &= ~SharedStateFlags;
this.state |= (openType.state & SharedStateFlags);
this.context = context;
this.open_type = openType;
this.targs = targs;
foreach (var arg in targs) {
if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
state |= StateFlags.HasDynamicElement;
break;
}
}
if (open_type.Kind == MemberKind.MissingType)
MemberCache = MemberCache.Empty;
if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
state |= StateFlags.ConstraintsChecked;
}
#region Properties
public override TypeSpec BaseType {
get {
if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
InitializeMemberCache (true);
return base.BaseType;
}
}
//
// Inflated type parameters with constraints array, mapping with type arguments is based on index
//
public TypeParameterSpec[] Constraints {
get {
if (constraints == null) {
constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
}
return constraints;
}
}
//
// Used to cache expensive constraints validation on constructed types
//
public bool HasConstraintsChecked {
get {
return (state & StateFlags.ConstraintsChecked) != 0;
}
set {
state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
}
}
public override IList<TypeSpec> Interfaces {
get {
if (cache == null)
InitializeMemberCache (true);
return base.Interfaces;
}
}
public override bool IsExpressionTreeType {
get {
return (open_type.state & StateFlags.InflatedExpressionType) != 0;
}
}
public override bool IsGenericIterateInterface {
get {
return (open_type.state & StateFlags.GenericIterateInterface) != 0;
}
}
public override bool IsGenericTask {
get {
return (open_type.state & StateFlags.GenericTask) != 0;
}
}
public override bool IsNullableType {
get {
return (open_type.state & StateFlags.InflatedNullableType) != 0;
}
}
//
// Types used to inflate the generic type
//
public override TypeSpec[] TypeArguments {
get {
return targs;
}
}
#endregion
public static bool ContainsTypeParameter (TypeSpec type)
{
if (type.Kind == MemberKind.TypeParameter)
return true;
var element_container = type as ElementTypeSpec;
if (element_container != null)
return ContainsTypeParameter (element_container.Element);
foreach (var t in type.TypeArguments) {
if (ContainsTypeParameter (t)) {
return true;
}
}
return false;
}
TypeParameterInflator CreateLocalInflator (IModuleContext context)
{
TypeParameterSpec[] tparams_full;
TypeSpec[] targs_full = targs;
if (IsNested) {
//
// Special case is needed when we are inflating an open type (nested type definition)
// on inflated parent. Consider following case
//
// Foo<T>.Bar<U> => Foo<string>.Bar<U>
//
// Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
//
List<TypeSpec> merged_targs = null;
List<TypeParameterSpec> merged_tparams = null;
var type = DeclaringType;
do {
if (type.TypeArguments.Length > 0) {
if (merged_targs == null) {
merged_targs = new List<TypeSpec> ();
merged_tparams = new List<TypeParameterSpec> ();
if (targs.Length > 0) {
merged_targs.AddRange (targs);
merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
}
}
merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
merged_targs.AddRange (type.TypeArguments);
}
type = type.DeclaringType;
} while (type != null);
if (merged_targs != null) {
// Type arguments are not in the right order but it should not matter in this case
targs_full = merged_targs.ToArray ();
tparams_full = merged_tparams.ToArray ();
} else if (targs.Length == 0) {
tparams_full = TypeParameterSpec.EmptyTypes;
} else {
tparams_full = open_type.MemberDefinition.TypeParameters;
}
} else if (targs.Length == 0) {
tparams_full = TypeParameterSpec.EmptyTypes;
} else {
tparams_full = open_type.MemberDefinition.TypeParameters;
}
return new TypeParameterInflator (context, this, tparams_full, targs_full);
}
MetaType CreateMetaInfo (TypeParameterMutator mutator)
{
//
// Converts nested type arguments into right order
// Foo<string, bool>.Bar<int> => string, bool, int
//
var all = new List<MetaType> ();
TypeSpec type = this;
TypeSpec definition = type;
do {
if (type.GetDefinition().IsGeneric) {
all.InsertRange (0,
type.TypeArguments != TypeSpec.EmptyTypes ?
type.TypeArguments.Select (l => l.GetMetaInfo ()) :
type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
}
definition = definition.GetDefinition ();
type = type.DeclaringType;
} while (type != null);
return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
}
public override ObsoleteAttribute GetAttributeObsolete ()
{
return open_type.GetAttributeObsolete ();
}
protected override bool IsNotCLSCompliant (out bool attrValue)
{
if (base.IsNotCLSCompliant (out attrValue))
return true;
foreach (var ta in TypeArguments) {
if (ta.MemberDefinition.CLSAttributeValue == false)
return true;
}
return false;
}
public override TypeSpec GetDefinition ()
{
return open_type;
}
public override MetaType GetMetaInfo ()
{
if (info == null)
info = CreateMetaInfo (null);
return info;
}
public override string GetSignatureForError ()
{
if (IsNullableType)
return targs[0].GetSignatureForError () + "?";
return base.GetSignatureForError ();
}
protected override string GetTypeNameSignature ()
{
if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
return null;
return "<" + TypeManager.CSharpName (targs) + ">";
}
public bool HasDynamicArgument ()
{
for (int i = 0; i < targs.Length; ++i) {
var item = targs[i];
if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return true;
if (item is InflatedTypeSpec) {
if (((InflatedTypeSpec) item).HasDynamicArgument ())
return true;
continue;
}
if (item.IsArray) {
while (item.IsArray) {
item = ((ArrayContainer) item).Element;
}
if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return true;
}
}
return false;
}
protected override void InitializeMemberCache (bool onlyTypes)
{
if (cache == null) {
var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
// Surprisingly, calling MemberCache on open type could meantime create cache on this type
// for imported type parameter constraints referencing nested type of this declaration
if (cache == null)
cache = new MemberCache (open_cache);
}
var inflator = CreateLocalInflator (context);
//
// Two stage inflate due to possible nested types recursive
// references
//
// class A<T> {
// B b;
// class B {
// T Value;
// }
// }
//
// When resolving type of `b' members of `B' cannot be
// inflated because are not yet available in membercache
//
if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
open_type.MemberCacheTypes.InflateTypes (cache, inflator);
//
// Inflate any implemented interfaces
//
if (open_type.Interfaces != null) {
ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
foreach (var iface in open_type.Interfaces) {
var iface_inflated = inflator.Inflate (iface);
if (iface_inflated == null)
continue;
AddInterface (iface_inflated);
}
}
//
// Handles the tricky case of recursive nested base generic type
//
// class A<T> : Base<A<T>.Nested> {
// class Nested {}
// }
//
// When inflating A<T>. base type is not yet known, secondary
// inflation is required (not common case) once base scope
// is known
//
if (open_type.BaseType == null) {
if (IsClass)
state |= StateFlags.PendingBaseTypeInflate;
} else {
BaseType = inflator.Inflate (open_type.BaseType);
}
} else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
//
// It can happen when resolving base type without being defined
// which is not allowed to happen and will always lead to an error
//
// class B { class N {} }
// class A<T> : A<B.N> {}
//
if (open_type.BaseType == null)
return;
BaseType = inflator.Inflate (open_type.BaseType);
state &= ~StateFlags.PendingBaseTypeInflate;
}
if (onlyTypes) {
state |= StateFlags.PendingMemberCacheMembers;
return;
}
var tc = open_type.MemberDefinition as TypeDefinition;
if (tc != null && !tc.HasMembersDefined) {
//
// Inflating MemberCache with undefined members
//
return;
}
if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
BaseType = inflator.Inflate (open_type.BaseType);
state &= ~StateFlags.PendingBaseTypeInflate;
}
state &= ~StateFlags.PendingMemberCacheMembers;
open_type.MemberCache.InflateMembers (cache, open_type, inflator);
}
public override TypeSpec Mutate (TypeParameterMutator mutator)
{
var targs = TypeArguments;
if (targs != null)
targs = mutator.Mutate (targs);
var decl = DeclaringType;
if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
decl = mutator.Mutate (decl);
if (targs == TypeArguments && decl == DeclaringType)
return this;
var mutated = (InflatedTypeSpec) MemberwiseClone ();
if (decl != DeclaringType) {
// Gets back MethodInfo in case of metaInfo was inflated
//mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
mutated.declaringType = decl;
mutated.state |= StateFlags.PendingMetaInflate;
}
if (targs != null) {
mutated.targs = targs;
mutated.info = null;
}
return mutated;
}
}
//
// Tracks the type arguments when instantiating a generic type. It's used
// by both type arguments and type parameters
//
public class TypeArguments
{
List<FullNamedExpression> args;
TypeSpec[] atypes;
public List<FullNamedExpression> Args {
get { return this.args; }
}
public TypeArguments (params FullNamedExpression[] types)
{
this.args = new List<FullNamedExpression> (types);
}
public void Add (FullNamedExpression type)
{
args.Add (type);
}
/// <summary>
/// We may only be used after Resolve() is called and return the fully
/// resolved types.
/// </summary>
// TODO: Not needed, just return type from resolve
public TypeSpec[] Arguments {
get {
return atypes;
}
set {
atypes = value;
}
}
public int Count {
get {
return args.Count;
}
}
public virtual bool IsEmpty {
get {
return false;
}
}
public List<FullNamedExpression> TypeExpressions {
get {
return this.args;
}
}
public string GetSignatureForError()
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < Count; ++i) {
var expr = args[i];
if (expr != null)
sb.Append (expr.GetSignatureForError ());
if (i + 1 < Count)
sb.Append (',');
}
return sb.ToString ();
}
/// <summary>
/// Resolve the type arguments.
/// </summary>
public virtual bool Resolve (IMemberContext ec)
{
if (atypes != null)
return atypes.Length != 0;
int count = args.Count;
bool ok = true;
atypes = new TypeSpec [count];
for (int i = 0; i < count; i++){
var te = args[i].ResolveAsType (ec);
if (te == null) {
ok = false;
continue;
}
atypes[i] = te;
if (te.IsStatic) {
ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
te.GetSignatureForError ());
ok = false;
}
if (te.IsPointer || te.IsSpecialRuntimeType) {
ec.Module.Compiler.Report.Error (306, args[i].Location,
"The type `{0}' may not be used as a type argument",
te.GetSignatureForError ());
ok = false;
}
}
if (!ok)
atypes = TypeSpec.EmptyTypes;
return ok;
}
public TypeArguments Clone ()
{
TypeArguments copy = new TypeArguments ();
foreach (var ta in args)
copy.args.Add (ta);
return copy;
}
}
public class UnboundTypeArguments : TypeArguments
{
public UnboundTypeArguments (int arity)
: base (new FullNamedExpression[arity])
{
}
public override bool IsEmpty {
get {
return true;
}
}
public override bool Resolve (IMemberContext ec)
{
// Nothing to be resolved
return true;
}
}
public class TypeParameters
{
List<TypeParameter> names;
TypeParameterSpec[] types;
public TypeParameters ()
{
names = new List<TypeParameter> ();
}
public TypeParameters (int count)
{
names = new List<TypeParameter> (count);
}
#region Properties
public int Count {
get {
return names.Count;
}
}
public TypeParameterSpec[] Types {
get {
return types;
}
}
#endregion
public void Add (TypeParameter tparam)
{
names.Add (tparam);
}
public void Add (TypeParameters tparams)
{
names.AddRange (tparams.names);
}
public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
{
types = new TypeParameterSpec[Count];
for (int i = 0; i < types.Length; ++i) {
var tp = names[i];
tp.Define (buiders[i + parentOffset], declaringType, parent);
types[i] = tp.Type;
types[i].DeclaredPosition = i + parentOffset;
if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
}
}
}
public TypeParameter this[int index] {
get {
return names [index];
}
set {
names[index] = value;
}
}
public TypeParameter Find (string name)
{
foreach (var tp in names) {
if (tp.Name == name)
return tp;
}
return null;
}
public string[] GetAllNames ()
{
return names.Select (l => l.Name).ToArray ();
}
public string GetSignatureForError ()
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < Count; ++i) {
if (i > 0)
sb.Append (',');
var name = names[i];
if (name != null)
sb.Append (name.GetSignatureForError ());
}
return sb.ToString ();
}
public void VerifyClsCompliance ()
{
foreach (var tp in names) {
tp.VerifyClsCompliance ();
}
}
}
//
// A type expression of generic type with type arguments
//
class GenericTypeExpr : TypeExpr
{
TypeArguments args;
TypeSpec open_type;
/// <summary>
/// Instantiate the generic type `t' with the type arguments `args'.
/// Use this constructor if you already know the fully resolved
/// generic type.
/// </summary>
public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
{
this.open_type = open_type;
loc = l;
this.args = args;
}
public override string GetSignatureForError ()
{
return TypeManager.CSharpName (type);
}
public override TypeSpec ResolveAsType (IMemberContext mc)
{
if (eclass != ExprClass.Unresolved)
return type;
if (!args.Resolve (mc))
return null;
TypeSpec[] atypes = args.Arguments;
//
// Now bind the parameters
//
var inflated = open_type.MakeGenericType (mc, atypes);
type = inflated;
eclass = ExprClass.Type;
//
// The constraints can be checked only when full type hierarchy is known
//
if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
var constraints = inflated.Constraints;
if (constraints != null) {
var cc = new ConstraintChecker (mc);
if (cc.CheckAll (open_type, atypes, constraints, loc)) {
inflated.HasConstraintsChecked = true;
}
}
}
return type;
}
public override bool Equals (object obj)
{
GenericTypeExpr cobj = obj as GenericTypeExpr;
if (cobj == null)
return false;
if ((type == null) || (cobj.type == null))
return false;
return type == cobj.type;
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
}
//
// Generic type with unbound type arguments, used for typeof (G<,,>)
//
class GenericOpenTypeExpr : TypeExpression
{
public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
: base (type.GetDefinition (), loc)
{
}
}
struct ConstraintChecker
{
IMemberContext mc;
bool recursive_checks;
public ConstraintChecker (IMemberContext ctx)
{
this.mc = ctx;
recursive_checks = false;
}
//
// Checks the constraints of open generic type against type
// arguments. This version is used for types which could not be
// checked immediatelly during construction because the type
// hierarchy was not yet fully setup (before Emit phase)
//
public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
{
//
// Check declaring type first if there is any
//
if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
return false;
while (type is ElementTypeSpec)
type = ((ElementTypeSpec) type).Element;
if (type.Arity == 0)
return true;
var gtype = type as InflatedTypeSpec;
if (gtype == null)
return true;
var constraints = gtype.Constraints;
if (constraints == null)
return true;
if (gtype.HasConstraintsChecked)
return true;
var cc = new ConstraintChecker (mc);
cc.recursive_checks = true;
if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
gtype.HasConstraintsChecked = true;
return true;
}
return false;
}
//
// Checks all type arguments againts type parameters constraints
// NOTE: It can run in probing mode when `this.mc' is null
//
public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
{
for (int i = 0; i < tparams.Length; i++) {
var targ = targs[i];
if (!CheckConstraint (context, targ, tparams [i], loc))
return false;
if (!recursive_checks)
continue;
if (!Check (mc, targ, loc))
return false;
}
return true;
}
bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
{
//
// First, check the `class' and `struct' constraints.
//
if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
if (mc != null) {
mc.Module.Compiler.Report.Error (452, loc,
"The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
}
return false;
}
if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
if (mc != null) {
mc.Module.Compiler.Report.Error (453, loc,
"The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
}
return false;
}
bool ok = true;
//
// Check the class constraint
//
if (tparam.HasTypeConstraint) {
if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
if (mc == null)
return false;
ok = false;
}
}
//
// Check the interfaces constraints
//
if (tparam.Interfaces != null) {
foreach (TypeSpec iface in tparam.Interfaces) {
if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
if (mc == null)
return false;
ok = false;
}
}
}
//
// Check the type parameter constraint
//
if (tparam.TypeArguments != null) {
foreach (var ta in tparam.TypeArguments) {
if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
if (mc == null)
return false;
ok = false;
}
}
}
//
// Finally, check the constructor constraint.
//
if (!tparam.HasSpecialConstructor)
return ok;
if (!HasDefaultConstructor (atype)) {
if (mc != null) {
mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
mc.Module.Compiler.Report.Error (310, loc,
"The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
}
return false;
}
return ok;
}
static bool HasDynamicTypeArgument (TypeSpec[] targs)
{
for (int i = 0; i < targs.Length; ++i) {
var targ = targs [i];
if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return true;
if (HasDynamicTypeArgument (targ.TypeArguments))
return true;
}
return false;
}
bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
{
if (atype == ttype)
return true;
if (atype.IsGenericParameter) {
var tps = (TypeParameterSpec) atype;
if (tps.TypeArguments != null) {
foreach (var targ in tps.TypeArguments) {
if (TypeSpecComparer.Override.IsEqual (targ, ttype))
return true;
}
}
if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
return true;
} else if (TypeSpec.IsValueType (atype)) {
if (atype.IsNullableType) {
//
// LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
//
if (TypeSpec.IsBaseClass (atype, ttype, false))
return true;
} else {
if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
return true;
}
} else {
if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
return true;
}
if (mc != null) {
mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
if (atype.IsGenericParameter) {
mc.Module.Compiler.Report.Error (314, loc,
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
} else if (TypeSpec.IsValueType (atype)) {
if (atype.IsNullableType) {
if (ttype.IsInterface) {
mc.Module.Compiler.Report.Error (313, loc,
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint `{3}'",
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
} else {
mc.Module.Compiler.Report.Error (312, loc,
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
}
} else {
mc.Module.Compiler.Report.Error (315, loc,
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
}
} else {
mc.Module.Compiler.Report.Error (311, loc,
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
}
}
return false;
}
static bool HasDefaultConstructor (TypeSpec atype)
{
var tp = atype as TypeParameterSpec;
if (tp != null) {
return tp.HasSpecialConstructor || tp.HasSpecialStruct;
}
if (atype.IsStruct || atype.IsEnum)
return true;
if (atype.IsAbstract)
return false;
var tdef = atype.GetDefinition ();
var found = MemberCache.FindMember (tdef,
MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
}
}
public partial class TypeManager
{
public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
{
var tp = t as TypeParameterSpec;
if (tp != null) {
Variance v = tp.Variance;
if (expected == Variance.None && v != expected ||
expected == Variance.Covariant && v == Variance.Contravariant ||
expected == Variance.Contravariant && v == Variance.Covariant) {
((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
}
return expected;
}
if (t.TypeArguments.Length > 0) {
var targs_definition = t.MemberDefinition.TypeParameters;
TypeSpec[] targs = GetTypeArguments (t);
for (int i = 0; i < targs.Length; ++i) {
Variance v = targs_definition[i].Variance;
CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
}
return expected;
}
if (t.IsArray)
return CheckTypeVariance (GetElementType (t), expected, member);
return Variance.None;
}
}
//
// Implements C# type inference
//
class TypeInference
{
//
// Tracks successful rate of type inference
//
int score = int.MaxValue;
readonly Arguments arguments;
readonly int arg_count;
public TypeInference (Arguments arguments)
{
this.arguments = arguments;
if (arguments != null)
arg_count = arguments.Count;
}
public int InferenceScore {
get {
return score;
}
}
public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
{
var method_generic_args = method.GenericDefinition.TypeParameters;
TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
if (!context.UnfixedVariableExists)
return TypeSpec.EmptyTypes;
AParametersCollection pd = method.Parameters;
if (!InferInPhases (ec, context, pd))
return null;
return context.InferredTypeArguments;
}
//
// Implements method type arguments inference
//
bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
{
int params_arguments_start;
if (methodParameters.HasParams) {
params_arguments_start = methodParameters.Count - 1;
} else {
params_arguments_start = arg_count;
}
TypeSpec [] ptypes = methodParameters.Types;
//
// The first inference phase
//
TypeSpec method_parameter = null;
for (int i = 0; i < arg_count; i++) {
Argument a = arguments [i];
if (a == null)
continue;
if (i < params_arguments_start) {
method_parameter = methodParameters.Types [i];
} else if (i == params_arguments_start) {
if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
method_parameter = methodParameters.Types [params_arguments_start];
else
method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
ptypes = (TypeSpec[]) ptypes.Clone ();
ptypes [i] = method_parameter;
}
//
// When a lambda expression, an anonymous method
// is used an explicit argument type inference takes a place
//
AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
if (am != null) {
if (am.ExplicitTypeInference (ec, tic, method_parameter))
--score;
continue;
}
if (a.IsByRef) {
score -= tic.ExactInference (a.Type, method_parameter);
continue;
}
if (a.Expr.Type == InternalType.NullLiteral)
continue;
if (TypeSpec.IsValueType (method_parameter)) {
score -= tic.LowerBoundInference (a.Type, method_parameter);
continue;
}
//
// Otherwise an output type inference is made
//
score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
}
//
// Part of the second phase but because it happens only once
// we don't need to call it in cycle
//
bool fixed_any = false;
if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
return false;
return DoSecondPhase (ec, tic, ptypes, !fixed_any);
}
bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
{
bool fixed_any = false;
if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
return false;
// If no further unfixed type variables exist, type inference succeeds
if (!tic.UnfixedVariableExists)
return true;
if (!fixed_any && fixDependent)
return false;
// For all arguments where the corresponding argument output types
// contain unfixed type variables but the input types do not,
// an output type inference is made
for (int i = 0; i < arg_count; i++) {
// Align params arguments
TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
if (!t_i.IsDelegate) {
if (!t_i.IsExpressionTreeType)
continue;
t_i = TypeManager.GetTypeArguments (t_i) [0];
}
var mi = Delegate.GetInvokeMethod (t_i);
TypeSpec rtype = mi.ReturnType;
if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
// It can be null for default arguments
if (arguments[i] == null)
continue;
score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
}
}
return DoSecondPhase (ec, tic, methodParameters, true);
}
}
public class TypeInferenceContext
{
protected enum BoundKind
{
Exact = 0,
Lower = 1,
Upper = 2
}
protected class BoundInfo : IEquatable<BoundInfo>
{
public readonly TypeSpec Type;
public readonly BoundKind Kind;
public BoundInfo (TypeSpec type, BoundKind kind)
{
this.Type = type;
this.Kind = kind;
}
public override int GetHashCode ()
{
return Type.GetHashCode ();
}
public virtual Expression GetTypeExpression ()
{
return new TypeExpression (Type, Location.Null);
}
#region IEquatable<BoundInfo> Members
public virtual bool Equals (BoundInfo other)
{
return Type == other.Type && Kind == other.Kind;
}
#endregion
}
readonly TypeSpec[] tp_args;
readonly TypeSpec[] fixed_types;
readonly List<BoundInfo>[] bounds;
bool failed;
// TODO MemberCache: Could it be TypeParameterSpec[] ??
public TypeInferenceContext (TypeSpec[] typeArguments)
{
if (typeArguments.Length == 0)
throw new ArgumentException ("Empty generic arguments");
fixed_types = new TypeSpec [typeArguments.Length];
for (int i = 0; i < typeArguments.Length; ++i) {
if (typeArguments [i].IsGenericParameter) {
if (bounds == null) {
bounds = new List<BoundInfo> [typeArguments.Length];
tp_args = new TypeSpec [typeArguments.Length];
}
tp_args [i] = typeArguments [i];
} else {
fixed_types [i] = typeArguments [i];
}
}
}
//
// Used together with AddCommonTypeBound fo implement
// 7.4.2.13 Finding the best common type of a set of expressions
//
public TypeInferenceContext ()
{
fixed_types = new TypeSpec [1];
tp_args = new TypeSpec [1];
tp_args[0] = InternalType.Arglist; // it can be any internal type
bounds = new List<BoundInfo> [1];
}
public TypeSpec[] InferredTypeArguments {
get {
return fixed_types;
}
}
public void AddCommonTypeBound (TypeSpec type)
{
AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
}
protected void AddToBounds (BoundInfo bound, int index)
{
//
// Some types cannot be used as type arguments
//
if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
return;
var a = bounds [index];
if (a == null) {
a = new List<BoundInfo> (2);
a.Add (bound);
bounds [index] = a;
return;
}
if (a.Contains (bound))
return;
a.Add (bound);
}
bool AllTypesAreFixed (TypeSpec[] types)
{
foreach (TypeSpec t in types) {
if (t.IsGenericParameter) {
if (!IsFixed (t))
return false;
continue;
}
if (TypeManager.IsGenericType (t))
return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
}
return true;
}
//
// 26.3.3.8 Exact Inference
//
public int ExactInference (TypeSpec u, TypeSpec v)
{
// If V is an array type
if (v.IsArray) {
if (!u.IsArray)
return 0;
var ac_u = (ArrayContainer) u;
var ac_v = (ArrayContainer) v;
if (ac_u.Rank != ac_v.Rank)
return 0;
return ExactInference (ac_u.Element, ac_v.Element);
}
// If V is constructed type and U is constructed type
if (TypeManager.IsGenericType (v)) {
if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
return 0;
TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
if (ga_u.Length != ga_v.Length)
return 0;
int score = 0;
for (int i = 0; i < ga_u.Length; ++i)
score += ExactInference (ga_u [i], ga_v [i]);
return score > 0 ? 1 : 0;
}
// If V is one of the unfixed type arguments
int pos = IsUnfixed (v);
if (pos == -1)
return 0;
AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
return 1;
}
public bool FixAllTypes (ResolveContext ec)
{
for (int i = 0; i < tp_args.Length; ++i) {
if (!FixType (ec, i))
return false;
}
return true;
}
//
// All unfixed type variables Xi are fixed for which all of the following hold:
// a, There is at least one type variable Xj that depends on Xi
// b, Xi has a non-empty set of bounds
//
public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
{
for (int i = 0; i < tp_args.Length; ++i) {
if (fixed_types[i] != null)
continue;
if (bounds[i] == null)
continue;
if (!FixType (ec, i))
return false;
fixed_any = true;
}
return true;
}
//
// All unfixed type variables Xi which depend on no Xj are fixed
//
public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
{
var types_to_fix = new List<TypeSpec> (tp_args);
for (int i = 0; i < methodParameters.Length; ++i) {
TypeSpec t = methodParameters[i];
if (!t.IsDelegate) {
if (!t.IsExpressionTreeType)
continue;
t = TypeManager.GetTypeArguments (t) [0];
}
if (t.IsGenericParameter)
continue;
var invoke = Delegate.GetInvokeMethod (t);
TypeSpec rtype = invoke.ReturnType;
while (rtype.IsArray)
rtype = ((ArrayContainer) rtype).Element;
if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
continue;
// Remove dependent types, they cannot be fixed yet
RemoveDependentTypes (types_to_fix, rtype);
}
foreach (TypeSpec t in types_to_fix) {
if (t == null)
continue;
int idx = IsUnfixed (t);
if (idx >= 0 && !FixType (ec, idx)) {
return false;
}
}
fixed_any = types_to_fix.Count > 0;
return true;
}
//
// 26.3.3.10 Fixing
//
public bool FixType (ResolveContext ec, int i)
{
// It's already fixed
if (fixed_types[i] != null)
throw new InternalErrorException ("Type argument has been already fixed");
if (failed)
return false;
var candidates = bounds [i];
if (candidates == null)
return false;
if (candidates.Count == 1) {
TypeSpec t = candidates[0].Type;
if (t == InternalType.NullLiteral)
return false;
fixed_types [i] = t;
return true;
}
//
// Determines a unique type from which there is
// a standard implicit conversion to all the other
// candidate types.
//
TypeSpec best_candidate = null;
int cii;
int candidates_count = candidates.Count;
for (int ci = 0; ci < candidates_count; ++ci) {
BoundInfo bound = candidates [ci];
for (cii = 0; cii < candidates_count; ++cii) {
if (cii == ci)
continue;
BoundInfo cbound = candidates[cii];
// Same type parameters with different bounds
if (cbound.Type == bound.Type) {
if (bound.Kind != BoundKind.Exact)
bound = cbound;
continue;
}
if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
if (cbound.Kind == BoundKind.Lower) {
if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
break;
}
continue;
}
if (cbound.Kind == BoundKind.Upper) {
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
break;
}
continue;
}
if (bound.Kind != BoundKind.Exact) {
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
break;
}
bound = cbound;
continue;
}
break;
}
if (bound.Kind == BoundKind.Lower) {
if (cbound.Kind == BoundKind.Lower) {
if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
break;
}
} else {
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
break;
}
bound = cbound;
}
continue;
}
if (bound.Kind == BoundKind.Upper) {
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
break;
}
} else {
throw new NotImplementedException ("variance conversion");
}
}
if (cii != candidates_count)
continue;
//
// We already have the best candidate, break if thet are different
//
// Dynamic is never ambiguous as we prefer dynamic over other best candidate types
//
if (best_candidate != null) {
if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
continue;
if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
return false;
}
best_candidate = bound.Type;
}
if (best_candidate == null)
return false;
fixed_types[i] = best_candidate;
return true;
}
public bool HasBounds (int pos)
{
return bounds[pos] != null;
}
//
// Uses inferred or partially infered types to inflate delegate type argument. Returns
// null when type parameter has not been fixed
//
public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
{
var tp = parameter as TypeParameterSpec;
if (tp != null) {
//
// Type inference works on generic arguments (MVAR) only
//
if (!tp.IsMethodOwned)
return parameter;
//
// Ensure the type parameter belongs to same container
//
if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
return fixed_types[tp.DeclaredPosition] ?? parameter;
return parameter;
}
var gt = parameter as InflatedTypeSpec;
if (gt != null) {
var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
for (int ii = 0; ii < inflated_targs.Length; ++ii) {
var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
if (inflated == null)
return null;
inflated_targs[ii] = inflated;
}
return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
}
var ac = parameter as ArrayContainer;
if (ac != null) {
var inflated = InflateGenericArgument (context, ac.Element);
if (inflated != ac.Element)
return ArrayContainer.MakeType (context.Module, inflated);
}
return parameter;
}
//
// Tests whether all delegate input arguments are fixed and generic output type
// requires output type inference
//
public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
{
while (returnType.IsArray)
returnType = ((ArrayContainer) returnType).Element;
if (returnType.IsGenericParameter) {
if (IsFixed (returnType))
return false;
} else if (TypeManager.IsGenericType (returnType)) {
if (returnType.IsDelegate) {
invoke = Delegate.GetInvokeMethod (returnType);
return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
}
TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
// At least one unfixed return type has to exist
if (AllTypesAreFixed (g_args))
return false;
} else {
return false;
}
// All generic input arguments have to be fixed
AParametersCollection d_parameters = invoke.Parameters;
return AllTypesAreFixed (d_parameters.Types);
}
bool IsFixed (TypeSpec type)
{
return IsUnfixed (type) == -1;
}
int IsUnfixed (TypeSpec type)
{
if (!type.IsGenericParameter)
return -1;
for (int i = 0; i < tp_args.Length; ++i) {
if (tp_args[i] == type) {
if (fixed_types[i] != null)
break;
return i;
}
}
return -1;
}
//
// 26.3.3.9 Lower-bound Inference
//
public int LowerBoundInference (TypeSpec u, TypeSpec v)
{
return LowerBoundInference (u, v, false);
}
//
// Lower-bound (false) or Upper-bound (true) inference based on inversed argument
//
int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
{
// If V is one of the unfixed type arguments
int pos = IsUnfixed (v);
if (pos != -1) {
AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
return 1;
}
// If U is an array type
var u_ac = u as ArrayContainer;
if (u_ac != null) {
var v_ac = v as ArrayContainer;
if (v_ac != null) {
if (u_ac.Rank != v_ac.Rank)
return 0;
if (TypeSpec.IsValueType (u_ac.Element))
return ExactInference (u_ac.Element, v_ac.Element);
return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
}
if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
return 0;
var v_i = TypeManager.GetTypeArguments (v) [0];
if (TypeSpec.IsValueType (u_ac.Element))
return ExactInference (u_ac.Element, v_i);
return LowerBoundInference (u_ac.Element, v_i);
}
if (v.IsGenericOrParentIsGeneric) {
//
// if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
// such that U is identical to, inherits from (directly or indirectly),
// or implements (directly or indirectly) C<U1..Uk>
//
var u_candidates = new List<TypeSpec> ();
var open_v = v.MemberDefinition;
for (TypeSpec t = u; t != null; t = t.BaseType) {
if (open_v == t.MemberDefinition)
u_candidates.Add (t);
//
// Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
// that would complicate the process a lot, instead I treat them as dynamic
//
if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
u_candidates.Add (t);
if (t.Interfaces != null) {
foreach (var iface in t.Interfaces) {
if (open_v == iface.MemberDefinition)
u_candidates.Add (iface);
}
}
}
TypeSpec[] unique_candidate_targs = null;
var ga_v = TypeSpec.GetAllTypeArguments (v);
foreach (TypeSpec u_candidate in u_candidates) {
//
// The unique set of types U1..Uk means that if we have an interface I<T>,
// class U : I<int>, I<long> then no type inference is made when inferring
// type I<T> by applying type U because T could be int or long
//
if (unique_candidate_targs != null) {
TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
unique_candidate_targs = second_unique_candidate_targs;
continue;
}
//
// This should always cause type inference failure
//
failed = true;
return 1;
}
//
// A candidate is dynamic type expression, to simplify things use dynamic
// for all type parameter of this type. For methods like this one
//
// void M<T, U> (IList<T>, IList<U[]>)
//
// dynamic becomes both T and U when the arguments are of dynamic type
//
if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
unique_candidate_targs = new TypeSpec[ga_v.Length];
for (int i = 0; i < unique_candidate_targs.Length; ++i)
unique_candidate_targs[i] = u_candidate;
} else {
unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
}
}
if (unique_candidate_targs != null) {
int score = 0;
int tp_index = -1;
TypeParameterSpec[] tps = null;
for (int i = 0; i < unique_candidate_targs.Length; ++i) {
if (tp_index < 0) {
while (v.Arity == 0)
v = v.DeclaringType;
tps = v.MemberDefinition.TypeParameters;
tp_index = tps.Length - 1;
}
Variance variance = tps [tp_index--].Variance;
TypeSpec u_i = unique_candidate_targs [i];
if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
if (ExactInference (u_i, ga_v [i]) == 0)
++score;
} else {
bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
(variance == Variance.Covariant && inversed);
if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
++score;
}
}
return score;
}
}
return 0;
}
//
// 26.3.3.6 Output Type Inference
//
public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
{
// If e is a lambda or anonymous method with inferred return type
AnonymousMethodExpression ame = e as AnonymousMethodExpression;
if (ame != null) {
TypeSpec rt = ame.InferReturnType (ec, this, t);
var invoke = Delegate.GetInvokeMethod (t);
if (rt == null) {
AParametersCollection pd = invoke.Parameters;
return ame.Parameters.Count == pd.Count ? 1 : 0;
}
TypeSpec rtype = invoke.ReturnType;
return LowerBoundInference (rt, rtype) + 1;
}
//
// if E is a method group and T is a delegate type or expression tree type
// return type Tb with parameter types T1..Tk and return type Tb, and overload
// resolution of E with the types T1..Tk yields a single method with return type U,
// then a lower-bound inference is made from U for Tb.
//
if (e is MethodGroupExpr) {
if (!t.IsDelegate) {
if (!t.IsExpressionTreeType)
return 0;
t = TypeManager.GetTypeArguments (t)[0];
}
var invoke = Delegate.GetInvokeMethod (t);
TypeSpec rtype = invoke.ReturnType;
if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
return 0;
// LAMESPEC: Standard does not specify that all methodgroup arguments
// has to be fixed but it does not specify how to do recursive type inference
// either. We choose the simple option and infer return type only
// if all delegate generic arguments are fixed.
TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
for (int i = 0; i < param_types.Length; ++i) {
var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
if (inflated == null)
return 0;
if (IsUnfixed (inflated) >= 0)
return 0;
param_types[i] = inflated;
}
MethodGroupExpr mg = (MethodGroupExpr) e;
Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
if (mg == null)
return 0;
return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
}
//
// if e is an expression with type U, then
// a lower-bound inference is made from U for T
//
return LowerBoundInference (e.Type, t) * 2;
}
void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
{
int idx = IsUnfixed (returnType);
if (idx >= 0) {
types [idx] = null;
return;
}
if (TypeManager.IsGenericType (returnType)) {
foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
RemoveDependentTypes (types, t);
}
}
}
public bool UnfixedVariableExists {
get {
foreach (TypeSpec ut in fixed_types) {
if (ut == null)
return true;
}
return false;
}
}
}
}
| 26.819133 | 169 | 0.63136 | [
"MIT"
] | GreenDamTan/simple-assembly-exploror | ILSpy/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs | 92,231 | C# |
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace WendigoJaeger.TranslationTool.Undo
{
public class UndoObservableCollection<T> : ObservableCollection<T>, IUndoPropertyChanged, IUndoArrayChanged, INotifyPropertyChanged
{
public event UndoArrayChangedEventHandler UndoArrayChanged;
public event UndoPropertyChangedEventHandler UndoPropertyChanged;
#pragma warning disable CS0114 // Member hides inherited member; missing override keyword
public event PropertyChangedEventHandler PropertyChanged;
#pragma warning restore CS0114 // Member hides inherited member; missing override keyword
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
if (e.Action == NotifyCollectionChangedAction.Add)
{
if (typeof(T).IsSubclassOf(typeof(UndoObject)))
{
foreach (UndoObject item in e.NewItems)
{
item.UndoArrayChanged -= undoArrayChangedProxy;
item.UndoArrayChanged += undoArrayChangedProxy;
item.UndoPropertyChanged -= undoPropertyChangedProxy;
item.UndoPropertyChanged += undoPropertyChangedProxy;
item.PropertyChanged -= propertyChangedProxy;
item.PropertyChanged += propertyChangedProxy;
}
}
object[] affectedObjects = new object[e.NewItems.Count];
for(int i=0; i<affectedObjects.Length; ++i)
{
affectedObjects[i] = e.NewItems[i];
}
undoArrayChangedProxy(this, new UndoArrayChangedEventArgs(UndoArrayChangedEventArgs.OperationType.Add, affectedObjects));
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
if (typeof(T).IsSubclassOf(typeof(UndoObject)))
{
foreach (UndoObject item in e.OldItems)
{
item.UndoArrayChanged -= undoArrayChangedProxy;
item.UndoPropertyChanged -= undoPropertyChangedProxy;
item.PropertyChanged -= propertyChangedProxy;
}
}
object[] affectedObjects = new object[e.OldItems.Count];
for (int i = 0; i < affectedObjects.Length; ++i)
{
affectedObjects[i] = e.OldItems[i];
}
undoArrayChangedProxy(this, new UndoArrayChangedEventArgs(UndoArrayChangedEventArgs.OperationType.Remove, affectedObjects));
}
}
private void undoArrayChangedProxy(object sender, UndoArrayChangedEventArgs e)
{
UndoArrayChanged?.Invoke(sender, e);
}
private void undoPropertyChangedProxy(object sender, UndoPropertyChangedEventArgs e)
{
UndoPropertyChanged?.Invoke(sender, e);
}
private void propertyChangedProxy(object sender, PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(sender, e);
}
}
}
| 40.463415 | 140 | 0.601567 | [
"MIT"
] | wendigojaeger/TranslationTools | LibWendigoJaegerTranslationTool/Undo/UndoObservableCollection.cs | 3,320 | 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 lambda-2015-03-31.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.Lambda.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lambda.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteFunctionConcurrency operation
/// </summary>
public class DeleteFunctionConcurrencyResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteFunctionConcurrencyResponse response = new DeleteFunctionConcurrencyResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceConflictException"))
{
return ResourceConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException"))
{
return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonLambdaException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteFunctionConcurrencyResponseUnmarshaller _instance = new DeleteFunctionConcurrencyResponseUnmarshaller();
internal static DeleteFunctionConcurrencyResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteFunctionConcurrencyResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.704348 | 189 | 0.661611 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Lambda/Generated/Model/Internal/MarshallTransformations/DeleteFunctionConcurrencyResponseUnmarshaller.cs | 4,681 | C# |
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using AD419.DataHelper.Web.Models;
using AD419.DataHelper.Web.ViewModels;
namespace AD419.DataHelper.Web.Controllers
{
public class ExpiredProjectsController : SuperController
{
// GET: ExpiredProjectCrossReference
public async Task<ViewResult> Index()
{
var year = FiscalYearService.FiscalYear;
var expired = await DbContext.GetExpired20XProjects(year);
var projects = DbContext.ExpiredProjectCrossReference.ToList();
var results =
from x in expired
join p in projects on x.AccessionNumber equals p.FromAccession into pMatch
from match in pMatch.DefaultIfEmpty()
select new ExpiringProjectMatch { ExpiringProject = x, MatchedProject = match};
return View(results.ToList());
}
public ActionResult Mappings()
{
var projects = DbContext.ExpiredProjectCrossReference.ToList();
return View(projects);
}
// GET: ExpiredProjectCrossReference/Details/5
public ActionResult Details(int id)
{
var project = DbContext.ExpiredProjectCrossReference.Find(id);
if (project == null)
{
return HttpNotFound();
}
return View(project);
}
// GET: ExpiredProjectCrossReference/Delete/5
public ActionResult Delete(int id)
{
var project = DbContext.ExpiredProjectCrossReference.Find(id);
if (project == null)
{
return HttpNotFound();
}
return View(project);
}
// POST: ExpiredProjectCrossReference/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var project = DbContext.ExpiredProjectCrossReference.Find(id);
if (project == null)
{
return HttpNotFound();
}
DbContext.ExpiredProjectCrossReference.Remove(project);
DbContext.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MapProject(string from, string to)
{
if (string.IsNullOrWhiteSpace(from))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (string.IsNullOrWhiteSpace(to))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var match = new ExpiredProjectCrossReference()
{
FromAccession = from,
ToAccession = to,
IsActive = true
};
DbContext.ExpiredProjectCrossReference.Add(match);
DbContext.SaveChanges();
return RedirectToAction("Index");
}
}
}
| 31.616162 | 96 | 0.569329 | [
"MIT"
] | ucdavis/AD419DataHelper | AD419.DataHelper.Web/Controllers/ExpiredProjectsController.cs | 3,132 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// ReSharper disable once CheckNamespace
namespace NPascalCoin.API.Objects {
/// <summary>
/// Type of key used for public/private key encryption.
/// </summary>
public enum KeyType {
/// <summary>
/// secp256k1
/// </summary>
SECP256K1 = 714,
/// <summary>
/// secp384r1
/// </summary>
SECP384R1 = 715,
/// <summary>
/// secp283k1
/// </summary>
SECP283K1 = 729,
/// <summary>
/// secp521r1
/// </summary>
SECP521R1 = 716,
}
}
| 16.333333 | 56 | 0.632653 | [
"MIT"
] | Sphere10/NPascalCoin | src/NPascalCoin/API/Objects/KeyType.cs | 590 | C# |
namespace CoAndContraVariance
{
public class Client : Person
{
public Client(string firstname, string lastname) : base(firstname, lastname) { }
public int Budget { get; set; }
}
}
| 20.9 | 88 | 0.641148 | [
"MIT"
] | shuryak/csharp-learning | Delegates/Covariance and contravariance/CoAndContraVariance/Client.cs | 209 | 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("MostFrequentlyMetElement")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MostFrequentlyMetElement")]
[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("93e44aea-c118-4457-a1f0-93269181c440")]
// 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.27027 | 84 | 0.752119 | [
"MIT"
] | LuGeorgiev/CSharpSelfLearning | Arrays/MostFrequentlyMetElement/Properties/AssemblyInfo.cs | 1,419 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.Tests.Stubs
{
public class DataReader : IDataReader
{
public void Dispose()
{
}
public string GetName(int i)
{
return null;
}
public string GetDataTypeName(int i)
{
return null;
}
public Type GetFieldType(int i)
{
return GetType();
}
public object GetValue(int i)
{
return null;
}
public int GetValues(object[] values)
{
return 0;
}
public int GetOrdinal(string name)
{
return 0;
}
public bool GetBoolean(int i)
{
return default(bool);
}
public byte GetByte(int i)
{
return default(byte);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
return default(long);
}
public char GetChar(int i)
{
return default(char);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
return default(long);
}
public Guid GetGuid(int i)
{
return default(Guid);
}
public short GetInt16(int i)
{
return default(short);
}
public int GetInt32(int i)
{
return default(int);
}
public long GetInt64(int i)
{
return default(long);
}
public float GetFloat(int i)
{
return default(float);
}
public double GetDouble(int i)
{
return default(double);
}
public string GetString(int i)
{
return null;
}
public decimal GetDecimal(int i)
{
return default(decimal);
}
public DateTime GetDateTime(int i)
{
return default(DateTime);
}
public IDataReader GetData(int i)
{
return null;
}
public bool IsDBNull(int i)
{
return false;
}
public int FieldCount { get; private set; }
object IDataRecord.this[int i]
{
get { return null; }
}
object IDataRecord.this[string name]
{
get { return null; }
}
public void Close()
{
}
public DataTable GetSchemaTable()
{
return null;
}
public bool NextResult()
{
return false;
}
public bool Read()
{
return false;
}
public int Depth { get; private set; }
public bool IsClosed { get; private set; }
public int RecordsAffected { get; private set; }
}
}
| 18.939024 | 98 | 0.469414 | [
"Apache-2.0"
] | marinoscar/Luval | Code/Luval.Tests/Stubs/DataReader.cs | 3,108 | C# |
using Xamarin.Forms;
namespace FFImageLoading.Forms.Sample
{
public partial class ByteArrayListPage : BasePage<ByteArrayListPageModel>
{
public ByteArrayListPage()
{
InitializeComponent();
}
}
}
| 18.846154 | 77 | 0.644898 | [
"MIT"
] | tmijieux/FFImageLoading | samples/ImageLoading.Forms.Sample/Shared/Pages/ByteArrayListPage.xaml.cs | 247 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class ModifyEipAddressAttributeResponse : AcsResponse
{
}
} | 36.384615 | 63 | 0.755814 | [
"Apache-2.0"
] | VAllens/aliyun-openapi-sdk-net-core | src/aliyun-net-sdk-ecs/Model/V20140526/ModifyEipAddressAttributeResponse.cs | 946 | C# |
using ErpBS100;
using PRISDK100;
using StdBE100;
using SUGIMPL_OME.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
namespace SUGIMPL_OME.CrossCompany
{
class PayablesReceivables
{
/// <summary>
/// Returns the global position of a specified company (and, optionally, its related companies) all over the group companies.
/// </summary>
/// <param name="ERPContext"></param>
/// <param name="EntityType"></param>
/// <param name="EntityCode"></param>
/// <param name="IncludeRelatedEntities"></param>
/// <returns>A StdBELista containing the information.</returns>
internal static StdBELista GetGlobalPosition(ERPContext ERPContext, String EntityType, String EntityCode, Boolean IncludeRelatedEntities)
{
StringBuilder sqlQRY = new StringBuilder();
Dictionary<String, String> GroupCompanies = CrossCompany.Platform.GetGroupCompanies(ERPContext);
StdBELista retValue = new StdBELista();
try
{
//Prepare the quary template to be used in each company
sqlQRY.Append("select Grp1= '', Empresa = '{0}', E.TipoEntidade , E.Entidade ");
sqlQRY.Append(" ,Orcamentos = isnull((select sum(totalmerc - totaldesc + totaloutros) from {1}..cabecdoc cd left join {1}..cabecdocstatus cds on cd.id = cds.idcabecdoc where cd.tipodoc = 'ORC' and cds.estado = 'G' and cd.entidade = E.CodEntidade and E.TipoEntidade IN('C', 'D')), 0) ");
sqlQRY.Append(" +isnull((select - sum(totalmerc - totaldesc + totaloutros) from {1}..cabeccompras cc left join {1}..cabeccomprasstatus ccs on cc.id = ccs.idcabeccompras where cc.tipodoc = 'PCO' and ccs.estado = 'G' and cc.entidade = E.CodEntidade and E.TipoEntidade IN('F', 'R')),0) ");
sqlQRY.Append(" ,Encomendas = isnull((select EncomendasPendentes from {1}..Clientes where Cliente = E.CodEntidade and E.TipoEntidade IN('C', 'D')),0) ");
sqlQRY.Append(" +isnull((select - EncomendasPendentes from {1}..fornecedores where fornecedor = E.CodEntidade and E.TipoEntidade IN('F', 'R')),0)");
sqlQRY.Append(" ,TotalVencido = isnull((select sum(valorpendente) from {1}..pendentes where entidade = E.CodEntidade and E.TipoEntidade IN('C', 'D') and datavenc < getdate() and tipoconta = 'CCC' group by entidade),0) ");
sqlQRY.Append(" +isnull((select sum(valorpendente) from {1}..pendentes where entidade = E.CodEntidade and E.TipoEntidade IN('F', 'R') and datavenc < getdate() and tipoconta = 'CCF' group by entidade),0) ");
sqlQRY.Append(" ,TotalDebito = isnull((select totaldeb from {1}..clientes where cliente = E.CodEntidade and E.TipoEntidade IN('C', 'D')),0) ");
sqlQRY.Append(" +isnull((select - totaldeb from {1}..fornecedores where fornecedor = E.CodEntidade and E.TipoEntidade IN('F', 'R')),0)");
sqlQRY.Append("from( ");
sqlQRY.Append(" select '{2}' as TipoEntidade, Cliente as CodEntidade, Nome as Entidade, '0' as Associada from {1}..Clientes where Cliente = '{3}' and '{2}' = 'C' ");
sqlQRY.Append(" UNION ALL ");
sqlQRY.Append(" select '{2}' as TipoEntidade, Fornecedor as CodEntidade, Nome as Entidade, '0' as Associada from {1}..Fornecedores where Fornecedor = '{3}' and '{2}' = 'F' ");
sqlQRY.Append(" UNION ALL ");
sqlQRY.Append(" select '{2}' as TipoEntidade, Terceiro as CodEntidade, Nome as Entidade, '0' as Associada from {1}..OutrosTerceiros where Terceiro = '{3}' and TipoEntidade = '{2}' ");
sqlQRY.Append(" UNION ALL ");
sqlQRY.Append(" select TipoEntidadeAssociada as TipoEntidade, EntidadeAssociada as CodEntidade, coalesce(C.Nome, F.Nome, T.Nome) as Entidade, 1 as Associada ");
sqlQRY.Append(" from {1}..EntidadesAssociadas EA ");
sqlQRY.Append(" left join {1}..Clientes C on C.Cliente = EA.EntidadeAssociada and EA.TipoEntidadeAssociada = 'C' ");
sqlQRY.Append(" left join {1}..Fornecedores F on F.Fornecedor = EA.EntidadeAssociada and EA.TipoEntidadeAssociada = 'F' ");
sqlQRY.Append(" left join {1}..OutrosTerceiros T on T.Terceiro = EA.EntidadeAssociada and T.TipoTerceiro = EA.TipoEntidadeAssociada ");
sqlQRY.Append(" where Entidade = '{3}' and EA.TipoEntidade = '{2}' ");
sqlQRY.Append(" ) as E ");
sqlQRY.Append("Where Associada = 0 or Associada = {4}");
//Prepare de final query (having all companies)
StringBuilder sqlQRYtoRun = new StringBuilder();
String strUnion = string.Empty;
foreach (String Company in GroupCompanies.Keys)
{
sqlQRYtoRun.Append(strUnion);
sqlQRYtoRun.AppendFormat(sqlQRY.ToString(), Company, string.Format("PRI{0}", Company), EntityType, EntityCode, IncludeRelatedEntities ? 1 : 0);
strUnion = "UNION ALL ";
}
//Execute the query to retrieve the information
retValue = ERPContext.BSO.Consulta(sqlQRYtoRun.ToString());
}
catch
{
//DO NOTHING
}
return retValue;
}
/// <summary>
/// Return a list of companies where the credit limit of the given customer is exceeded orelse has been blocked.
/// </summary>
/// <param name="strCustomer">Customer to be analised</param>
/// <returns>List<String></String></returns>
internal static List<String> CreditLimitExceeded(ERPContext ERPContext, String strCustomer)
{
List<String> companiesList = new List<String>();
Dictionary<String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(ERPContext);
foreach (string company in groupCompanies.Keys)
{
ErpBS currentCompany = new ErpBS();
currentCompany.AbreEmpresaTrabalho(
StdBETipos.EnumTipoPlataforma.tpEmpresarial,
company,
Properties.Settings.Default.User, //ERPContext.BSO.Contexto.ObjUtilizador.Codigo,
Properties.Settings.Default.Password //ERPContext.BSO.Contexto.ObjUtilizador.Password
);
if ((currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "TipoCred") == "2")
|| (currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "limitecred") < currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "totaldeb")))
{
companiesList.Add(company);
}
currentCompany.FechaEmpresaTrabalho();
}
return companiesList;
}
}
}
| 60.720339 | 311 | 0.607955 | [
"MIT"
] | Everest89/ERP10Extensibility | Implementation/SIMulticompanyOrganizations/SIMulticompanyOrganizations/CrossCompany/PayablesReceivables.cs | 7,167 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class BTests
{
const int TimeLimit = 2000;
const double RelativeError = 1e-9;
[TestMethod, Timeout(TimeLimit)]
public void Test1()
{
const string input = @"6 1 2 2
2 1 1 3 0 2
";
const string output = @"5
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
[TestMethod, Timeout(TimeLimit)]
public void Test2()
{
const string input = @"6 1 5 2
2 1 1 3 0 2
";
const string output = @"3
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
[TestMethod, Timeout(TimeLimit)]
public void Test3()
{
const string input = @"10 4 8 5
7 2 3 6 1 6 5 4 6 5
";
const string output = @"8
";
Tester.InOutTest(Tasks.B.Solve, input, output);
}
}
}
| 21.333333 | 59 | 0.526042 | [
"CC0-1.0"
] | AconCavy/AtCoder.Tasks.CS | AGC/AGC041/Tests/BTests.cs | 960 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace KaupischIT.Extensions
{
/// <summary>
/// Stellt Erweiterungsmethoden für die IEnumerable-Schnittstelle bereit
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Gibt die eine leere Sequenz zurück, wenn die angegebene Sequenz null ist.
/// </summary>
/// <typeparam name="T">Der Typ der Elemente von source.</typeparam>
/// <param name="source">Die Sequenz, für die eine leere Sequenz zurückgegeben werden soll, wenn sie null ist.</param>
/// <returns>Eine leere Auflistung, wenn source null ist; andernfalls source selbst.</returns>
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source) => source ?? Enumerable.Empty<T>();
/// <summary>
/// Korreliert die Elemente einer Sequenz anhand der Gleichheit der Schlüssel. Schlüssel werden mithilfe des Standardgleichheitsvergleichs verglichen.
/// </summary>
/// <typeparam name="TSource">Der Typ der Elemente der beiden Sequenzen.</typeparam>
/// <typeparam name="TKey">Der Typ der von den Schlüsselauswahlfunktionen zurückgegebenen Schlüssel.</typeparam>
/// <typeparam name="TResult"> Der Typ der Ergebniselemente.</typeparam>
/// <param name="source">Die Sequenz, die mit sich selbst verknüpft werden soll</param>
/// <param name="outerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der ersten Sequenz.</param>
/// <param name="innerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der zweiten Sequenz.</param>
/// <param name="resultSelector">Eine Funktion zum Erstellen eines Ergebniselements anhand eines Element aus der ersten Sequenz und einer Auflistung von übereinstimmenden Elementen aus der zweiten Sequenz.</param>
/// <returns>Ein System.Collections.Generic.IEnumerable, das Elemente vom Typ TResult enthält, die durch Ausführen eines Group Joins von zwei Sequenzen ermittelt werden.</returns>
public static IEnumerable<TResult> SelfJoin<TSource, TKey, TResult>(this IEnumerable<TSource> source,Func<TSource,TKey> outerKeySelector,Func<TSource,TKey> innerKeySelector,Func<TSource,TSource,TResult> resultSelector)
{
return source.Join(source,outerKeySelector,innerKeySelector,resultSelector);
}
/// <summary>
/// Korreliert die Elemente einer Sequenz anhand der Gleichheit der Schlüssel. Dabei werden alle Tupel der ersten Sequenz in die Ergebnisrelation aufgenommen und jene Attribute eines Tupels mit Nullwerten aufgefüllt, die keinen Join-Partner aus der zweiten Sequenz gefunden haben. Schlüssel werden mithilfe des Standardgleichheitsvergleichs verglichen.
/// </summary>
/// <typeparam name="TSource">Der Typ der Elemente der beiden Sequenzen.</typeparam>
/// <typeparam name="TKey">Der Typ der von den Schlüsselauswahlfunktionen zurückgegebenen Schlüssel.</typeparam>
/// <typeparam name="TResult"> Der Typ der Ergebniselemente.</typeparam>
/// <param name="source">Die Sequenz, die mit sich selbst verknüpft werden soll</param>
/// <param name="outerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der ersten Sequenz.</param>
/// <param name="innerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der zweiten Sequenz.</param>
/// <param name="resultSelector">Eine Funktion zum Erstellen eines Ergebniselements anhand eines Element aus der ersten Sequenz und einer Auflistung von übereinstimmenden Elementen aus der zweiten Sequenz.</param>
/// <returns>Ein System.Collections.Generic.IEnumerable, das Elemente vom Typ TResult enthält, die durch Ausführen eines Group Joins von zwei Sequenzen ermittelt werden.</returns>
public static IEnumerable<TResult> SelfLeftOuterJoin<TSource, TKey, TResult>(this IEnumerable<TSource> source,Func<TSource,TKey> outerKeySelector,Func<TSource,TKey> innerKeySelector,Func<TSource,TSource,TResult> resultSelector)
{
return source.LeftOuterJoin(source,outerKeySelector,innerKeySelector,resultSelector);
}
/// <summary>
/// Korreliert die Elemente von zwei Sequenzen anhand der Gleichheit der Schlüssel. Dabei werden alle Tupel der ersten Sequenz in die Ergebnisrelation aufgenommen und jene Attribute eines Tupels mit Nullwerten aufgefüllt, die keinen Join-Partner aus der zweiten Sequenz gefunden haben. Schlüssel werden mithilfe des Standardgleichheitsvergleichs verglichen.
/// </summary>
/// <typeparam name="TOuter">Der Typ der Elemente der ersten Sequenz.</typeparam>
/// <typeparam name="TInner">Der Typ der Elemente der zweiten Sequenz.</typeparam>
/// <typeparam name="TKey">Der Typ der von den Schlüsselauswahlfunktionen zurückgegebenen Schlüssel.</typeparam>
/// <typeparam name="TResult"> Der Typ der Ergebniselemente.</typeparam>
/// <param name="outer">Die erste zu verknüpfende Sequenz</param>
/// <param name="inner">Die Sequenz, die mit der ersten Sequenz verknüpft werden soll.</param>
/// <param name="outerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der ersten Sequenz.</param>
/// <param name="innerKeySelector"> Eine Funktion zum Extrahieren des Joinschlüssels aus jedem Element der zweiten Sequenz.</param>
/// <param name="resultSelector">Eine Funktion zum Erstellen eines Ergebniselements anhand eines Element aus der ersten Sequenz und einer Auflistung von übereinstimmenden Elementen aus der zweiten Sequenz.</param>
/// <returns>Ein System.Collections.Generic.IEnumerable, das Elemente vom Typ TResult enthält, die durch Ausführen eines Group Joins von zwei Sequenzen ermittelt werden.</returns>
public static IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer,IEnumerable<TInner> inner,Func<TOuter,TKey> outerKeySelector,Func<TInner,TKey> innerKeySelector,Func<TOuter,TInner,TResult> resultSelector)
{
return outer
.GroupJoin(inner,outerKeySelector,innerKeySelector,(outerItem,innerGroup) => innerGroup.DefaultIfEmpty().Select(innerGroupItem => resultSelector(outerItem,innerGroupItem)))
.SelectMany(value => value);
}
/// <summary>
/// Gruppiert eine Sequenz nach der angegebenen Datumsauswahlfunktion und fügt leere Gruppen für nicht vorhandene Datumswerte im gesamten Bereich der Sequenz ein.
/// Die leeren Gruppen werden so gewählt, dass stets der gesamte Monat befüllt wird.
/// </summary>
/// <typeparam name="TElement">Der Typ der Elemente der Eingabesequenz</typeparam>
/// <param name="source">Die Eingabesequenz</param>
/// <param name="dateSelector">Die Funktion zum Extrahieren des Datums aus jedem Element</param>
/// <returns>Eine Sequenz mit den gruppierten Elementen der Eingabesequenz</returns>
public static IEnumerable<IGrouping<DateTime,TElement>> FullDateGroupBy<TElement>(this IEnumerable<TElement> source,Func<TElement,DateTime?> dateSelector)
{
source = source.Where(item => dateSelector(item).HasValue).ToList(); // für Performance (sonst wird source jeweils bei Min,Max und GroupJoin evaluiert)
if (!source.Any())
return Enumerable.Empty<IGrouping<DateTime,TElement>>();
// Monatsanfang des kleinsten Datums der Eingabesequenz finden
DateTime minDate = source.Min(item => dateSelector(item).Value.Date);
minDate = minDate.AddDays(1-minDate.Day);
// Monatsende des größten Datums der Eingabesequenz finden
DateTime maxDate = source.Max(item => dateSelector(item).Value.Date);
maxDate = maxDate.AddDays(1-maxDate.Day).AddMonths(1).AddDays(-1);
// Datumsgruppierung durchführen
return EnumerableExtensions.FullDateGroupBy(source,element => dateSelector(element).Value.Date,minDate,maxDate);
}
/// <summary>
/// Gruppiert eine Sequenz nach der angegebenen Datumsauswahlfunktion und fügt leere Gruppen für nicht vorhandene Datumswerte im gesamten Bereich der Sequenz ein.
/// </summary>
/// <typeparam name="TElement">Der Typ der Elemente der Eingabesequenz</typeparam>
/// <param name="source">Die Eingabesequenz</param>
/// <param name="dateSelector">Die Funktion zum Extrahieren des Datums aus jedem Element</param>
/// <param name="minDate">Das Datum, mit dem die Ausgabesequenz begonnen wird</param>
/// <param name="maxDate">Das Datum, mit dem die Ausgabesequenz beendet wird</param>
/// <returns></returns>
public static IEnumerable<IGrouping<DateTime,TElement>> FullDateGroupBy<TElement>(this IEnumerable<TElement> source,Func<TElement,DateTime> dateSelector,DateTime minDate,DateTime maxDate)
{
return Enumerable.Range(0,(maxDate-minDate).Days+1).Select(i => minDate.AddDays(i))
.GroupJoin(source,date => date,item => dateSelector(item).Date,(date,group) => new Grouping<DateTime,TElement>(date,group))
.Cast<IGrouping<DateTime,TElement>>();
}
/// <summary>
/// Stellt eine Auflistung von Objekten dar, die über einen gemeinsamen Schlüssel verfügen
/// </summary>
/// <typeparam name="TKey">Der Typ des Schlüssels</typeparam>
/// <typeparam name="TValue">Der Typ der Werte</typeparam>
private class Grouping<TKey, TValue> : IGrouping<TKey,TValue>
{
public TKey Key { get; set; }
public IEnumerable<TValue> Values { get; set; }
public Grouping(TKey key,IEnumerable<TValue> values)
{
this.Key = key;
this.Values = values;
}
public IEnumerator<TValue> GetEnumerator() => this.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() { return this.Values.GetEnumerator(); ; }
}
}
}
| 66.895833 | 360 | 0.754386 | [
"MIT"
] | Kaupisch-IT/KaupischIT.Shared | KaupischIT.Extensions/EnumerableExtensions.cs | 9,689 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace EditingCollections.Data
{
public class PurchaseItem : INotifyPropertyChanged, IEditableObject
{
private ItemData _copyData;
private ItemData _currentData;
public PurchaseItem()
: this("New Item", 0, DateTime.Now)
{
}
public PurchaseItem(string desc, double price, DateTime endDate)
{
Description = desc;
Price = price;
OfferExpires = endDate;
}
public string Description
{
get { return _currentData.Description; }
set
{
if (_currentData.Description != value)
{
_currentData.Description = value;
NotifyPropertyChanged();
}
}
}
public double Price
{
get { return _currentData.Price; }
set
{
if (_currentData.Price != value)
{
_currentData.Price = value;
NotifyPropertyChanged();
}
}
}
public DateTime OfferExpires
{
get { return _currentData.OfferExpire; }
set
{
if (_currentData.OfferExpire != value)
{
_currentData.OfferExpire = value;
NotifyPropertyChanged();
}
}
}
public override string ToString() => $"{Description}, {Price:c}, {OfferExpires:D}";
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region IEditableObject Members
public void BeginEdit()
{
_copyData = _currentData;
}
public void CancelEdit()
{
_currentData = _copyData;
NotifyPropertyChanged("");
}
public void EndEdit()
{
_copyData = new ItemData();
}
#endregion
private struct ItemData
{
internal string Description;
internal DateTime OfferExpire;
internal double Price;
}
}
}
| 23.460177 | 91 | 0.519804 | [
"MIT"
] | darkzonecode/WPFSamples | WPFSamples/Data Binding/EditingCollections/Data/PurchaseItem.cs | 2,653 | C# |
using Neo.IO;
using Neo.IO.Data.LevelDB;
using Neo.IO.Json;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.Wallets;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using static System.IO.Path;
namespace Neo.Plugins
{
public class RpcNep17Tracker : Plugin, IPersistencePlugin
{
private const byte Nep17BalancePrefix = 0xf8;
private const byte Nep17TransferSentPrefix = 0xf9;
private const byte Nep17TransferReceivedPrefix = 0xfa;
private DB _db;
private WriteBatch _writeBatch;
private string _dbPath;
private bool _shouldTrackHistory;
private bool _recordNullAddressHistory;
private uint _maxResults;
private uint _network;
private Snapshot _levelDbSnapshot;
private NeoSystem System;
public override string Description => "Enquiries NEP-17 balances and transaction history of accounts through RPC";
protected override void OnSystemLoaded(NeoSystem system)
{
if (system.Settings.Network != _network) return;
System = system;
string path = string.Format(_dbPath, system.Settings.Network.ToString("X8"));
_db = DB.Open(GetFullPath(path), new Options { CreateIfMissing = true });
RpcServerPlugin.RegisterMethods(this, _network);
}
protected override void Configure()
{
_dbPath = GetConfiguration().GetSection("DBPath").Value ?? "Nep17BalanceData";
_shouldTrackHistory = (GetConfiguration().GetSection("TrackHistory").Value ?? true.ToString()) != false.ToString();
_recordNullAddressHistory = (GetConfiguration().GetSection("RecordNullAddressHistory").Value ?? false.ToString()) != false.ToString();
_maxResults = uint.Parse(GetConfiguration().GetSection("MaxResults").Value ?? "1000");
_network = uint.Parse(GetConfiguration().GetSection("Network").Value ?? "5195086");
}
private void ResetBatch()
{
_writeBatch = new WriteBatch();
_levelDbSnapshot?.Dispose();
_levelDbSnapshot = _db.GetSnapshot();
}
private static byte[] Key(byte prefix, ISerializable key)
{
byte[] buffer = new byte[key.Size + 1];
using (MemoryStream ms = new MemoryStream(buffer, true))
using (BinaryWriter writer = new BinaryWriter(ms))
{
writer.Write(prefix);
key.Serialize(writer);
}
return buffer;
}
private void Put(byte prefix, ISerializable key, ISerializable value)
{
_writeBatch.Put(Key(prefix, key), value.ToArray());
}
private void Delete(byte prefix, ISerializable key)
{
_writeBatch.Delete(Key(prefix, key));
}
private void RecordTransferHistory(DataCache snapshot, UInt160 scriptHash, UInt160 from, UInt160 to, BigInteger amount, UInt256 txHash, ref ushort transferIndex)
{
if (!_shouldTrackHistory) return;
UInt256 hash = NativeContract.Ledger.CurrentHash(snapshot);
uint height = NativeContract.Ledger.CurrentIndex(snapshot);
TrimmedBlock block = NativeContract.Ledger.GetTrimmedBlock(snapshot, hash);
if (_recordNullAddressHistory || from != UInt160.Zero)
{
Put(Nep17TransferSentPrefix,
new Nep17TransferKey(from, block.Header.Timestamp, scriptHash, transferIndex),
new Nep17Transfer
{
Amount = amount,
UserScriptHash = to,
BlockIndex = height,
TxHash = txHash
});
}
if (_recordNullAddressHistory || to != UInt160.Zero)
{
Put(Nep17TransferReceivedPrefix,
new Nep17TransferKey(to, block.Header.Timestamp, scriptHash, transferIndex),
new Nep17Transfer
{
Amount = amount,
UserScriptHash = from,
BlockIndex = height,
TxHash = txHash
});
}
transferIndex++;
}
private void HandleNotification(DataCache snapshot, IVerifiable scriptContainer, UInt160 scriptHash, string eventName,
VM.Types.Array stateItems,
Dictionary<Nep17BalanceKey, Nep17Balance> nep17BalancesChanged, ref ushort transferIndex)
{
if (eventName != "Transfer") return;
if (stateItems.Count != 3) return;
if (!(stateItems[0].IsNull) && !(stateItems[0] is VM.Types.ByteString))
return;
if (!(stateItems[1].IsNull) && !(stateItems[1] is VM.Types.ByteString))
return;
var amountItem = stateItems[2];
if (!(amountItem is VM.Types.ByteString || amountItem is VM.Types.Integer))
return;
byte[] fromBytes = stateItems[0].IsNull ? null : stateItems[0].GetSpan().ToArray();
if (fromBytes != null && fromBytes.Length != UInt160.Length)
return;
byte[] toBytes = stateItems[1].IsNull ? null : stateItems[1].GetSpan().ToArray();
if (toBytes != null && toBytes.Length != UInt160.Length)
return;
if (fromBytes == null && toBytes == null) return;
var from = UInt160.Zero;
var to = UInt160.Zero;
if (fromBytes != null)
{
from = new UInt160(fromBytes);
var fromKey = new Nep17BalanceKey(from, scriptHash);
if (!nep17BalancesChanged.ContainsKey(fromKey)) nep17BalancesChanged.Add(fromKey, new Nep17Balance());
}
if (toBytes != null)
{
to = new UInt160(toBytes);
var toKey = new Nep17BalanceKey(to, scriptHash);
if (!nep17BalancesChanged.ContainsKey(toKey)) nep17BalancesChanged.Add(toKey, new Nep17Balance());
}
if (scriptContainer is Transaction transaction)
{
RecordTransferHistory(snapshot, scriptHash, from, to, amountItem.GetInteger(), transaction.Hash, ref transferIndex);
}
}
void IPersistencePlugin.OnPersist(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList<Blockchain.ApplicationExecuted> applicationExecutedList)
{
if (system.Settings.Network != _network) return;
// Start freshly with a new DBCache for each block.
ResetBatch();
Dictionary<Nep17BalanceKey, Nep17Balance> nep17BalancesChanged = new Dictionary<Nep17BalanceKey, Nep17Balance>();
ushort transferIndex = 0;
foreach (Blockchain.ApplicationExecuted appExecuted in applicationExecutedList)
{
// Executions that fault won't modify storage, so we can skip them.
if (appExecuted.VMState.HasFlag(VMState.FAULT)) continue;
foreach (var notifyEventArgs in appExecuted.Notifications)
{
if (!(notifyEventArgs?.State is VM.Types.Array stateItems) || stateItems.Count == 0)
continue;
HandleNotification(snapshot, notifyEventArgs.ScriptContainer, notifyEventArgs.ScriptHash, notifyEventArgs.EventName,
stateItems, nep17BalancesChanged, ref transferIndex);
}
}
foreach (var nep17BalancePair in nep17BalancesChanged)
{
// get guarantee accurate balances by calling balanceOf for keys that changed.
byte[] script;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitDynamicCall(nep17BalancePair.Key.AssetScriptHash, "balanceOf", nep17BalancePair.Key.UserScriptHash.ToArray());
script = sb.ToArray();
}
using (ApplicationEngine engine = ApplicationEngine.Run(script, snapshot, gas: 100000000, settings: system.Settings))
{
if (engine.State.HasFlag(VMState.FAULT)) continue;
if (engine.ResultStack.Count <= 0) continue;
nep17BalancePair.Value.Balance = engine.ResultStack.Pop().GetInteger();
}
nep17BalancePair.Value.LastUpdatedBlock = block.Index;
if (nep17BalancePair.Value.Balance.IsZero)
{
Delete(Nep17BalancePrefix, nep17BalancePair.Key);
continue;
}
Put(Nep17BalancePrefix, nep17BalancePair.Key, nep17BalancePair.Value);
}
}
void IPersistencePlugin.OnCommit(NeoSystem system, Block block, DataCache snapshot)
{
if (system.Settings.Network != _network) return;
_db.Write(WriteOptions.Default, _writeBatch);
}
bool IPersistencePlugin.ShouldThrowExceptionFromCommit(Exception ex)
{
return true;
}
private void AddTransfers(byte dbPrefix, UInt160 userScriptHash, ulong startTime, ulong endTime,
JArray parentJArray)
{
var prefix = new[] { dbPrefix }.Concat(userScriptHash.ToArray()).ToArray();
byte[] startTimeBytes, endTimeBytes;
if (BitConverter.IsLittleEndian)
{
startTimeBytes = BitConverter.GetBytes(BinaryPrimitives.ReverseEndianness(startTime));
endTimeBytes = BitConverter.GetBytes(BinaryPrimitives.ReverseEndianness(endTime));
}
else
{
startTimeBytes = BitConverter.GetBytes(startTime);
endTimeBytes = BitConverter.GetBytes(endTime);
}
var transferPairs = _db.FindRange<Nep17TransferKey, Nep17Transfer>(
prefix.Concat(startTimeBytes).ToArray(),
prefix.Concat(endTimeBytes).ToArray());
int resultCount = 0;
foreach (var (key, value) in transferPairs)
{
if (++resultCount > _maxResults) break;
JObject transfer = new JObject();
transfer["timestamp"] = key.TimestampMS;
transfer["assethash"] = key.AssetScriptHash.ToString();
transfer["transferaddress"] = value.UserScriptHash == UInt160.Zero ? null : value.UserScriptHash.ToAddress(System.Settings.AddressVersion);
transfer["amount"] = value.Amount.ToString();
transfer["blockindex"] = value.BlockIndex;
transfer["transfernotifyindex"] = key.BlockXferNotificationIndex;
transfer["txhash"] = value.TxHash.ToString();
parentJArray.Add(transfer);
}
}
private UInt160 GetScriptHashFromParam(string addressOrScriptHash)
{
return addressOrScriptHash.Length < 40 ?
addressOrScriptHash.ToScriptHash(System.Settings.AddressVersion) : UInt160.Parse(addressOrScriptHash);
}
[RpcMethod]
public JObject GetNep17Transfers(JArray _params)
{
if (!_shouldTrackHistory) throw new RpcException(-32601, "Method not found");
UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString());
// If start time not present, default to 1 week of history.
ulong startTime = _params.Count > 1 ? (ulong)_params[1].AsNumber() :
(DateTime.UtcNow - TimeSpan.FromDays(7)).ToTimestampMS();
ulong endTime = _params.Count > 2 ? (ulong)_params[2].AsNumber() : DateTime.UtcNow.ToTimestampMS();
if (endTime < startTime) throw new RpcException(-32602, "Invalid params");
JObject json = new JObject();
JArray transfersSent = new JArray();
json["sent"] = transfersSent;
JArray transfersReceived = new JArray();
json["received"] = transfersReceived;
json["address"] = userScriptHash.ToAddress(System.Settings.AddressVersion);
AddTransfers(Nep17TransferSentPrefix, userScriptHash, startTime, endTime, transfersSent);
AddTransfers(Nep17TransferReceivedPrefix, userScriptHash, startTime, endTime, transfersReceived);
return json;
}
[RpcMethod]
public JObject GetNep17Balances(JArray _params)
{
UInt160 userScriptHash = GetScriptHashFromParam(_params[0].AsString());
JObject json = new JObject();
JArray balances = new JArray();
json["balance"] = balances;
json["address"] = userScriptHash.ToAddress(System.Settings.AddressVersion);
using (Iterator it = _db.NewIterator(ReadOptions.Default))
{
byte[] prefix = Key(Nep17BalancePrefix, userScriptHash);
for (it.Seek(prefix); it.Valid(); it.Next())
{
ReadOnlySpan<byte> key_bytes = it.Key();
if (!key_bytes.StartsWith(prefix)) break;
Nep17BalanceKey key = key_bytes[1..].AsSerializable<Nep17BalanceKey>();
if (NativeContract.ContractManagement.GetContract(System.StoreView, key.AssetScriptHash) is null)
continue;
Nep17Balance value = it.Value().AsSerializable<Nep17Balance>();
balances.Add(new JObject
{
["assethash"] = key.AssetScriptHash.ToString(),
["amount"] = value.Balance.ToString(),
["lastupdatedblock"] = value.LastUpdatedBlock
});
}
}
return json;
}
}
}
| 44.071429 | 169 | 0.588613 | [
"MIT"
] | PaschaC420/neo-modules | src/RpcNep17Tracker/RpcNep17Tracker.cs | 14,191 | C# |
using System;
using System.Collections.Generic;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.DataConstruction
{
public interface ITimePeriodTextListBuilder
{
void Add(TimePeriod timePeriod);
void AddRange(IEnumerable<TimePeriod> timePeriods);
IList<string> GetTimePeriodStrings();
}
}
| 24.928571 | 59 | 0.756447 | [
"MIT"
] | PublicHealthEngland/fingertips-open | PholioVisualisationWS/DataConstruction/ITimePeriodTextListBuilder.cs | 351 | C# |
using Microsoft.AspNetCore.Mvc;
using Sfa.Tl.ResultsAndCertification.Common.Enum;
using System.Threading.Tasks;
namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.PostResultsServiceControllerTests.PrsAddRommGet
{
public abstract class TestSetup : PostResultsServiceControllerTestBase
{
public IActionResult Result { get; private set; }
public int ProfileId { get; set; }
public int AssessmentId { get; set; }
public ComponentType ComponentType {get;set;}
public bool? IsBack { get; set; }
public async override Task When()
{
Result = await Controller.PrsAddRommAsync(ProfileId, AssessmentId, ComponentType, IsBack);
}
}
} | 36.4 | 114 | 0.710165 | [
"MIT"
] | SkillsFundingAgency/tl-result-and-certification | src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/PostResultsServiceControllerTests/PrsAddRommGet/TestSetup.cs | 730 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace FixedLoanCalculator
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
| 31.830508 | 143 | 0.632588 | [
"MIT"
] | BSchafer01/BSCustomFixedLoanCalculator | FixedLoanCalculator/Startup.cs | 1,878 | C# |
namespace Net.Xmpp.Extensions
{
/// <summary>
/// Describes how long a conference room will exist for.
/// </summary>
public enum RoomPersistence
{
/// <summary>
/// Not specified by the server.
/// </summary>
Undefined,
/// <summary>
/// A room that is destroyed if the last occupant exits.
/// </summary>
Temporary,
/// <summary>
/// A room that is not destroyed if the last occupant exits.
/// </summary>
Persistent
}
}
| 22.75 | 68 | 0.527473 | [
"MIT"
] | las-nsc/Net.Xmpp | Extensions/XEP-0045/RoomPersistence.cs | 548 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static partial class CookieCollectionTest
{
//These cookies are designed to have some similar and different properties so that each is unique in the eyes of a CookieComparer object
private static Cookie c1 = new Cookie("name1", "value");
private static Cookie c2 = new Cookie("name2", "value", "path"); //Same name, has a path
private static Cookie c3 = new Cookie("name2", "value", "different-path"); //Same name, different path
private static Cookie c4 = new Cookie("name3", "value", "path", "domain"); //Different name, has a domain
private static Cookie c5 = new Cookie("name3", "value", "path", "different-domain"); //Same name, different domain
private static CookieCollection CreateCookieCollection1()
{
CookieCollection cc = new CookieCollection();
cc.Add(c1);
cc.Add(c2);
cc.Add(c3);
cc.Add(c4);
cc.Add(c5);
return cc;
}
private static CookieCollection CreateCookieCollection2()
{
CookieCollection cc = new CookieCollection();
cc.Add(CreateCookieCollection1());
return cc;
}
[Fact]
public static void Add_Cookie_Success()
{
CookieCollection cc = CreateCookieCollection1();
Assert.Equal(5, cc.Count);
}
[Fact]
public static void Add_ExistingCookie_NameUpdatesCookie()
{
CookieCollection cc = CreateCookieCollection1();
c4.Name = "new-name";
cc.Add(c4);
Assert.Equal(c4, cc[c4.Name]);
c4.Name = "name3"; //Reset
}
[Fact]
public static void Add_ExistingCookie_PathUpdatesCookie()
{
CookieCollection cc = CreateCookieCollection1();
c4.Path = "new-path";
cc.Add(c4);
Assert.Equal(c4, cc[c4.Name]);
c4.Path = "path"; //Reset
}
[Fact]
public static void Add_ExistingCookie_DomainUpdatesCookie()
{
CookieCollection cc = CreateCookieCollection1();
c4.Domain = "new-domain";
cc.Add(c4);
Assert.Equal(c4, cc[c4.Name]);
c4.Domain = "domain"; //Reset
}
[Fact]
public static void Add_Cookie_Invalid()
{
CookieCollection cc = new CookieCollection();
Assert.Throws<ArgumentNullException>(() => cc.Add((Cookie)null));
}
[Fact]
public static void Add_CookieCollection_Success()
{
CookieCollection cc = CreateCookieCollection2();
Assert.Equal(5, cc.Count);
}
[Fact]
public static void Add_CookieCollection_Invalid()
{
CookieCollection cc = new CookieCollection();
Assert.Throws<ArgumentNullException>(() => cc.Add((CookieCollection)null));
}
[Fact]
public static void IsSynchronized_Get_Success()
{
ICollection cc = new CookieCollection();
Assert.False(cc.IsSynchronized);
}
[Fact]
public static void SyncRoot_Get_Success()
{
ICollection cc = new CookieCollection();
Assert.Equal(cc, cc.SyncRoot);
}
[Fact]
public static void CopyTo_Success()
{
ICollection cc = CreateCookieCollection1();
Array cookies = new object[cc.Count];
cc.CopyTo(cookies, 0);
Assert.Equal(cc.Count, cookies.Length);
}
[Fact]
public static void Enumerator_Index_Invalid()
{
CookieCollection cc = CreateCookieCollection1();
IEnumerator enumerator = cc.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index < 0
enumerator.MoveNext(); enumerator.MoveNext(); enumerator.MoveNext();
enumerator.MoveNext(); enumerator.MoveNext(); enumerator.MoveNext();
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index >= count
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index should be -1
}
[Fact]
public static void Enumerator_Version_Invalid()
{
CookieCollection cc = CreateCookieCollection1();
IEnumerator enumerator = cc.GetEnumerator();
enumerator.MoveNext();
cc.Add(new Cookie("name5", "value"));
object current = null;
var exception = Record.Exception(() => current = enumerator.Current);
// On full framework, enumerator.Current throws an exception because the collection has been modified after
// creating the enumerator.
if (exception == null)
{
Assert.NotNull(current);
}
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); // Enumerator out of sync
}
}
}
| 31.557471 | 144 | 0.578583 | [
"MIT"
] | 2E0PGS/corefx | src/System.Net.Primitives/tests/FunctionalTests/CookieCollectionTest.cs | 5,491 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using DqtApi.DataStore.Crm.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
namespace DqtApi.Tests
{
public partial class TestDataHelper
{
public async Task<CreatePersonResult> CreatePerson(
bool earlyYears = false,
bool assessmentOnly = false,
bool withQualification = false,
bool withActiveSanction = false)
{
if (earlyYears && assessmentOnly)
{
throw new ArgumentException($"Cannot set both {nameof(earlyYears)} and {nameof(assessmentOnly)}.");
}
var teacherId = Guid.NewGuid();
var firstName = Faker.Name.First();
var middleName = Faker.Name.Middle();
var lastName = Faker.Name.Last();
var birthDate = Faker.Identification.DateOfBirth();
var nino = Faker.Identification.UkNationalInsuranceNumber();
var email = Faker.Internet.Email();
var programmeType = earlyYears ? dfeta_ITTProgrammeType.EYITTAssessmentOnly :
assessmentOnly ? dfeta_ITTProgrammeType.AssessmentOnlyRoute :
dfeta_ITTProgrammeType.RegisteredTeacherProgramme;
var ittProviderUkprn = "10044534";
var lookupRequestBuilder = _dataverseAdapter.CreateMultipleRequestBuilder();
var getIttProviderTask = _globalCache.GetOrCreateAsync(
CacheKeys.GetIttProviderOrganizationByUkprnKey(ittProviderUkprn),
_ => _dataverseAdapter.GetOrganizationsByUkprn(ittProviderUkprn, columnNames: Array.Empty<string>(), lookupRequestBuilder)
.ContinueWith(t => t.Result.SingleOrDefault()));
var earlyYearsStatus = "220"; // 220 == 'Early Years Trainee'
var getEarlyYearsStatusTask = earlyYears ?
_globalCache.GetOrCreateAsync(
CacheKeys.GetEarlyYearsStatusKey(earlyYearsStatus),
_ => _dataverseAdapter.GetEarlyYearsStatus(earlyYearsStatus, lookupRequestBuilder)) :
Task.FromResult<dfeta_earlyyearsstatus>(null);
var teacherStatus = programmeType == dfeta_ITTProgrammeType.AssessmentOnlyRoute ?
"212" : // 212 == 'AOR Candidate'
"211"; // 211 == 'Trainee Teacher:DMS'
var getTeacherStatusTask = !earlyYears ?
_globalCache.GetOrCreateAsync(
CacheKeys.GetTeacherStatusKey(teacherStatus),
_ => _dataverseAdapter.GetTeacherStatus(teacherStatus, qtsDateRequired: false, lookupRequestBuilder)) :
Task.FromResult<dfeta_teacherstatus>(null);
var country = "XK";
var getCountryCodeTask = _globalCache.GetOrCreateAsync(
CacheKeys.GetCountryKey(country),
_ => _dataverseAdapter.GetCountry(country, lookupRequestBuilder));
var heSubjectCode = "100366"; // computer science
var getHeSubjectTask = _globalCache.GetOrCreateAsync(
CacheKeys.GetHeSubjectKey(heSubjectCode),
_ => _dataverseAdapter.GetHeSubjectByCode(heSubjectCode, lookupRequestBuilder));
var qualificationName = "First Degree";
var getQualificationTask = _globalCache.GetOrCreateAsync(
CacheKeys.GetHeQualificationKey(qualificationName),
_ => _dataverseAdapter.GetHeQualificationByName(qualificationName, lookupRequestBuilder));
await lookupRequestBuilder.Execute();
var ittProvider = getIttProviderTask.Result;
var earlyYearsStatusId = getEarlyYearsStatusTask?.Result?.Id;
var teacherStatusId = getTeacherStatusTask?.Result?.Id;
var countryId = getCountryCodeTask.Result.Id;
var heSubjectId = getHeSubjectTask.Result.Id;
var qualificationId = getQualificationTask.Result.Id;
var txnRequestBuilder = _dataverseAdapter.CreateTransactionRequestBuilder();
txnRequestBuilder.AddRequests(
new CreateRequest()
{
Target = new Contact()
{
Id = teacherId,
FirstName = firstName,
MiddleName = middleName,
LastName = lastName,
BirthDate = birthDate,
dfeta_NINumber = nino,
EMailAddress1 = email,
Address1_Line1 = Faker.Address.StreetAddress(),
Address1_City = Faker.Address.City(),
Address1_Country = "United Kingdom",
Address1_PostalCode = Faker.Address.UkPostCode()
}
},
new UpdateRequest()
{
Target = new Contact()
{
Id = teacherId,
dfeta_TRNAllocateRequest = DateTime.UtcNow
}
});
var createIttTask = txnRequestBuilder.AddRequest<CreateResponse>(new CreateRequest()
{
Target = new dfeta_initialteachertraining()
{
dfeta_PersonId = new EntityReference(Contact.EntityLogicalName, teacherId),
dfeta_EstablishmentId = new EntityReference(Account.EntityLogicalName, ittProvider.Id),
dfeta_ProgrammeType = programmeType,
dfeta_Result = assessmentOnly ? dfeta_ITTResult.UnderAssessment : dfeta_ITTResult.InTraining
}
});
var createQtsTask = txnRequestBuilder.AddRequest<CreateResponse>(new CreateRequest()
{
Target = new dfeta_qtsregistration()
{
dfeta_PersonId = new EntityReference(Contact.EntityLogicalName, teacherId),
dfeta_EarlyYearsStatusId = earlyYearsStatusId.HasValue ? new EntityReference(dfeta_earlyyearsstatus.EntityLogicalName, earlyYearsStatusId.Value) : null,
dfeta_TeacherStatusId = teacherStatusId.HasValue ? new EntityReference(dfeta_teacherstatus.EntityLogicalName, teacherStatusId.Value) : null
}
});
if (withQualification)
{
txnRequestBuilder.AddRequest(new CreateRequest()
{
Target = new dfeta_qualification()
{
dfeta_PersonId = new EntityReference(Contact.EntityLogicalName, teacherId),
dfeta_HE_CountryId = new EntityReference(dfeta_qualification.EntityLogicalName, countryId),
dfeta_HE_EstablishmentId = new EntityReference(Account.EntityLogicalName, ittProvider.Id),
dfeta_Type = dfeta_qualification_dfeta_Type.HigherEducation,
dfeta_HE_ClassDivision = dfeta_classdivision.Pass,
dfeta_HE_CompletionDate = DateTime.Now.AddMonths(-1),
dfeta_HE_HESubject1Id = new EntityReference(dfeta_hesubject.EntityLogicalName, heSubjectId),
dfeta_HE_HEQualificationId = new EntityReference(dfeta_hequalification.EntityLogicalName, qualificationId)
}
});
}
if (withActiveSanction)
{
txnRequestBuilder.AddRequest(new CreateRequest()
{
Target = new dfeta_sanction()
{
dfeta_PersonId = new EntityReference(Contact.EntityLogicalName, teacherId),
dfeta_SanctionCodeId = new EntityReference(dfeta_sanction.EntityLogicalName, new Guid("95790cd0-c83b-e311-82ec-005056b1356a")) // T1
}
});
}
await txnRequestBuilder.Execute();
var ittId = createIttTask.GetResponse().id;
var qtsId = createQtsTask.GetResponse().id;
return new CreatePersonResult(teacherId, firstName, lastName, DateOnly.FromDateTime(birthDate), nino, ittId, qtsId, ittProvider.Id, ittProviderUkprn);
}
public record CreatePersonResult(
Guid TeacherId,
string FirstName,
string LastName,
DateOnly BirthDate,
string Nino,
Guid InitialTeacherTrainingId,
Guid QtsRegistrationId,
Guid IttProviderId,
string IttProviderUkprn);
}
}
| 46.811828 | 172 | 0.596302 | [
"MIT"
] | DFE-Digital/qualified-teachers-api | tests/DqtApi.Tests/TestDataHelper.CreatePerson.cs | 8,709 | C# |
#if UNITY_EDITOR || RUNTIME_CSG
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Sabresaurus.SabreCSG
{
public class VertexWeldToleranceOperation : VertexWeldOperation
{
protected float tolerance;
// Takes the selected vertices and welds together any of them that are within the tolerance distance of
// other vertices. Duplicate vertices and polygons are then removed.
public VertexWeldToleranceOperation (Polygon[] sourcePolygons, List<Vertex> sourceVertices, float tolerance)
: base(sourcePolygons, sourceVertices)
{
this.tolerance = tolerance;
}
public override void PerformWeld ()
{
List<List<Vertex>> groupedVertices = new List<List<Vertex>>();
VertexComparerTolerance comparer = new VertexComparerTolerance(tolerance);
// Group the selected vertices into clusters
for (int sourceVertexIndex = 0; sourceVertexIndex < sourceVertices.Count; sourceVertexIndex++)
{
Vertex sourceVertex = sourceVertices[sourceVertexIndex];
bool added = false;
for (int groupIndex = 0; groupIndex < groupedVertices.Count; groupIndex++)
{
if(groupedVertices[groupIndex].Contains(sourceVertex, comparer))
{
groupedVertices[groupIndex].Add(sourceVertex);
added = true;
break;
}
}
if(!added)
{
groupedVertices.Add(new List<Vertex>() { sourceVertex } );
}
}
for (int groupIndex = 0; groupIndex < groupedVertices.Count; groupIndex++)
{
List<Vertex> vertices = groupedVertices[groupIndex];
// Ignoring any groups that only contain one vertex
if(vertices.Count > 1)
{
// New position for the vertices is their center
Vector3 newPosition = Vector3.zero;
for (int vertexIndex = 0; vertexIndex < vertices.Count; vertexIndex++)
{
newPosition += vertices[vertexIndex].Position;
}
newPosition /= vertices.Count;
// Update all the selected vertices UVs
for (int vertexIndex = 0; vertexIndex < vertices.Count; vertexIndex++)
{
Polygon polygon = vertexPolygonMappings[vertices[vertexIndex]];
vertices[vertexIndex].UV = GeometryHelper.GetUVForPosition(polygon, newPosition);
}
// Update all the selected vertices to their new position
for (int vertexIndex = 0; vertexIndex < vertices.Count; vertexIndex++)
{
vertices[vertexIndex].Position = newPosition;
}
}
}
}
private class VertexComparerTolerance : IEqualityComparer<Vertex>
{
float squareTolerance; // Using square distance for comparisons is quicker
public VertexComparerTolerance (float tolerance)
{
this.squareTolerance = tolerance * tolerance;
}
public bool Equals (Vertex x, Vertex y)
{
float squareMagnitude = (x.Position - y.Position).sqrMagnitude;
return (squareMagnitude <= squareTolerance);
}
public int GetHashCode (Vertex obj)
{
// The similarity or difference between two positions can only be calculated if both are supplied
// when Distinct is called GetHashCode is used to determine which values are in collision first
// therefore we return the same hash code for all values to ensure all comparisons must use
// our Equals method to properly determine which values are actually considered equal
return 1;
}
}
}
}
#endif
| 30.724771 | 110 | 0.709764 | [
"MIT"
] | BentouDev/SenseiJam2017 | Assets/SabreCSG/Scripts/Tools/Utilities/Vertex Weld Ops/VertexWeldToleranceOperation.cs | 3,351 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using RVTR.Account.ObjectModel.Models;
using Xunit;
namespace RVTR.Account.UnitTesting.Tests
{
public class BankCardModelTest
{
public static readonly IEnumerable<Object[]> _bankCards = new List<Object[]>
{
new object[]
{
new BankCardModel()
{
Id = 0,
Expiry = DateTime.Now,
Number = "378282246310005"
}
},
new object[]
{
new BankCardModel()
{
Id = 0,
Expiry = DateTime.Now,
Number = "6011111111111117"
}
},
new object[]
{
new BankCardModel()
{
Id = 0,
Expiry = DateTime.Now,
Number = "5555555555554444"
}
},
new object[]
{
new BankCardModel()
{
Id = 0,
Expiry = DateTime.Now,
Number = "4111111111111111"
}
}
};
[Theory]
[MemberData(nameof(_bankCards))]
public void Test_Create_BankCardModel(BankCardModel bankCard)
{
var validationContext = new ValidationContext(bankCard);
var actual = Validator.TryValidateObject(bankCard, validationContext, null, true);
Assert.True(actual);
}
[Theory]
[MemberData(nameof(_bankCards))]
public void Test_Validate_BankCardModel(BankCardModel bankCard)
{
var validationContext = new ValidationContext(bankCard);
Assert.Empty(bankCard.Validate(validationContext));
}
}
}
| 22.225352 | 88 | 0.580482 | [
"MIT"
] | 2006-jun15-net/rvtr-svc-account | aspnet/RVTR.Account.UnitTesting/Tests/BankCardModelTest.cs | 1,578 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lpp.Dns.Data
{
[Table("DataMartAvailabilityPeriods_v2")]
public class DataMartAvailabilityPeriod_v2
{
[Key, Column(Order = 0)]
public Guid DataMartID { get; set; }
public DataMart DataMart { get; set; }
[Key, Column(Order = 1)]
public string DataTable { get; set; }
[Key, Column(Order = 2)]
public string PeriodCategory { get; set; }
[Key, Column(Order = 3)]
public string Period { get; set; }
public int Year { get; set; }
public int? Quarter { get; set; }
}
internal class DataMartAvailabilityPeriod_v2Configuration : EntityTypeConfiguration<DataMartAvailabilityPeriod_v2>
{
public DataMartAvailabilityPeriod_v2Configuration()
{
Property(x => x.DataMartID).IsRequired();
Property(x => x.DataTable).HasMaxLength(80).IsRequired();
Property(x => x.Period).HasMaxLength(10).IsRequired();
Property(x => x.PeriodCategory).HasColumnType("char").HasMaxLength(1).IsRequired();
}
}
}
| 34.25641 | 118 | 0.661677 | [
"Apache-2.0"
] | Missouri-BMI/popmednet | Lpp.Dns.Data/DataMarts/DataMartAvailabilityPeriod_v2.cs | 1,338 | C# |
/*
* Stocks API For Digital Portals
*
* The stocks API features a screener to search for equity instruments based on stock-specific parameters. Parameters for up to three fiscal years might now be used in one request; data is available for the ten most recent completed fiscal years. Estimates are available for the current and two consecutive fiscal years. A separate endpoint returns the possible values and value ranges for the parameters that the endpoint /stock/notation/screener/search accepts: Application developers can request the values and value ranges only for a restricted set of notations that match predefined parameters. This functionality may be used to pre-fill the values and value ranges of the parameters of the /stock/notation/screener/search endpoint so that performing a search always leads to a non-empty set of notations. The endpoint /stock/notation/ranking/intraday/list ranks stocks notations using intraday figures, for example to build a gainers/losers list. Additional endpoints include end-of-day benchmark key figures, and selected fundamentals (as of end of fiscal year and with potentially daily updates). This API is fully integrated with the corresponding Quotes API, allowing access to detailed price and performance information of instruments, as well as basic security identifier cross-reference. For direct access to price histories, please refer to the Time Series API for Digital Portals. Similar criteria based screener APIs exist for fixed income instruments and securitized derivatives: See the Bonds API and the Securitized Derivatives API for details.
*
* The version of the OpenAPI document: 2
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.StocksAPIforDigitalPortals.Client.OpenAPIDateConverter;
namespace FactSet.SDK.StocksAPIforDigitalPortals.Model
{
/// <summary>
/// Possible values and value ranges of the parameters.
/// </summary>
[DataContract(Name = "inline_response_200_12_data")]
public partial class InlineResponse20012Data : IEquatable<InlineResponse20012Data>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InlineResponse20012Data" /> class.
/// </summary>
/// <param name="totalCount">Number of notations that satisfy the request parameters, hence have been used to retrieve the possible values and value ranges..</param>
/// <param name="valueUnit">List of value unit identifiers. See endpoint `/basic/valueUnit/list` for possible values..</param>
/// <param name="market">List of market identifiers. See endpoint `/basic/market/list` for possible values..</param>
/// <param name="stockType">List of stock types..</param>
/// <param name="industryClassification">Lists of categories of the industry classification. Here, an industry is a category from any level of category system FactSet Revere Business Industry Classification System (RBICS). Starting with the most coarse level (one), for each level of the category system, the list of categories of the stocks, matching the parameters, is returned. See endpoint `/category/listBySystem` with `id=48` for possible values..</param>
/// <param name="company">company.</param>
/// <param name="compliance">compliance.</param>
/// <param name="reportedKeyFigures">reportedKeyFigures.</param>
/// <param name="performance">performance.</param>
/// <param name="volatility">volatility.</param>
/// <param name="tradingValue">tradingValue.</param>
/// <param name="simpleMovingAverage">simpleMovingAverage.</param>
/// <param name="rsiWilder">rsiWilder.</param>
/// <param name="recommendation">recommendation.</param>
/// <param name="estimates">estimates.</param>
public InlineResponse20012Data(decimal totalCount = default(decimal), List<InlineResponse20012DataValueUnit> valueUnit = default(List<InlineResponse20012DataValueUnit>), List<InlineResponse20012DataMarket> market = default(List<InlineResponse20012DataMarket>), List<InlineResponse20012DataStockType> stockType = default(List<InlineResponse20012DataStockType>), List<InlineResponse20012DataIndustryClassification> industryClassification = default(List<InlineResponse20012DataIndustryClassification>), InlineResponse20012DataCompany company = default(InlineResponse20012DataCompany), InlineResponse20012DataCompliance compliance = default(InlineResponse20012DataCompliance), InlineResponse20012DataReportedKeyFigures reportedKeyFigures = default(InlineResponse20012DataReportedKeyFigures), InlineResponse20012DataPerformance performance = default(InlineResponse20012DataPerformance), InlineResponse20012DataVolatility volatility = default(InlineResponse20012DataVolatility), InlineResponse20012DataTradingValue tradingValue = default(InlineResponse20012DataTradingValue), InlineResponse20012DataSimpleMovingAverage simpleMovingAverage = default(InlineResponse20012DataSimpleMovingAverage), InlineResponse20012DataRsiWilder rsiWilder = default(InlineResponse20012DataRsiWilder), InlineResponse20012DataRecommendation recommendation = default(InlineResponse20012DataRecommendation), InlineResponse20012DataEstimates estimates = default(InlineResponse20012DataEstimates))
{
this.TotalCount = totalCount;
this.ValueUnit = valueUnit;
this.Market = market;
this.StockType = stockType;
this.IndustryClassification = industryClassification;
this.Company = company;
this.Compliance = compliance;
this.ReportedKeyFigures = reportedKeyFigures;
this.Performance = performance;
this.Volatility = volatility;
this.TradingValue = tradingValue;
this.SimpleMovingAverage = simpleMovingAverage;
this.RsiWilder = rsiWilder;
this.Recommendation = recommendation;
this.Estimates = estimates;
}
/// <summary>
/// Number of notations that satisfy the request parameters, hence have been used to retrieve the possible values and value ranges.
/// </summary>
/// <value>Number of notations that satisfy the request parameters, hence have been used to retrieve the possible values and value ranges.</value>
[DataMember(Name = "totalCount", EmitDefaultValue = false)]
public decimal TotalCount { get; set; }
/// <summary>
/// List of value unit identifiers. See endpoint `/basic/valueUnit/list` for possible values.
/// </summary>
/// <value>List of value unit identifiers. See endpoint `/basic/valueUnit/list` for possible values.</value>
[DataMember(Name = "valueUnit", EmitDefaultValue = false)]
public List<InlineResponse20012DataValueUnit> ValueUnit { get; set; }
/// <summary>
/// List of market identifiers. See endpoint `/basic/market/list` for possible values.
/// </summary>
/// <value>List of market identifiers. See endpoint `/basic/market/list` for possible values.</value>
[DataMember(Name = "market", EmitDefaultValue = false)]
public List<InlineResponse20012DataMarket> Market { get; set; }
/// <summary>
/// List of stock types.
/// </summary>
/// <value>List of stock types.</value>
[DataMember(Name = "stockType", EmitDefaultValue = false)]
public List<InlineResponse20012DataStockType> StockType { get; set; }
/// <summary>
/// Lists of categories of the industry classification. Here, an industry is a category from any level of category system FactSet Revere Business Industry Classification System (RBICS). Starting with the most coarse level (one), for each level of the category system, the list of categories of the stocks, matching the parameters, is returned. See endpoint `/category/listBySystem` with `id=48` for possible values.
/// </summary>
/// <value>Lists of categories of the industry classification. Here, an industry is a category from any level of category system FactSet Revere Business Industry Classification System (RBICS). Starting with the most coarse level (one), for each level of the category system, the list of categories of the stocks, matching the parameters, is returned. See endpoint `/category/listBySystem` with `id=48` for possible values.</value>
[DataMember(Name = "industryClassification", EmitDefaultValue = false)]
public List<InlineResponse20012DataIndustryClassification> IndustryClassification { get; set; }
/// <summary>
/// Gets or Sets Company
/// </summary>
[DataMember(Name = "company", EmitDefaultValue = false)]
public InlineResponse20012DataCompany Company { get; set; }
/// <summary>
/// Gets or Sets Compliance
/// </summary>
[DataMember(Name = "compliance", EmitDefaultValue = false)]
public InlineResponse20012DataCompliance Compliance { get; set; }
/// <summary>
/// Gets or Sets ReportedKeyFigures
/// </summary>
[DataMember(Name = "reportedKeyFigures", EmitDefaultValue = false)]
public InlineResponse20012DataReportedKeyFigures ReportedKeyFigures { get; set; }
/// <summary>
/// Gets or Sets Performance
/// </summary>
[DataMember(Name = "performance", EmitDefaultValue = false)]
public InlineResponse20012DataPerformance Performance { get; set; }
/// <summary>
/// Gets or Sets Volatility
/// </summary>
[DataMember(Name = "volatility", EmitDefaultValue = false)]
public InlineResponse20012DataVolatility Volatility { get; set; }
/// <summary>
/// Gets or Sets TradingValue
/// </summary>
[DataMember(Name = "tradingValue", EmitDefaultValue = false)]
public InlineResponse20012DataTradingValue TradingValue { get; set; }
/// <summary>
/// Gets or Sets SimpleMovingAverage
/// </summary>
[DataMember(Name = "simpleMovingAverage", EmitDefaultValue = false)]
public InlineResponse20012DataSimpleMovingAverage SimpleMovingAverage { get; set; }
/// <summary>
/// Gets or Sets RsiWilder
/// </summary>
[DataMember(Name = "rsiWilder", EmitDefaultValue = false)]
public InlineResponse20012DataRsiWilder RsiWilder { get; set; }
/// <summary>
/// Gets or Sets Recommendation
/// </summary>
[DataMember(Name = "recommendation", EmitDefaultValue = false)]
public InlineResponse20012DataRecommendation Recommendation { get; set; }
/// <summary>
/// Gets or Sets Estimates
/// </summary>
[DataMember(Name = "estimates", EmitDefaultValue = false)]
public InlineResponse20012DataEstimates Estimates { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class InlineResponse20012Data {\n");
sb.Append(" TotalCount: ").Append(TotalCount).Append("\n");
sb.Append(" ValueUnit: ").Append(ValueUnit).Append("\n");
sb.Append(" Market: ").Append(Market).Append("\n");
sb.Append(" StockType: ").Append(StockType).Append("\n");
sb.Append(" IndustryClassification: ").Append(IndustryClassification).Append("\n");
sb.Append(" Company: ").Append(Company).Append("\n");
sb.Append(" Compliance: ").Append(Compliance).Append("\n");
sb.Append(" ReportedKeyFigures: ").Append(ReportedKeyFigures).Append("\n");
sb.Append(" Performance: ").Append(Performance).Append("\n");
sb.Append(" Volatility: ").Append(Volatility).Append("\n");
sb.Append(" TradingValue: ").Append(TradingValue).Append("\n");
sb.Append(" SimpleMovingAverage: ").Append(SimpleMovingAverage).Append("\n");
sb.Append(" RsiWilder: ").Append(RsiWilder).Append("\n");
sb.Append(" Recommendation: ").Append(Recommendation).Append("\n");
sb.Append(" Estimates: ").Append(Estimates).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as InlineResponse20012Data);
}
/// <summary>
/// Returns true if InlineResponse20012Data instances are equal
/// </summary>
/// <param name="input">Instance of InlineResponse20012Data to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InlineResponse20012Data input)
{
if (input == null)
{
return false;
}
return
(
this.TotalCount == input.TotalCount ||
this.TotalCount.Equals(input.TotalCount)
) &&
(
this.ValueUnit == input.ValueUnit ||
this.ValueUnit != null &&
input.ValueUnit != null &&
this.ValueUnit.SequenceEqual(input.ValueUnit)
) &&
(
this.Market == input.Market ||
this.Market != null &&
input.Market != null &&
this.Market.SequenceEqual(input.Market)
) &&
(
this.StockType == input.StockType ||
this.StockType != null &&
input.StockType != null &&
this.StockType.SequenceEqual(input.StockType)
) &&
(
this.IndustryClassification == input.IndustryClassification ||
this.IndustryClassification != null &&
input.IndustryClassification != null &&
this.IndustryClassification.SequenceEqual(input.IndustryClassification)
) &&
(
this.Company == input.Company ||
(this.Company != null &&
this.Company.Equals(input.Company))
) &&
(
this.Compliance == input.Compliance ||
(this.Compliance != null &&
this.Compliance.Equals(input.Compliance))
) &&
(
this.ReportedKeyFigures == input.ReportedKeyFigures ||
(this.ReportedKeyFigures != null &&
this.ReportedKeyFigures.Equals(input.ReportedKeyFigures))
) &&
(
this.Performance == input.Performance ||
(this.Performance != null &&
this.Performance.Equals(input.Performance))
) &&
(
this.Volatility == input.Volatility ||
(this.Volatility != null &&
this.Volatility.Equals(input.Volatility))
) &&
(
this.TradingValue == input.TradingValue ||
(this.TradingValue != null &&
this.TradingValue.Equals(input.TradingValue))
) &&
(
this.SimpleMovingAverage == input.SimpleMovingAverage ||
(this.SimpleMovingAverage != null &&
this.SimpleMovingAverage.Equals(input.SimpleMovingAverage))
) &&
(
this.RsiWilder == input.RsiWilder ||
(this.RsiWilder != null &&
this.RsiWilder.Equals(input.RsiWilder))
) &&
(
this.Recommendation == input.Recommendation ||
(this.Recommendation != null &&
this.Recommendation.Equals(input.Recommendation))
) &&
(
this.Estimates == input.Estimates ||
(this.Estimates != null &&
this.Estimates.Equals(input.Estimates))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = (hashCode * 59) + this.TotalCount.GetHashCode();
if (this.ValueUnit != null)
{
hashCode = (hashCode * 59) + this.ValueUnit.GetHashCode();
}
if (this.Market != null)
{
hashCode = (hashCode * 59) + this.Market.GetHashCode();
}
if (this.StockType != null)
{
hashCode = (hashCode * 59) + this.StockType.GetHashCode();
}
if (this.IndustryClassification != null)
{
hashCode = (hashCode * 59) + this.IndustryClassification.GetHashCode();
}
if (this.Company != null)
{
hashCode = (hashCode * 59) + this.Company.GetHashCode();
}
if (this.Compliance != null)
{
hashCode = (hashCode * 59) + this.Compliance.GetHashCode();
}
if (this.ReportedKeyFigures != null)
{
hashCode = (hashCode * 59) + this.ReportedKeyFigures.GetHashCode();
}
if (this.Performance != null)
{
hashCode = (hashCode * 59) + this.Performance.GetHashCode();
}
if (this.Volatility != null)
{
hashCode = (hashCode * 59) + this.Volatility.GetHashCode();
}
if (this.TradingValue != null)
{
hashCode = (hashCode * 59) + this.TradingValue.GetHashCode();
}
if (this.SimpleMovingAverage != null)
{
hashCode = (hashCode * 59) + this.SimpleMovingAverage.GetHashCode();
}
if (this.RsiWilder != null)
{
hashCode = (hashCode * 59) + this.RsiWilder.GetHashCode();
}
if (this.Recommendation != null)
{
hashCode = (hashCode * 59) + this.Recommendation.GetHashCode();
}
if (this.Estimates != null)
{
hashCode = (hashCode * 59) + this.Estimates.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 53.593264 | 1,570 | 0.607966 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/StocksAPIforDigitalPortals/v3/src/FactSet.SDK.StocksAPIforDigitalPortals/Model/InlineResponse20012Data.cs | 20,687 | 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("Sample.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample.Tests")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("fc016d96-efd4-4ee8-87ab-2f07ac0c5eb2")]
// 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.756757 | 84 | 0.743737 | [
"BSD-3-Clause"
] | andreabalducci/Prxm.Cqrs | Sample.Tests/Properties/AssemblyInfo.cs | 1,400 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Outputs.Jaegertracing.V1
{
[OutputType]
public sealed class JaegerSpecAgentAffinityPodAntiAffinity
{
public readonly ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Jaegertracing.V1.JaegerSpecAgentAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecution> PreferredDuringSchedulingIgnoredDuringExecution;
public readonly ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Jaegertracing.V1.JaegerSpecAgentAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution> RequiredDuringSchedulingIgnoredDuringExecution;
[OutputConstructor]
private JaegerSpecAgentAffinityPodAntiAffinity(
ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Jaegertracing.V1.JaegerSpecAgentAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecution> preferredDuringSchedulingIgnoredDuringExecution,
ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Jaegertracing.V1.JaegerSpecAgentAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution> requiredDuringSchedulingIgnoredDuringExecution)
{
PreferredDuringSchedulingIgnoredDuringExecution = preferredDuringSchedulingIgnoredDuringExecution;
RequiredDuringSchedulingIgnoredDuringExecution = requiredDuringSchedulingIgnoredDuringExecution;
}
}
}
| 54.5 | 223 | 0.831193 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/jaeger/dotnet/Kubernetes/Crds/Operators/Jaeger/Jaegertracing/V1/Outputs/JaegerSpecAgentAffinityPodAntiAffinity.cs | 1,635 | C# |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using System.Collections;
using Leap;
namespace Leap.Unity {
/** A physics model for our rigid hand made out of various Unity Collider. */
public class RigidHand : SkeletalHand {
public override ModelType HandModelType {
get {
return ModelType.Physics;
}
}
public float filtering = 0.5f;
public override bool SupportsEditorPersistence() {
return true;
}
public override void InitHand() {
base.InitHand();
}
public override void UpdateHand() {
for (int f = 0; f < fingers.Length; ++f) {
if (fingers[f] != null) {
fingers[f].UpdateFinger();
}
}
if (palm != null) {
Rigidbody palmBody = palm.GetComponent<Rigidbody>();
if (palmBody) {
palmBody.MovePosition(GetPalmCenter());
palmBody.MoveRotation(GetPalmRotation());
} else {
palm.position = GetPalmCenter();
palm.rotation = GetPalmRotation();
}
}
if (forearm != null) {
// Set arm dimensions.
CapsuleCollider capsule = forearm.GetComponent<CapsuleCollider>();
if (capsule != null) {
// Initialization
capsule.direction = 2;
forearm.localScale = new Vector3(1f / transform.lossyScale.x, 1f / transform.lossyScale.y, 1f / transform.lossyScale.z);
// Update
capsule.radius = GetArmWidth() / 2f;
capsule.height = GetArmLength() + GetArmWidth();
}
Rigidbody forearmBody = forearm.GetComponent<Rigidbody>();
if (forearmBody) {
forearmBody.MovePosition(GetArmCenter());
forearmBody.MoveRotation(GetArmRotation());
} else {
forearm.position = GetArmCenter();
forearm.rotation = GetArmRotation();
}
}
}
}
}
| 33.723684 | 131 | 0.514631 | [
"MIT"
] | CallumFerguson/VR-Protein | Assets/LeapMotion/Core/Scripts/Hands/RigidHand.cs | 2,563 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Generator.Shared.Utilities
{
public static class StringHelper
{
public static bool TryMultiReplace(string input, Dictionary<string, string> replacements, ref string result)
{
var regex = new Regex(string.Join("|", replacements.Keys));
if (regex.IsMatch(input))
{
result = regex.Replace(input, m => replacements[m.Value]);
return true;
}
result = input;
return false;
}
}
} | 23.428571 | 110 | 0.711382 | [
"MIT"
] | havenindustries/Amusoft.VisualStudio.TemplateGenerator | src/Generator.Shared/Utilities/StringHelper.cs | 494 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.ECR;
using Amazon.ECR.Model;
namespace Amazon.PowerShell.Cmdlets.ECR
{
/// <summary>
/// List the tags for an Amazon ECR resource.
/// </summary>
[Cmdlet("Get", "ECRResourceTag")]
[OutputType("Amazon.ECR.Model.Tag")]
[AWSCmdlet("Calls the Amazon EC2 Container Registry ListTagsForResource API operation.", Operation = new[] {"ListTagsForResource"}, SelectReturnType = typeof(Amazon.ECR.Model.ListTagsForResourceResponse))]
[AWSCmdletOutput("Amazon.ECR.Model.Tag or Amazon.ECR.Model.ListTagsForResourceResponse",
"This cmdlet returns a collection of Amazon.ECR.Model.Tag objects.",
"The service call response (type Amazon.ECR.Model.ListTagsForResourceResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetECRResourceTagCmdlet : AmazonECRClientCmdlet, IExecutor
{
#region Parameter ResourceArn
/// <summary>
/// <para>
/// <para>The Amazon Resource Name (ARN) that identifies the resource for which to list the
/// tags. Currently, the only supported resource is an Amazon ECR repository.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String ResourceArn { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'Tags'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ECR.Model.ListTagsForResourceResponse).
/// Specifying the name of a property of type Amazon.ECR.Model.ListTagsForResourceResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "Tags";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the ResourceArn parameter.
/// The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ResourceArn' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.ECR.Model.ListTagsForResourceResponse, GetECRResourceTagCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.ResourceArn;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.ResourceArn = this.ResourceArn;
#if MODULAR
if (this.ResourceArn == null && ParameterWasBound(nameof(this.ResourceArn)))
{
WriteWarning("You are passing $null as a value for parameter ResourceArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.ECR.Model.ListTagsForResourceRequest();
if (cmdletContext.ResourceArn != null)
{
request.ResourceArn = cmdletContext.ResourceArn;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.ECR.Model.ListTagsForResourceResponse CallAWSServiceOperation(IAmazonECR client, Amazon.ECR.Model.ListTagsForResourceRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon EC2 Container Registry", "ListTagsForResource");
try
{
#if DESKTOP
return client.ListTagsForResource(request);
#elif CORECLR
return client.ListTagsForResourceAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String ResourceArn { get; set; }
public System.Func<Amazon.ECR.Model.ListTagsForResourceResponse, GetECRResourceTagCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.Tags;
}
}
}
| 44.736318 | 282 | 0.610098 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/ECR/Basic/Get-ECRResourceTag-Cmdlet.cs | 8,992 | C# |
namespace SlackNet
{
[SlackType("group")]
public class StarredGroup : StarredItem
{
public string Group { get; set; }
}
} | 18.25 | 43 | 0.60274 | [
"MIT"
] | Cereal-Killa/SlackNet | SlackNet/Objects/StarredGroup.cs | 148 | C# |
using System;
namespace PhotoChannelWebAPI.Dtos
{
public class CommentForListDto
{
public int UserId { get; set; }
public int CommentId { get; set; }
public string Description { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime ShareDate { get; set; }
}
}
| 24.733333 | 47 | 0.609164 | [
"MIT"
] | AliYildizoz909/PhotoChannel | PhotoChannelWebAPI/Dtos/CommentForListDto.cs | 373 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Gltf.Serialization
{
internal sealed partial class Exporter
{
private static readonly Matrix4x4 InvertZMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, -1));
private static readonly Matrix4x4 InvertZMatrixInverse = InvertZMatrix.inverse;
private struct Skin
{
public Matrix4x4[] BindPoses;
public Transform RootBone;
public Transform[] Bones;
public override bool Equals(object obj)
{
var skin = (Skin)obj;
return
this.BindPoses.SequenceEqual(skin.BindPoses) &&
this.RootBone == skin.RootBone &&
this.Bones.SequenceEqual(skin.Bones);
}
public override int GetHashCode()
{
int hashCode = this.RootBone.GetHashCode();
foreach (var bindPose in this.BindPoses)
{
hashCode ^= bindPose.GetHashCode();
}
foreach (var bone in this.Bones)
{
hashCode ^= bone.GetHashCode();
}
return hashCode;
}
}
private static Matrix4x4 GetRightHandedMatrix(Matrix4x4 matrix)
{
return InvertZMatrixInverse * matrix * InvertZMatrix;
}
private int ExportSkin(SkinnedMeshRenderer skinnedMeshRenderer)
{
var skin = new Skin
{
BindPoses = skinnedMeshRenderer.sharedMesh.bindposes,
RootBone = skinnedMeshRenderer.rootBone,
Bones = skinnedMeshRenderer.bones,
};
int index;
if (this.objectToIndexCache.TryGetValue(skin, out index))
{
return index;
}
if (!this.ApplyExtensions(extension => extension.ExportSkin(skinnedMeshRenderer, out index)))
{
index = this.skins.Count;
this.skins.Add(new Schema.Skin
{
InverseBindMatrices = this.ExportData(skin.BindPoses.Select(bindpose => GetRightHandedMatrix(bindpose))),
Skeleton = this.objectToIndexCache[skin.RootBone.gameObject],
Joints = skin.Bones.Select(bone => this.objectToIndexCache[bone.gameObject]).ToArray(),
});
}
this.ApplyExtensions(extension => extension.PostExportSkin(index, skinnedMeshRenderer));
this.objectToIndexCache.Add(skin, index);
return index;
}
private void ExportSkins(IEnumerable<GameObject> gameObjects)
{
foreach (var gameObject in gameObjects)
{
foreach (var skinnedMeshRenderer in gameObject.GetComponentsInChildren<SkinnedMeshRenderer>())
{
var nodeIndex = this.objectToIndexCache[skinnedMeshRenderer.gameObject];
if (skinnedMeshRenderer.sharedMesh.bindposes != null && skinnedMeshRenderer.sharedMesh.bindposes.Any() &&
skinnedMeshRenderer.rootBone != null ||
skinnedMeshRenderer.bones != null && skinnedMeshRenderer.bones.Any())
{
this.nodes[nodeIndex].Skin = this.ExportSkin(skinnedMeshRenderer);
}
}
}
}
}
}
| 35.979798 | 130 | 0.550253 | [
"MIT"
] | bghgary/glTF-Tools-for-Unity | UnityProject/Assets/Gltf/Editor/Exporter.Skin.cs | 3,564 | C# |
using System;
using System.Threading.Tasks;
using MAVN.Numerics;
namespace MAVN.Service.WalletManagement.Domain.Publishers
{
public interface IEmailNotificationsPublisher
{
Task SendP2PSucceededForSenderAsync(string customerId,
string transactionId,
Money18 amount,
DateTime timestamp,
Money18 currentBalance,
string receiverEmail);
Task SendP2PSucceededForReceiverAsync(string customerId,
string transactionId,
Money18 amount,
DateTime timestamp,
Money18 currentBalance,
string senderEmail);
Task SendP2PFailedForSenderAsync(string customerId,
string transactionId,
Money18 amount,
DateTime timestamp,
Money18 currentBalance,
string receiverEmail);
}
}
| 28.193548 | 64 | 0.643021 | [
"MIT"
] | HannaAndreevna/MAVN.Service.WalletManagement | src/MAVN.Service.WalletManagement.Domain/Publishers/IEmailNotificationsPublisher.cs | 876 | 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 autoscaling-2011-01-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.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the CompleteLifecycleAction operation.
/// Completes the lifecycle action for the specified token or instance with the specified
/// result.
///
///
/// <para>
/// This step is a part of the procedure for adding a lifecycle hook to an Auto Scaling
/// group:
/// </para>
/// <ol> <li>
/// <para>
/// (Optional) Create a Lambda function and a rule that allows CloudWatch Events to invoke
/// your Lambda function when Amazon EC2 Auto Scaling launches or terminates instances.
/// </para>
/// </li> <li>
/// <para>
/// (Optional) Create a notification target and an IAM role. The target can be either
/// an Amazon SQS queue or an Amazon SNS topic. The role allows Amazon EC2 Auto Scaling
/// to publish lifecycle notifications to the target.
/// </para>
/// </li> <li>
/// <para>
/// Create the lifecycle hook. Specify whether the hook is used when the instances launch
/// or terminate.
/// </para>
/// </li> <li>
/// <para>
/// If you need more time, record the lifecycle action heartbeat to keep the instance
/// in a pending state.
/// </para>
/// </li> <li>
/// <para>
/// <b>If you finish before the timeout period ends, complete the lifecycle action.</b>
///
/// </para>
/// </li> </ol>
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html">Amazon
/// EC2 Auto Scaling lifecycle hooks</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public partial class CompleteLifecycleActionRequest : AmazonAutoScalingRequest
{
private string _autoScalingGroupName;
private string _instanceId;
private string _lifecycleActionResult;
private string _lifecycleActionToken;
private string _lifecycleHookName;
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=1600)]
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The ID of the instance.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=19)]
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property LifecycleActionResult.
/// <para>
/// The action for the group to take. This parameter can be either <code>CONTINUE</code>
/// or <code>ABANDON</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string LifecycleActionResult
{
get { return this._lifecycleActionResult; }
set { this._lifecycleActionResult = value; }
}
// Check to see if LifecycleActionResult property is set
internal bool IsSetLifecycleActionResult()
{
return this._lifecycleActionResult != null;
}
/// <summary>
/// Gets and sets the property LifecycleActionToken.
/// <para>
/// A universally unique identifier (UUID) that identifies a specific lifecycle action
/// associated with an instance. Amazon EC2 Auto Scaling sends this token to the notification
/// target you specified when you created the lifecycle hook.
/// </para>
/// </summary>
[AWSProperty(Min=36, Max=36)]
public string LifecycleActionToken
{
get { return this._lifecycleActionToken; }
set { this._lifecycleActionToken = value; }
}
// Check to see if LifecycleActionToken property is set
internal bool IsSetLifecycleActionToken()
{
return this._lifecycleActionToken != null;
}
/// <summary>
/// Gets and sets the property LifecycleHookName.
/// <para>
/// The name of the lifecycle hook.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string LifecycleHookName
{
get { return this._lifecycleHookName; }
set { this._lifecycleHookName = value; }
}
// Check to see if LifecycleHookName property is set
internal bool IsSetLifecycleHookName()
{
return this._lifecycleHookName != null;
}
}
} | 35.077778 | 126 | 0.590117 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AutoScaling/Generated/Model/CompleteLifecycleActionRequest.cs | 6,314 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite
{
public partial class AppInstanceIdExtendedTest : SMB2TestBase
{
#region Test Cases
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.CombinedFeatureNonClusterRequired)]
[TestCategory(TestCategories.Positive)]
[Description("Operate files with encrypted message before and after client failover.")]
public void AppInstanceId_Encryption()
{
AppInstanceIdTestWithEncryption(encryptionInInitialOpen: true, encryptionInReOpen: true);
}
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.CombinedFeatureNonClusterRequired)]
[TestCategory(TestCategories.Compatibility)]
[Description("Operate files with encrypted message before failover but with unencrypted message after failover.")]
public void AppInstanceId_Negative_EncryptionInInitialOpen_NoEncryptionInReOpen()
{
#region Check Applicability
TestConfig.CheckServerEncrypt();
#endregion
AppInstanceIdTestWithEncryption(encryptionInInitialOpen: true, encryptionInReOpen: false);
}
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.CombinedFeatureNonClusterRequired)]
[TestCategory(TestCategories.Compatibility)]
[Description("Operate files with encrypted message before client failover but with unencrypted message after failover.")]
public void AppInstanceId_Negative_NoEncryptionInInitialOpen_EncryptionInReOpen()
{
#region Check Applicability
TestConfig.CheckServerEncrypt();
#endregion
AppInstanceIdTestWithEncryption(encryptionInInitialOpen: false, encryptionInReOpen: true);
}
#endregion
#region Common Methods
/// <summary>
/// Test AppInstanceId with encryption
/// </summary>
/// <param name="encryptionInInitialOpen">Set true if encryption is enabled in initial open, otherwise set false</param>
/// <param name="encryptionInReOpen">Set true if encryption is enabled in re-open, otherwise set false</param>
private void AppInstanceIdTestWithEncryption(bool encryptionInInitialOpen, bool encryptionInReOpen)
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb30);
TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_ENCRYPTION
| NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_LEASING
| NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES);
TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID, CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2, CreateContextTypeValue.SMB2_CREATE_REQUEST_LEASE);
#endregion
uncSharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.EncryptedFileShare);
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "InitialOpen: Connect to share via Nic1.");
FILEID fileIdForInitialOpen;
uint treeIdForInitialOpen;
ConnectShare(TestConfig.SutIPAddress, TestConfig.ClientNic1IPAddress, clientForInitialOpen, out treeIdForInitialOpen, encryptionInInitialOpen);
// Skip the verification of signature when sending a non-encrypted CREATE request to an encrypted share
if (!encryptionInInitialOpen)
{
clientForInitialOpen.Smb2Client.DisableVerifySignature = true;
}
#region CREATE an open with AppInstanceId
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "InitialOpen: CREATE an open with AppInstanceId.");
Smb2CreateContextResponse[] serverCreateContexts;
status = clientForInitialOpen.Create(
treeIdForInitialOpen,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdForInitialOpen,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[] {
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = Guid.NewGuid(),
},
new Smb2CreateAppInstanceId
{
AppInstanceId = appInstanceId
}
},
shareAccess: ShareAccess_Values.NONE,
checker: (header, response) => { });
#endregion
if (!encryptionInInitialOpen)
{
BaseTestSite.Assert.AreNotEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Create durable handle request to encrypted share without encryption should not SUCCESS ");
BaseTestSite.CaptureRequirementIfAreEqual(
Smb2Status.STATUS_ACCESS_DENIED,
status,
RequirementCategory.STATUS_ACCESS_DENIED.Id,
RequirementCategory.STATUS_ACCESS_DENIED.Description);
}
else
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Create durable handle request V2 should succeed, actual status is {0}", Smb2Status.GetStatusCode(status));
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "InitialOpen: Write contents to file.");
status = clientForInitialOpen.Write(treeIdForInitialOpen, fileIdForInitialOpen, contentWrite);
}
FILEID fileIdForReOpen;
uint treeIdForReOpen;
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Connect to same share via Nic2.");
ConnectShare(TestConfig.SutIPAddress, TestConfig.ClientNic2IPAddress, clientForReOpen, out treeIdForReOpen, encryptionInReOpen);
// Skip the verification of signature when sending a non-encrypted CREATE request to an encrypted share
if (!encryptionInReOpen)
{
clientForReOpen.Smb2Client.DisableVerifySignature = true;
}
#region CREATE an open with same AppInstanceId for reopen
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: CREATE an open with same AppInstanceId for reopen.");
status = clientForReOpen.Create(
treeIdForReOpen,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdForReOpen,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[] {
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = Guid.NewGuid(),
},
new Smb2CreateAppInstanceId
{
// Use the same application instance id to force the server close all files
AppInstanceId = appInstanceId
}
},
shareAccess: ShareAccess_Values.NONE,
checker: (header, response) => { });
#endregion
if (encryptionInInitialOpen && encryptionInReOpen)
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Create durable handle request should succeed, actual status is {0}", Smb2Status.GetStatusCode(status));
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Read the contents written by InitialOpen.");
status = clientForReOpen.Read(treeIdForReOpen, fileIdForReOpen, 0, (uint)contentWrite.Length, out contentRead);
BaseTestSite.Assert.IsTrue(
contentRead.Equals(contentWrite),
"The written content should equal to read content.");
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Close file.");
status = clientForReOpen.Close(treeIdForReOpen, fileIdForReOpen);
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Disconnect the share.");
status = clientForReOpen.TreeDisconnect(treeIdForReOpen);
}
else if (encryptionInInitialOpen && !encryptionInReOpen)
{
BaseTestSite.Assert.AreNotEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Create durable handle request to encrypted share without encryption should not SUCCESS ");
BaseTestSite.CaptureRequirementIfAreEqual(
Smb2Status.STATUS_ACCESS_DENIED,
status,
RequirementCategory.STATUS_ACCESS_DENIED.Id,
RequirementCategory.STATUS_ACCESS_DENIED.Description);
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Disconnect the share.");
status = clientForReOpen.TreeDisconnect(treeIdForReOpen, (header, response) => { });
BaseTestSite.Assert.AreNotEqual(
Smb2Status.STATUS_SUCCESS,
status,
"TreeDisconnect should not SUCCESS");
BaseTestSite.CaptureRequirementIfAreEqual(
Smb2Status.STATUS_ACCESS_DENIED,
status,
RequirementCategory.STATUS_ACCESS_DENIED.Id,
RequirementCategory.STATUS_ACCESS_DENIED.Description);
}
else if (!encryptionInInitialOpen && encryptionInReOpen)
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Create durable handle request should succeed, actual status is {0}", Smb2Status.GetStatusCode(status));
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Close file.");
status = clientForReOpen.Close(treeIdForReOpen, fileIdForReOpen);
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Disconnect from the share.");
status = clientForReOpen.TreeDisconnect(treeIdForReOpen);
}
BaseTestSite.Log.Add(TestTools.LogEntryKind.TestStep, "ReOpen: Log off.");
status = clientForReOpen.LogOff();
}
#endregion
}
}
| 49.668142 | 206 | 0.631537 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | TestSuites/FileServer/src/SMB2/TestSuite/AppInstanceId/AppInstanceIdWithEncryption.cs | 11,225 | C# |
using LyncNinja.Services.Interfaces.Data;
namespace LyncNinja.Services.DataService
{
public class DataService : IDataService
{
#region Constructor
public DataService(ILinkedResourceData linkedResourceData)
{
LinkedResource = linkedResourceData;
}
#endregion
#region Properties
/// <summary>
/// Retrieves data functions for the LinkedResource object
/// </summary>
public ILinkedResourceData LinkedResource { get; internal set; }
#endregion
}
}
| 25.454545 | 72 | 0.641071 | [
"MIT"
] | lukecusolito/LyncNinja | LyncNinja.Services.DataService/DataService.cs | 562 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenBudgeteer.Core.Common.Database;
#nullable disable
namespace OpenBudgeteer.Core.Migrations.Sqlite
{
[DbContext(typeof(SqliteDatabaseContext))]
[Migration("20220213195523_ImportCreditColumn")]
partial class ImportCreditColumn
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "6.0.0");
modelBuilder.Entity("OpenBudgeteer.Core.Models.Account", b =>
{
b.Property<int>("AccountId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("IsActive")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.HasKey("AccountId");
b.ToTable("Account");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BankTransaction", b =>
{
b.Property<int>("TransactionId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccountId")
.HasColumnType("INTEGER");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65, 2)");
b.Property<string>("Memo")
.HasColumnType("TEXT");
b.Property<string>("Payee")
.HasColumnType("TEXT");
b.Property<DateTime>("TransactionDate")
.HasColumnType("TEXT");
b.HasKey("TransactionId");
b.ToTable("BankTransaction");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.Bucket", b =>
{
b.Property<int>("BucketId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("BucketGroupId")
.HasColumnType("INTEGER");
b.Property<string>("ColorCode")
.HasColumnType("TEXT");
b.Property<bool>("IsInactive")
.HasColumnType("INTEGER");
b.Property<DateTime>("IsInactiveFrom")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<DateTime>("ValidFrom")
.HasColumnType("TEXT");
b.HasKey("BucketId");
b.ToTable("Bucket");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BucketGroup", b =>
{
b.Property<int>("BucketGroupId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("Position")
.HasColumnType("INTEGER");
b.HasKey("BucketGroupId");
b.ToTable("BucketGroup");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BucketMovement", b =>
{
b.Property<int>("BucketMovementId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65, 2)");
b.Property<int>("BucketId")
.HasColumnType("INTEGER");
b.Property<DateTime>("MovementDate")
.HasColumnType("TEXT");
b.HasKey("BucketMovementId");
b.ToTable("BucketMovement");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BucketRuleSet", b =>
{
b.Property<int>("BucketRuleSetId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<int>("TargetBucketId")
.HasColumnType("INTEGER");
b.HasKey("BucketRuleSetId");
b.ToTable("BucketRuleSet");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BucketVersion", b =>
{
b.Property<int>("BucketVersionId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("BucketId")
.HasColumnType("INTEGER");
b.Property<int>("BucketType")
.HasColumnType("INTEGER");
b.Property<int>("BucketTypeXParam")
.HasColumnType("INTEGER");
b.Property<decimal>("BucketTypeYParam")
.HasColumnType("decimal(65, 2)");
b.Property<DateTime>("BucketTypeZParam")
.HasColumnType("TEXT");
b.Property<string>("Notes")
.HasColumnType("TEXT");
b.Property<DateTime>("ValidFrom")
.HasColumnType("TEXT");
b.Property<int>("Version")
.HasColumnType("INTEGER");
b.HasKey("BucketVersionId");
b.ToTable("BucketVersion");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.BudgetedTransaction", b =>
{
b.Property<int>("BudgetedTransactionId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65, 2)");
b.Property<int>("BucketId")
.HasColumnType("INTEGER");
b.Property<int>("TransactionId")
.HasColumnType("INTEGER");
b.HasKey("BudgetedTransactionId");
b.ToTable("BudgetedTransaction");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.ImportProfile", b =>
{
b.Property<int>("ImportProfileId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccountId")
.HasColumnType("INTEGER");
b.Property<string>("AmountColumnName")
.HasColumnType("TEXT");
b.Property<string>("CreditColumnName")
.HasColumnType("TEXT");
b.Property<string>("DateFormat")
.HasColumnType("TEXT");
b.Property<char>("Delimiter")
.HasColumnType("TEXT");
b.Property<int>("HeaderRow")
.HasColumnType("INTEGER");
b.Property<string>("MemoColumnName")
.HasColumnType("TEXT");
b.Property<string>("NumberFormat")
.HasColumnType("TEXT");
b.Property<string>("PayeeColumnName")
.HasColumnType("TEXT");
b.Property<string>("ProfileName")
.HasColumnType("TEXT");
b.Property<char>("TextQualifier")
.HasColumnType("TEXT");
b.Property<string>("TransactionDateColumnName")
.HasColumnType("TEXT");
b.HasKey("ImportProfileId");
b.ToTable("ImportProfile");
});
modelBuilder.Entity("OpenBudgeteer.Core.Models.MappingRule", b =>
{
b.Property<int>("MappingRuleId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("BucketRuleSetId")
.HasColumnType("INTEGER");
b.Property<int>("ComparisionField")
.HasColumnType("INTEGER");
b.Property<int>("ComparisionType")
.HasColumnType("INTEGER");
b.Property<string>("ComparisionValue")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("MappingRuleId");
b.ToTable("MappingRule");
});
#pragma warning restore 612, 618
}
}
}
| 33.614286 | 85 | 0.451551 | [
"Apache-2.0",
"MIT"
] | Hazy87/OpenBudgeteer | OpenBudgeteer.Core/Migrations/Sqlite/20220213195523_ImportCreditColumn.Designer.cs | 9,414 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MobiFlight
{
class UsageDetails
{
protected static bool enabled = false;
public static bool Enabled()
{
return enabled;
}
public static void Enabled(bool state)
{
enabled = state;
}
public static int Started()
{
return Properties.Settings.Default.Started;
}
public static string UrlString()
{
if (!enabled) return "";
return "?"
+ "started=" + Started() + "&"
+ "size=";
}
}
}
| 18.648649 | 55 | 0.497101 | [
"Unlicense"
] | CaptainBobSim/Connector-Open-Source-Control-Loading-system | Base/UsageDetails.cs | 692 | C# |
namespace Netflix_Helper
{
partial class Form1
{
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
/// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form 디자이너에서 생성한 코드
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Bodoni MT Poster Compressed", 60F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(369, 87);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(451, 138);
this.label1.TabIndex = 0;
this.label1.Text = "Netflix Helper";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("굴림", 20F);
this.textBox1.Location = new System.Drawing.Point(171, 245);
this.textBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(740, 53);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// comboBox1
//
this.comboBox1.Font = new System.Drawing.Font("굴림", 20F);
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(171, 311);
this.comboBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(840, 48);
this.comboBox1.TabIndex = 3;
this.comboBox1.Text = "장르 검색(SF, ...)";
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(918, 245);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(93, 53);
this.button1.TabIndex = 4;
this.button1.Text = "검색";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(1049, 12);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(69, 52);
this.button2.TabIndex = 5;
this.button2.Text = "불러오기";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(171, 386);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(840, 518);
this.richTextBox1.TabIndex = 6;
this.richTextBox1.Text = "";
this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);
//
// richTextBox2
//
this.richTextBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.richTextBox2.Font = new System.Drawing.Font("굴림", 10F);
this.richTextBox2.Location = new System.Drawing.Point(12, 12);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(1031, 52);
this.richTextBox2.TabIndex = 7;
this.richTextBox2.Text = "";
this.richTextBox2.TextChanged += new System.EventHandler(this.richTextBox2_TextChanged);
//
// button3
//
this.button3.Location = new System.Drawing.Point(1124, 13);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(95, 51);
this.button3.TabIndex = 8;
this.button3.Text = "읽기";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.LightSlateGray;
this.ClientSize = new System.Drawing.Size(1231, 916);
this.Controls.Add(this.button3);
this.Controls.Add(this.richTextBox2);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Netflix_Helper";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.RichTextBox richTextBox2;
private System.Windows.Forms.Button button3;
}
}
| 45.398773 | 174 | 0.569324 | [
"MIT"
] | rlawlghkd12/Netplex_Helper | develop/Netflix_Helper/Form1.Designer.cs | 7,636 | C# |
using CommonMark.Formatters;
using CommonMark.Parser;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
namespace CommonMark
{
/// <summary>
/// Contains methods for parsing and formatting CommonMark data.
/// </summary>
public static class CommonMarkConverter
{
private static Lazy<Assembly> _assembly = new Lazy<Assembly>(InitializeAssembly, LazyThreadSafetyMode.None);
private static Assembly Assembly
{
get { return _assembly.Value; }
}
private static Assembly InitializeAssembly()
{
#if portable_259 || NETSTANDARD1_0
return typeof(CommonMarkConverter).GetTypeInfo().Assembly;
#else
return typeof(CommonMarkConverter).Assembly;
#endif
}
private static Lazy<Version> _version = new Lazy<Version>(InitializeVersion, LazyThreadSafetyMode.None);
/// <summary>
/// Gets the CommonMark package version number.
/// Note that this might differ from the actual assembly version which is updated less often to
/// reduce problems when upgrading the nuget package.
/// </summary>
public static Version Version
{
get
{
return _version.Value;
}
}
private static Version InitializeVersion()
{
// System.Xml is not available so resort to string parsing.
using (var stream = Assembly.GetManifestResourceStream("CommonMark.Properties.CommonMark.NET.nuspec"))
using (var reader = new System.IO.StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
var i = line.IndexOf("<version>", StringComparison.Ordinal);
if (i == -1)
continue;
i += 9;
return new Version(line.Substring(i, line.IndexOf("</version>", StringComparison.Ordinal) - i));
}
}
return null;
}
/// <summary>
/// Gets the CommonMark assembly version number. Note that might differ from the actual release version
/// since the assembly version is not always incremented to reduce possible reference errors when updating.
/// </summary>
[Obsolete("Use Version property instead.", false)]
[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Version AssemblyVersion
{
get
{
return new AssemblyName(Assembly.FullName).Version;
}
}
/// <summary>
/// Performs the first stage of the conversion - parses block elements from the source and created the syntax tree.
/// </summary>
/// <param name="source">The reader that contains the source data.</param>
/// <param name="settings">The object containing settings for the parsing process.</param>
/// <returns>The block element that represents the document.</returns>
/// <exception cref="ArgumentNullException">when <paramref name="source"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during block parsing.</exception>
/// <exception cref="IOException">when error occur while reading the data.</exception>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public static Syntax.Block ProcessStage1(TextReader source, CommonMarkSettings settings = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (settings == null)
settings = CommonMarkSettings.Default;
var cur = Syntax.Block.CreateDocument();
var doc = cur;
var line = new LineInfo(settings.TrackSourcePosition, settings);
try
{
var reader = new TabTextReader(source);
reader.ReadLine(line);
while (line.Line != null)
{
BlockMethods.IncorporateLine(line, ref cur);
reader.ReadLine(line);
}
}
catch(IOException)
{
throw;
}
catch(CommonMarkException)
{
throw;
}
catch(Exception ex)
{
throw new CommonMarkException("An error occurred while parsing line " + line.ToString(), cur, ex);
}
try
{
do
{
BlockMethods.Finalize(cur, line);
cur = cur.Parent;
} while (cur != null);
}
catch (CommonMarkException)
{
throw;
}
catch (Exception ex)
{
throw new CommonMarkException("An error occurred while finalizing open containers.", cur, ex);
}
return doc;
}
/// <summary>
/// Performs the second stage of the conversion - parses block element contents into inline elements.
/// </summary>
/// <param name="document">The top level document element.</param>
/// <param name="settings">The object containing settings for the parsing process.</param>
/// <exception cref="ArgumentException">when <paramref name="document"/> does not represent a top level document.</exception>
/// <exception cref="ArgumentNullException">when <paramref name="document"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during inline parsing.</exception>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void ProcessStage2(Syntax.Block document, CommonMarkSettings settings = null)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
if (document.Tag != Syntax.BlockTag.Document)
throw new ArgumentException("The block element passed to this method must represent a top level document.", nameof(document));
if (settings == null)
settings = CommonMarkSettings.Default;
try
{
BlockMethods.ProcessInlines(document, document.Document, settings);
}
catch(CommonMarkException)
{
throw;
}
catch(Exception ex)
{
throw new CommonMarkException("An error occurred during inline parsing.", ex);
}
}
/// <summary>
/// Performs the last stage of the conversion - converts the syntax tree to HTML representation.
/// </summary>
/// <param name="document">The top level document element.</param>
/// <param name="target">The target text writer where the result will be written to.</param>
/// <param name="settings">The object containing settings for the formatting process.</param>
/// <exception cref="ArgumentException">when <paramref name="document"/> does not represent a top level document.</exception>
/// <exception cref="ArgumentNullException">when <paramref name="document"/> or <paramref name="target"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during formatting.</exception>
/// <exception cref="IOException">when error occur while writing the data to the target.</exception>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void ProcessStage3(Syntax.Block document, TextWriter target, CommonMarkSettings settings = null)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (document.Tag != Syntax.BlockTag.Document)
throw new ArgumentException("The block element passed to this method must represent a top level document.", nameof(document));
if (settings == null)
settings = CommonMarkSettings.Default;
try
{
switch (settings.OutputFormat)
{
case OutputFormat.Html:
HtmlFormatterSlim.BlocksToHtml(target, document, settings);
break;
case OutputFormat.SyntaxTree:
Printer.PrintBlocks(target, document, settings);
break;
case OutputFormat.CustomDelegate:
if (settings.OutputDelegate == null)
throw new CommonMarkException("If `settings.OutputFormat` is set to `CustomDelegate`, the `settings.OutputDelegate` property must be populated.");
settings.OutputDelegate(document, target, settings);
break;
default:
throw new CommonMarkException("Unsupported value '" + settings.OutputFormat + "' in `settings.OutputFormat`.");
}
}
catch (CommonMarkException)
{
throw;
}
catch(IOException)
{
throw;
}
catch(Exception ex)
{
throw new CommonMarkException("An error occurred during formatting of the document.", ex);
}
}
/// <summary>
/// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
/// convert the document to HTML using the built-in converter.
/// </summary>
/// <param name="source">The reader that contains the source data.</param>
/// <param name="settings">The object containing settings for the parsing and formatting process.</param>
/// <exception cref="ArgumentNullException">when <paramref name="source"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
/// <exception cref="IOException">when error occur while reading or writing the data.</exception>
public static Syntax.Block Parse(TextReader source, CommonMarkSettings settings = null)
{
if (settings == null)
settings = CommonMarkSettings.Default;
var document = ProcessStage1(source, settings);
ProcessStage2(document, settings);
return document;
}
/// <summary>
/// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
/// convert the document to HTML using the built-in converter.
/// </summary>
/// <param name="source">The source data.</param>
/// <param name="settings">The object containing settings for the parsing and formatting process.</param>
/// <exception cref="ArgumentNullException">when <paramref name="source"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
/// <exception cref="IOException">when error occur while reading or writing the data.</exception>
public static Syntax.Block Parse(string source, CommonMarkSettings settings = null)
{
if (source == null)
return null;
using (var reader = new System.IO.StringReader(source))
return Parse(reader, settings);
}
/// <summary>
/// Converts the given source data and writes the result directly to the target.
/// </summary>
/// <param name="source">The reader that contains the source data.</param>
/// <param name="target">The target text writer where the result will be written to.</param>
/// <param name="settings">The object containing settings for the parsing and formatting process.</param>
/// <exception cref="ArgumentNullException">when <paramref name="source"/> or <paramref name="target"/> is <see langword="null"/></exception>
/// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
/// <exception cref="IOException">when error occur while reading or writing the data.</exception>
public static void Convert(TextReader source, TextWriter target, CommonMarkSettings settings = null)
{
if (settings == null)
settings = CommonMarkSettings.Default;
var document = ProcessStage1(source, settings);
ProcessStage2(document, settings);
ProcessStage3(document, target, settings);
}
/// <summary>
/// Converts the given source data and returns the result as a string.
/// </summary>
/// <param name="source">The source data.</param>
/// <param name="settings">The object containing settings for the parsing and formatting process.</param>
/// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
/// <returns>The converted data.</returns>
public static string Convert(string source, CommonMarkSettings settings = null)
{
if (source == null)
return null;
using (var reader = new System.IO.StringReader(source))
using (var writer = new System.IO.StringWriter(System.Globalization.CultureInfo.CurrentCulture))
{
Convert(reader, writer, settings);
return writer.ToString();
}
}
}
}
| 44.943218 | 174 | 0.595283 | [
"BSD-3-Clause"
] | eway-crm/CommonMark.NET | CommonMark/CommonMarkConverter.cs | 14,249 | C# |
namespace LinkStash.Core
{
using System;
using Newtonsoft.Json;
/// <summary>
/// This base class provides comparison based on the Id and the usual
/// reference equality.
/// </summary>
public abstract class Entity
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public string Type
{
get
{
return this.GetType().Name;
}
}
public DateTime Timestamp { get; set; }
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">a.</param>
/// <param name="b">The b.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(Entity a, Entity b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
{
return true;
}
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a.Equals(b);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">a.</param>
/// <param name="b">The b.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(Entity a, Entity b)
{
return !(a == b);
}
/// <summary>
/// Determines whether the specified <see cref="object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as Entity;
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
if (this.Id.IsNullOrEmpty() || other.Id.IsNullOrEmpty())
{
return false;
}
return this.Id == other.Id;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return $"{this.GetType()} {this.Id}".GetHashCode();
}
public override string ToString()
{
return $"{ this.GetType().Name} [Id={this.Id}]";
}
}
} | 27.171171 | 120 | 0.467175 | [
"MIT"
] | vip32/LinkStash | src/LinkStash.Core/Entities/Entity.cs | 3,018 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Peachpie Syntax")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Peachpie Syntax")]
[assembly: AssemblyCopyright("Copyright © Peachpie 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 35.258065 | 84 | 0.745654 | [
"Apache-2.0"
] | dnelly/peachpie | src/Compiler/PhpSyntax/Properties/AssemblyInfo.cs | 1,096 | C# |
using System;
namespace RestfulFirebase.Utilities
{
/// <summary>
/// Provides <see cref="TimeSpan"/> extensions.
/// </summary>
public static class TimeSpanExtensions
{
private const int Second = 1;
private const int Minute = 60 * Second;
private const int Hour = 60 * Minute;
private const int Day = 24 * Hour;
private const int Week = 7 * Day;
private const int Month = 30 * Day;
private const int Year = 12 * Month;
/// <summary>
/// Gets nicely formatted time span such as "just now", "a minute" etc.
/// </summary>
/// <param name="timeSpan">
/// </param>
/// <returns>
/// The nicely formatted time span representation of the provided <paramref name="timeSpan"/> parameter.
/// </returns>
public static string GetNiceFormattedTimeSpan(this TimeSpan timeSpan)
{
double delta = Math.Abs(timeSpan.TotalSeconds);
if (delta < 1 * Minute)
return "just now";
if (delta < 2 * Minute)
return "a minute";
if (delta < 60 * Minute)
return timeSpan.Minutes + " minutes";
if (delta < 2 * Hour)
return "an hour";
if (delta < 24 * Hour)
return timeSpan.Hours + " hours";
if (delta < 48 * Hour)
return "yesterday";
if (delta < 30 * Day)
return timeSpan.Days + " days";
if (delta < 12 * Month)
{
int months = Convert.ToInt32(Math.Floor((double)timeSpan.Days / 30));
return months <= 1 ? "a month" : months + " months";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)timeSpan.Days / 365));
return years <= 1 ? "a year" : years + " years";
}
}
}
}
| 30.859375 | 112 | 0.498228 | [
"Apache-2.0"
] | Kiryuumaru/RestfulFirebase | RestfulFirebase/Utilities/TimeSpanExtensions.cs | 1,977 | C# |
using System.IO;
using OrchardCore.Environment.Commands;
namespace OrchardCore.Hosting.HostContext
{
public class CommandHostContext
{
public CommandReturnCodes StartSessionResult { get; set; }
public CommandReturnCodes RetryResult { get; set; }
public OrchardParameters Arguments { get; set; }
public DirectoryInfo OrchardDirectory { get; set; }
public bool DisplayUsageHelp { get; set; }
public CommandHostAgent CommandHost { get; internal set; }
}
}
| 30.294118 | 66 | 0.702913 | [
"BSD-3-Clause"
] | Craige/OrchardCore | src/OrchardCore/OrchardCore.Hosting.Console/HostContext/CommandHostContext.cs | 515 | C# |
using Autofac;
using Collatz.Api.Logging;
namespace Collatz.Api
{
public sealed class ApiModule
: Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<SerilogLogging>().As<ILogger>().SingleInstance();
}
}
}
| 17.5 | 73 | 0.728571 | [
"MIT"
] | rockfordlhotka/xplat-netcore-webassembly | src/jbock/Collatz.Api/ApiModule.cs | 282 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if NETFX_CORE
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Web.Http;
#else
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http.Internal;
using System.Runtime.Serialization;
using System.Text;
using System.Web.Http;
#endif
#if NETFX_CORE
namespace System.Net.Http.Formatting
#else
namespace System.Net.Http.Formatting.Internal
#endif
{
/// <summary>
/// NameValueCollection to represent form data and to generate form data output.
/// </summary>
#if NETFX_CORE
public class HttpValueCollection : IEnumerable<KeyValuePair<string, string>>
#else
[Serializable]
internal class HttpValueCollection : NameValueCollection
#endif
{
#if NETFX_CORE
internal readonly HashSet<string> Names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
internal readonly List<KeyValuePair<string, string>> List = new List<KeyValuePair<string, string>>();
/// <summary>
/// Creates a new <see cref="System.Net.Http.Formatting.HttpValueCollection"/> instance
/// </summary>
public HttpValueCollection()
{
}
#else
protected HttpValueCollection(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
private HttpValueCollection()
: base(StringComparer.OrdinalIgnoreCase) // case-insensitive keys
{
}
#endif
// Use a builder function instead of a ctor to avoid virtual calls from the ctor.
// The above condition is only important in the Full .NET fx implementation.
internal static HttpValueCollection Create()
{
return new HttpValueCollection();
}
internal static HttpValueCollection Create(IEnumerable<KeyValuePair<string, string>> pairs)
{
Contract.Assert(pairs != null);
var hvc = new HttpValueCollection();
// Ordering example:
// k=A&j=B&k=C --> k:[A,C];j=[B].
foreach (KeyValuePair<string, string> kvp in pairs)
{
hvc.Add(kvp.Key, kvp.Value);
}
#if !NETFX_CORE
hvc.IsReadOnly = false;
#endif
return hvc;
}
/// <summary>
/// Adds a name-value pair to the collection.
/// </summary>
/// <param name="name">The name to be added as a case insensitive string.</param>
/// <param name="value">The value to be added.</param>
public
#if !NETFX_CORE
override
#endif
void Add(string name, string value)
{
ThrowIfMaxHttpCollectionKeysExceeded(Count);
name = name ?? String.Empty;
value = value ?? String.Empty;
#if NETFX_CORE
Names.Add(name);
List.Add(new KeyValuePair<string, string>(name, value));
#else
base.Add(name, value);
#endif
}
/// <summary>
/// Converts the content of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, multiple values with a single key are comma separated.</returns>
public override string ToString()
{
return ToString(true);
}
private static void ThrowIfMaxHttpCollectionKeysExceeded(int count)
{
if (count >= MediaTypeFormatter.MaxHttpCollectionKeys)
{
throw Error.InvalidOperation(System.Net.Http.Properties.Resources.MaxHttpCollectionKeyLimitReached, MediaTypeFormatter.MaxHttpCollectionKeys, typeof(MediaTypeFormatter));
}
}
private string ToString(bool urlEncode)
{
if (Count == 0)
{
return String.Empty;
}
StringBuilder builder = new StringBuilder();
bool first = true;
#if NETFX_CORE
foreach (string name in Names)
#else
foreach (string name in this)
#endif
{
string[] values = GetValues(name);
if (values == null || values.Length == 0)
{
first = AppendNameValuePair(builder, first, urlEncode, name, String.Empty);
}
else
{
foreach (string value in values)
{
first = AppendNameValuePair(builder, first, urlEncode, name, value);
}
}
}
return builder.ToString();
}
private static bool AppendNameValuePair(StringBuilder builder, bool first, bool urlEncode, string name, string value)
{
string effectiveName = name ?? String.Empty;
string encodedName = urlEncode ? UriQueryUtility.UrlEncode(effectiveName) : effectiveName;
string effectiveValue = value ?? String.Empty;
string encodedValue = urlEncode ? UriQueryUtility.UrlEncode(effectiveValue) : effectiveValue;
if (first)
{
first = false;
}
else
{
builder.Append("&");
}
builder.Append(encodedName);
if (!String.IsNullOrEmpty(encodedValue))
{
builder.Append("=");
builder.Append(encodedValue);
}
return first;
}
#if NETFX_CORE
/// <summary>
/// Gets the values associated with the specified name
/// combined into one comma-separated list.
/// </summary>
/// <param name="name">The name of the entry that contains the values to get. The name can be null.</param>
/// <returns>A <see cref="System.String"/> that contains a comma-separated list of url encoded values associated
/// with the specified name if found; otherwise, null. The values are Url encoded.</returns>
public string this[string name]
{
get
{
return Get(name);
}
}
/// <summary>
/// Gets the number of names in the collection.
/// </summary>
public int Count
{
get
{
return Names.Count;
}
}
/// <summary>
/// Gets the values associated with the specified name
/// combined into one comma-separated list.
/// </summary>
/// <param name="name">The name of the entry that contains the values to get. The name can be null.</param>
/// <returns>
/// A <see cref="System.String"/> that contains a comma-separated list of url encoded values associated
/// with the specified name if found; otherwise, null. The values are Url encoded.
/// </returns>
public string Get(string name)
{
name = name ?? String.Empty;
if (!Names.Contains(name))
{
return null;
}
List<string> values = GetValuesInternal(name);
Contract.Assert(values != null && values.Count > 0);
return String.Join(",", values);
}
/// <summary>
/// Gets the values associated with the specified name.
/// </summary>
/// <param name="name">The <see cref="System.String"/></param>
/// <returns>A <see cref="System.String"/> that contains url encoded values associated with the name, or null if the name does not exist.</returns>
public string[] GetValues(string name)
{
name = name ?? String.Empty;
if (!Names.Contains(name))
{
return null;
}
return GetValuesInternal(name).ToArray();
}
// call this when only when there are values available.
private List<string> GetValuesInternal(string name)
{
List<string> values = new List<string>();
for (int i = 0; i < List.Count; i++)
{
KeyValuePair<string, string> kvp = List[i];
if (String.Equals(kvp.Key, name, StringComparison.OrdinalIgnoreCase))
{
values.Add(kvp.Value);
}
}
return values;
}
/// <inheritdoc />
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return List.GetEnumerator();
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
#endif
}
}
| 31.755319 | 186 | 0.567616 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs | 8,957 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Runtime.CompilerServices;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osuTK;
namespace osu.Framework.Utils
{
public readonly ref struct ConvexPolygonClipper<TClip, TSubject>
where TClip : IConvexPolygon
where TSubject : IConvexPolygon
{
private readonly TClip clipPolygon;
private readonly TSubject subjectPolygon;
public ConvexPolygonClipper(ref TClip clipPolygon, ref TSubject subjectPolygon)
{
this.clipPolygon = clipPolygon;
this.subjectPolygon = subjectPolygon;
}
/// <summary>
/// Determines the minimum buffer size required to clip the two polygons.
/// </summary>
/// <returns>The minimum buffer size required for <see cref="clipPolygon"/> to clip <see cref="subjectPolygon"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetClipBufferSize()
{
// There can only be at most two intersections for each of the subject's vertices
return subjectPolygon.GetVertices().Length * 2;
}
/// <summary>
/// Clips <see cref="subjectPolygon"/> by <see cref="clipPolygon"/>.
/// </summary>
/// <returns>A clockwise-ordered set of vertices representing the result of clipping <see cref="subjectPolygon"/> by <see cref="clipPolygon"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<Vector2> Clip() => Clip(new Vector2[GetClipBufferSize()]);
/// <summary>
/// Clips <see cref="subjectPolygon"/> by <see cref="clipPolygon"/> using an intermediate buffer.
/// </summary>
/// <param name="buffer">The buffer to contain the clipped vertices. Must have a length of <see cref="GetClipBufferSize"/>.</param>
/// <returns>A clockwise-ordered set of vertices representing the result of clipping <see cref="subjectPolygon"/> by <see cref="clipPolygon"/>.</returns>
public Span<Vector2> Clip(in Span<Vector2> buffer)
{
if (buffer.Length < GetClipBufferSize())
{
throw new ArgumentException($"Clip buffer must have a length of {GetClipBufferSize()}, but was {buffer.Length}."
+ "Use GetClipBufferSize() to calculate the size of the buffer.", nameof(buffer));
}
ReadOnlySpan<Vector2> origSubjectVertices = subjectPolygon.GetVertices();
if (origSubjectVertices.Length == 0)
return Span<Vector2>.Empty;
ReadOnlySpan<Vector2> origClipVertices = clipPolygon.GetVertices();
if (origClipVertices.Length == 0)
return Span<Vector2>.Empty;
// Add the subject vertices to the buffer and immediately normalise them
Span<Vector2> subjectVertices = getNormalised(origSubjectVertices, buffer.Slice(0, origSubjectVertices.Length), true);
// Since the clip vertices aren't modified, we can use them as they are if they are normalised
// However if they are not normalised, then we must add them to the buffer and normalise them there
bool clipNormalised = Vector2Extensions.GetOrientation(origClipVertices) >= 0;
Span<Vector2> clipBuffer = clipNormalised ? null : stackalloc Vector2[origClipVertices.Length];
ReadOnlySpan<Vector2> clipVertices = clipNormalised
? origClipVertices
: getNormalised(origClipVertices, clipBuffer, false);
// Number of vertices in the buffer that need to be tested against
// This becomes the number of vertices in the resulting polygon after each clipping iteration
int inputCount = subjectVertices.Length;
int validClipEdges = 0;
// Process the clip edge connecting the last vertex to the first vertex
inputCount = processClipEdge(new Line(clipVertices[^1], clipVertices[0]), buffer, inputCount, ref validClipEdges);
// Process all other edges
for (int c = 1; c < clipVertices.Length; c++)
{
if (inputCount == 0)
break;
inputCount = processClipEdge(new Line(clipVertices[c - 1], clipVertices[c]), buffer, inputCount, ref validClipEdges);
}
if (validClipEdges < 3)
return Span<Vector2>.Empty;
return buffer.Slice(0, inputCount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int processClipEdge(in Line clipEdge, in Span<Vector2> buffer, in int inputCount, ref int validClipEdges)
{
if (clipEdge.EndPoint == clipEdge.StartPoint)
return inputCount;
validClipEdges++;
// Temporary storage for the vertices from the buffer as the buffer gets altered
Span<Vector2> inputVertices = stackalloc Vector2[buffer.Length];
// Store the original vertices (buffer will get altered)
buffer.CopyTo(inputVertices);
int outputCount = 0;
// Process the edge connecting the last vertex with the first vertex
outputVertices(ref inputVertices[inputCount - 1], ref inputVertices[0], clipEdge, buffer, ref outputCount);
// Process all other vertices
for (int i = 1; i < inputCount; i++)
outputVertices(ref inputVertices[i - 1], ref inputVertices[i], clipEdge, buffer, ref outputCount);
return outputCount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void outputVertices(ref Vector2 startVertex, ref Vector2 endVertex, in Line clipEdge, in Span<Vector2> buffer, ref int bufferIndex)
{
if (endVertex.InRightHalfPlaneOf(clipEdge))
{
if (!startVertex.InRightHalfPlaneOf(clipEdge))
{
clipEdge.TryIntersectWith(ref startVertex, ref endVertex, out float t);
buffer[bufferIndex++] = clipEdge.At(t);
}
buffer[bufferIndex++] = endVertex;
}
else if (startVertex.InRightHalfPlaneOf(clipEdge))
{
clipEdge.TryIntersectWith(ref startVertex, ref endVertex, out float t);
buffer[bufferIndex++] = clipEdge.At(t);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Span<Vector2> getNormalised(in ReadOnlySpan<Vector2> original, in Span<Vector2> bufferSlice, bool verify)
{
original.CopyTo(bufferSlice);
if (!verify || Vector2Extensions.GetOrientation(original) < 0)
bufferSlice.Reverse();
return bufferSlice;
}
}
}
| 46.038462 | 162 | 0.615288 | [
"MIT"
] | Flutterish/osu-framework | osu.Framework/Utils/ConvexPolygonClipper.cs | 7,027 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DotMercy.custom {
public partial class GenerateJobCard {
/// <summary>
/// grid control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::DevExpress.Web.ASPxGridView grid;
/// <summary>
/// SqlDataSource1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource SqlDataSource1;
/// <summary>
/// sdsPackingMonth control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource sdsPackingMonth;
/// <summary>
/// sdsModel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource sdsModel;
/// <summary>
/// sdsModelGroup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource sdsModelGroup;
/// <summary>
/// sdsVarian control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource sdsVarian;
}
}
| 34.428571 | 84 | 0.53112 | [
"Apache-2.0"
] | dotindo/9deddde2 | DotMercy/DotMercy/custom/GenerateJobCard.aspx.designer.cs | 2,410 | C# |
using System;
using System.Linq;
using Abp.Dapper.Repositories;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Events.Bus.Entities;
using Shouldly;
using Xunit;
namespace Abp.Dapper.NHibernate.Tests
{
public class DapperNhBasedRepository_Tests : DapperNhBasedApplicationTestBase
{
private readonly IDapperRepository<Person> _personDapperRepository;
private readonly IRepository<Person> _personRepository;
public DapperNhBasedRepository_Tests()
{
_personRepository = Resolve<IRepository<Person>>();
_personDapperRepository = Resolve<IDapperRepository<Person>>();
UsingSession(session => session.Save(new Person("Oguzhan_Initial")));
}
[Fact]
public void Should_Get_All_People()
{
_personRepository.Insert(new Person("Oguzhan"));
_personDapperRepository.GetAll().Count().ShouldBe(2);
}
[Fact]
public void Should_Insert_People()
{
_personRepository.Insert(new Person("Oguzhan2"));
Person insertedPerson = UsingSession(session => session.Query<Person>().FirstOrDefault(p => p.Name == "Oguzhan2"));
insertedPerson.ShouldNotBe(null);
insertedPerson.IsTransient().ShouldBe(false);
insertedPerson.Name.ShouldBe("Oguzhan2");
Person insertedPersonFromDapper = _personDapperRepository.FirstOrDefault(x => x.Name == "Oguzhan2");
insertedPersonFromDapper.ShouldNotBe(null);
insertedPersonFromDapper.IsTransient().ShouldBe(false);
insertedPersonFromDapper.Name.ShouldBe("Oguzhan2");
}
[Fact]
public void Update_With_Action_Test()
{
Person userBefore = UsingSession(session => session.Query<Person>().Single(p => p.Name == "Oguzhan_Initial"));
Person updatedUser = _personRepository.Update(userBefore.Id, user => user.Name = "Oguzhan_Updated_With_NH");
updatedUser.Id.ShouldBe(userBefore.Id);
updatedUser.Name.ShouldBe("Oguzhan_Updated_With_NH");
Person userAfter = UsingSession(session => session.Get<Person>(userBefore.Id));
userAfter.Name.ShouldBe("Oguzhan_Updated_With_NH");
Person updatedWithNh = _personDapperRepository.FirstOrDefault(x => x.Name == "Oguzhan_Updated_With_NH");
updatedWithNh.Name = "Oguzhan_Updated_With_Dapper";
_personDapperRepository.Update(updatedWithNh);
Person updatedWithDapper = _personDapperRepository.Get(updatedWithNh.Id);
updatedWithDapper.Name.ShouldBe("Oguzhan_Updated_With_Dapper");
}
[Fact]
public void Should_Trigger_Event_On_Insert()
{
var triggerCount = 0;
Resolve<IEventBus>().Register<EntityCreatedEventData<Person>>(
eventData =>
{
eventData.Entity.Name.ShouldBe("Oguzhan_To_Fire_Event");
eventData.Entity.IsTransient().ShouldBe(false);
triggerCount++;
});
_personDapperRepository.Insert(new Person("Oguzhan_To_Fire_Event"));
triggerCount.ShouldBe(1);
}
[Fact]
public void Should_Trigger_Event_On_Update()
{
var triggerCount = 0;
Resolve<IEventBus>().Register<EntityUpdatedEventData<Person>>(
eventData =>
{
eventData.Entity.Name.ShouldBe("Oguzhan_Updated_Event_Fire");
triggerCount++;
});
Person person = _personDapperRepository.Single(p => p.Name == "Oguzhan_Initial");
person.Name = "Oguzhan_Updated_Event_Fire";
_personDapperRepository.Update(person);
triggerCount.ShouldBe(1);
}
[Fact]
public void Should_Trigger_Event_On_Delete()
{
var triggerCount = 0;
Resolve<IEventBus>().Register<EntityDeletedEventData<Person>>(
eventData =>
{
eventData.Entity.Name.ShouldBe("Oguzhan_Initial");
triggerCount++;
});
Person person = _personDapperRepository.Single(p => p.Name == "Oguzhan_Initial");
_personDapperRepository.Delete(person);
triggerCount.ShouldBe(1);
_personDapperRepository.FirstOrDefault(p => p.Name == "Oguzhan_Initial").ShouldBe(null);
}
[Fact]
public void Dapper_and_NHibernate_should_work_under_same_unitofwork()
{
using (IUnitOfWorkCompleteHandle uow = Resolve<IUnitOfWorkManager>().Begin())
{
int personId = _personDapperRepository.InsertAndGetId(new Person("Oguzhan_Same_Uow"));
Person person = _personRepository.Get(personId);
person.ShouldNotBeNull();
uow.Complete();
}
}
[Fact]
public void Dapper_and_NHibernate_should_work_under_same_unitofwork_and_when_any_exception_appears_then_rollback_should__be_consistent_for_two_orm()
{
Resolve<IEventBus>().Register<EntityCreatingEventData<Person>>(
eventData =>
{
eventData.Entity.Name.ShouldBe("Oguzhan_Same_Uow");
throw new ApplicationException("Uow Rollback");
});
try
{
using (IUnitOfWorkCompleteHandle uow = Resolve<IUnitOfWorkManager>().Begin())
{
int personId = _personDapperRepository.InsertAndGetId(new Person("Oguzhan_Same_Uow"));
Person person = _personRepository.Get(personId);
person.ShouldNotBeNull();
uow.Complete();
}
}
catch
{
//no handling.
}
_personDapperRepository.FirstOrDefault(x => x.Name == "Oguzhan_Same_Uow").ShouldBeNull();
_personRepository.FirstOrDefault(x => x.Name == "Oguzhan_Same_Uow").ShouldBeNull();
}
}
}
| 35.810345 | 156 | 0.603595 | [
"MIT"
] | 12321/aspnetboilerplate | test/Abp.Dapper.NHibernate.Tests/DapperNhBasedRepository_Tests.cs | 6,233 | C# |
using Newtonsoft.Json;
namespace Alexa.NET.Management.ReferenceCatalogManagement
{
public class CatalogScheduleTrigger:IUpdateJobTrigger
{
[JsonProperty("type")] public string Type => "Schedule";
[JsonProperty("hour")]
public int Hour { get; set; }
[JsonProperty("dayOfWeek",NullValueHandling = NullValueHandling.Ignore)]
public int? DayOfWeek { get; set; }
}
} | 29.714286 | 80 | 0.677885 | [
"MIT"
] | stoiveyp/Alexa.NET.Management | Alexa.NET.Management/ReferenceCatalogManagement/CatalogScheduleTrigger.cs | 418 | C# |
// --------------------------------------------------------------------------------------------
// <copyright file="DataLoaderConfigurationLatchMock.cs" company="Effort Team">
// Copyright (C) Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------
namespace Effort.Test.Internal.Fakes
{
using Effort.DataLoaders;
public class DataLoaderConfigurationLatchMock : IDataLoaderConfigurationLatch
{
public DataLoaderConfigurationLatchMock()
{
this.AcquireCallCount = 0;
this.ReleaseCallCount = 0;
}
public int AcquireCallCount
{
get;
set;
}
public int ReleaseCallCount
{
get;
set;
}
public void Acquire()
{
this.AcquireCallCount++;
}
public void Release()
{
this.ReleaseCallCount++;
}
}
}
| 36.616667 | 97 | 0.573964 | [
"MIT"
] | HydAu/EFeffort | Main/Source/Effort.Test/Internal/Fakes/DataLoaderConfigurationLatchMock.cs | 2,199 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Generated by the MSBuild WriteCodeFragment class.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("AspNetCoreSslExample")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("AspNetCoreSslExample")]
[assembly: System.Reflection.AssemblyTitleAttribute("AspNetCoreSslExample")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] | 52.941176 | 81 | 0.671111 | [
"MIT"
] | tanaka-takayoshi/aspnetcore-ssl-exameple | AspNetCoreSslExample/obj/Debug/netcoreapp2.0/AspNetCoreSslExample.AssemblyInfo.cs | 900 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using F0.Cli;
namespace F0.Tests.Commands
{
internal sealed class InternalCommand : CommandBase
{
internal const string Name = "internal";
public InternalCommand()
{
}
internal string[]? Args { get; set; }
internal string? Internal { get; set; }
public override Task<CommandResult> ExecuteAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
}
| 18.230769 | 87 | 0.732068 | [
"MIT"
] | Flash0ver/F0.Cli | source/test/F0.Cli.Tests/Commands/InternalCommand.cs | 474 | C# |
// Copyright © 2017 Valdis Iljuconoks.
// 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.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using FluiTec.DbLocalizationProvider.Abstractions;
using FluiTec.DbLocalizationProvider.Internal;
namespace FluiTec.DbLocalizationProvider.Sync
{
internal class LocalizedEnumTypeScanner : IResourceTypeScanner
{
public bool ShouldScan(Type target)
{
return target.BaseType == typeof(Enum) && target.GetCustomAttribute<LocalizedResourceAttribute>() != null;
}
public string GetResourceKeyPrefix(Type target, string keyPrefix = null)
{
var resourceAttribute = target.GetCustomAttribute<LocalizedResourceAttribute>();
return !string.IsNullOrEmpty(resourceAttribute?.KeyPrefix)
? resourceAttribute?.KeyPrefix
: string.IsNullOrEmpty(keyPrefix)
? target.FullName
: keyPrefix;
}
public ICollection<DiscoveredResource> GetClassLevelResources(Type target, string resourceKeyPrefix)
{
return Enumerable.Empty<DiscoveredResource>().ToList();
}
public ICollection<DiscoveredResource> GetResources(Type target, string resourceKeyPrefix)
{
var enumType = Enum.GetUnderlyingType(target);
var isHidden = target.GetCustomAttribute<HiddenAttribute>() != null;
string GetEnumTranslation(MemberInfo mi)
{
var result = mi.Name;
var displayAttribute = mi.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute != null)
result = displayAttribute.Name;
return result;
}
return target.GetMembers(BindingFlags.Public | BindingFlags.Static)
.Select(mi =>
{
var isResourceHidden = isHidden || mi.GetCustomAttribute<HiddenAttribute>() != null;
var translations = DiscoveredTranslation.FromSingle(GetEnumTranslation(mi));
var additionalTranslationsAttributes =
mi.GetCustomAttributes<TranslationForCultureAttribute>().ToList();
if (additionalTranslationsAttributes.Any())
translations.AddRange(additionalTranslationsAttributes.Select(_ =>
new DiscoveredTranslation(_.Translation, _.Culture)));
return new DiscoveredResource(mi,
ResourceKeyBuilder.BuildResourceKey(target, mi.Name),
translations,
mi.Name,
target,
enumType,
enumType.IsSimpleType(),
isResourceHidden);
})
.ToList();
}
}
} | 43.182796 | 118 | 0.643177 | [
"Apache-2.0",
"MIT"
] | FluiTec/FluiTec.AppFx.Localization | src/LocalizationProvider/src/DbLocalizationProvider/Sync/LocalizedEnumTypeScanner.cs | 4,019 | 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("02-Vowels-Count")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02-Vowels-Count")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3fd72b7a-8044-41cd-a411-22fbe348bd66")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784 | 84 | 0.746066 | [
"Apache-2.0"
] | KostadinovK/Technology-Fundamentals | 07-Methods-Functions/Homework/02-Vowels-Count/Properties/AssemblyInfo.cs | 1,401 | C# |
// Copyright (c) Russlan Akiev. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityBase.Twilio
{
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ServiceBase.Notification.Sms;
using ServiceBase.Notification.Twilio;
using ServiceBase.Plugins;
public class ConfigureServicesAction : IConfigureServicesAction
{
public void Execute(IServiceCollection services)
{
IServiceProvider serviceProvider = services
.BuildServiceProvider();
IConfiguration configuration = serviceProvider
.GetService<IConfiguration>();
services.AddScoped<ISmsService, DefaultSmsService>();
services.AddSingleton(configuration
.GetSection("Sms").Get<DefaultSmsServiceOptions>());
services.AddScoped<ISmsSender, TwilioSmsSender>();
services.AddSingleton(configuration
.GetSection("Sms:Twilio").Get<TwilioOptions>());
}
}
}
| 33.2 | 107 | 0.674699 | [
"Apache-2.0"
] | BGuang/IdentityBase | src/IdentityBase.Web/Plugins/IdentityBase.Twilio/ConfigureServicesAction.cs | 1,162 | C# |
using System;
using System.Runtime.InteropServices;
namespace SevenZip.NativeInterface.IO
{
/// <summary>
/// An interface with no implementation.
/// </summary>
[Guid("23170F69-40C1-278A-0000-000300060000")]
[InterfaceImplementation(InterfaceImplementarionType.NotImplemented)]
public interface IStreamGetSize
: IUnknown
{
// **** Not yet implemented. ****
// void GetSize(UInt64 * size);
}
}
| 23.842105 | 73 | 0.657837 | [
"MIT"
] | rougemeilland/SevenZip.Compression.Wrapper.NET | SevenZip.NativeInterface/IO/IStreamGetSize.cs | 455 | C# |
using System;
using D_Parser.Formatting;
using D_Parser.Formatting.Indent;
using MonoDevelop.Ide.Gui.Content;
namespace MonoDevelop.D.Formatting.Indentation
{
public class DIndentEngine : IndentEngine, IDocumentStateEngine, DFormattingOptionsFactory
{
DFormattingPolicy policy;
TextStylePolicy textStyle;
public DIndentEngine(DFormattingPolicy policy, TextStylePolicy textStyle)
: base(policy.Options, textStyle.TabsToSpaces, textStyle.IndentWidth, policy.KeepAlignmentSpaces)
{
this.policy = policy;
this.textStyle = textStyle;
}
protected override IndentEngine Construct()
{
return new DIndentEngine(policy, textStyle);
}
}
}
| 25.653846 | 100 | 0.785607 | [
"Apache-2.0"
] | llucenic/Mono-D | MonoDevelop.DBinding/Formatting/Indentation/DIndentEngine.cs | 669 | C# |
using Codetox;
using UnityEngine;
namespace Codetox.Variables
{
[CreateAssetMenu(menuName = Framework.MenuRoot.Variables.Reference, fileName = nameof(ReferenceVariable), order = 12)]
public sealed class ReferenceVariable : Variable<Object>
{
}
} | 26.3 | 122 | 0.749049 | [
"MIT"
] | aruizrab/codetox-for-unity | Runtime/Variables/ReferenceVariable.cs | 265 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Text;
namespace DocGenerator.Documentation.Blocks
{
public class JavaScriptBlock : CodeBlock
{
public JavaScriptBlock(string text, int startingLine, int depth, string memberName = null)
: base(text, startingLine, depth, "javascript", memberName) { }
public string Title { get; set; }
public override string ToAsciiDoc()
{
var builder = new StringBuilder();
if (!string.IsNullOrEmpty(Title))
builder.AppendLine("." + Title);
builder.AppendLine(!string.IsNullOrEmpty(MemberName)
? $"[source, {Language.ToLowerInvariant()}, method=\"{MemberName.ToLowerInvariant()}\"]"
: $"[source, {Language.ToLowerInvariant()}]");
builder.AppendLine("----");
var (code, callOuts) = BlockCallOutHelper.ExtractCallOutsFromCode(Value);
builder.AppendLine(code);
builder.AppendLine("----");
foreach (var callOut in callOuts) builder.AppendLine(callOut);
return builder.ToString();
}
}
}
| 31.027027 | 92 | 0.715157 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | src/DocGenerator/Documentation/Blocks/JavaScriptBlock.cs | 1,148 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Labs_81_ASP_Framework_ToDoV2
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 26.681818 | 70 | 0.715503 | [
"MIT"
] | Lidinh26/Sparta-C-Sharp-Course | Labs_81_ASP_Framework_ToDoV2/Global.asax.cs | 589 | 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.Azure.WebJobs.Extensions.SignalRService
{
internal class SignalRCollectorBuilder<T> : IConverter<SignalRAttribute, IAsyncCollector<T>>
{
private readonly SignalRConfigProvider configProvider;
public SignalRCollectorBuilder(SignalRConfigProvider configProvider)
{
this.configProvider = configProvider;
}
public IAsyncCollector<T> Convert(SignalRAttribute attribute)
{
var client = configProvider.GetAzureSignalRClient(attribute.ConnectionStringSetting, attribute.HubName);
return new SignalRAsyncCollector<T>(client);
}
}
}
| 36.454545 | 116 | 0.721945 | [
"MIT"
] | JialinXin/azure-functions-signalrservice-extension | src/SignalRServiceExtension/Bindings/SignalRCollectorBuilder.cs | 804 | C# |
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering.HighDefinition
{
class SharedRTManager
{
// The render target used when we do not support MSAA
RTHandle m_NormalRT = null;
RTHandle m_MotionVectorsRT = null;
RTHandle m_CameraDepthStencilBuffer = null;
// Needed in case passes will need to read stencil per pixel rather than per sample
// The best we can do for resolve is an OR of all samples, however this is inaccurate by nature.
RTHandle m_StencilBufferResolved;
RTHandle m_CameraDepthBufferMipChain;
RTHandle m_CameraHalfResDepthBuffer = null;
HDUtils.PackedMipChainInfo m_CameraDepthBufferMipChainInfo; // This is metadata
// The two render targets that should be used when we render in MSAA
RTHandle m_NormalMSAART = null;
RTHandle m_MotionVectorsMSAART = null;
// This texture must be used because reading directly from an MSAA Depth buffer is way to expensive. The solution that we went for is writing the depth in an additional color buffer (10x cheaper to solve on ps4)
RTHandle m_DepthAsColorMSAART = null;
RTHandle m_CameraDepthStencilMSAABuffer;
// This texture stores a set of depth values that are required for evaluating a bunch of effects in MSAA mode (R = Samples Max Depth, G = Samples Min Depth, G = Samples Average Depth)
RTHandle m_CameraDepthValuesBuffer = null;
ComputeBuffer m_CoarseStencilBuffer = null;
// MSAA resolve materials
Material m_DepthResolveMaterial = null;
Material m_ColorResolveMaterial = null;
// Flags that defines if we are using a local texture or external
bool m_ReuseGBufferMemory = false;
bool m_MotionVectorsSupport = false;
bool m_MSAASupported = false;
MSAASamples m_MSAASamples = MSAASamples.None;
// Arrays of RTIDs that are used to set render targets (when MSAA and when not MSAA)
protected RenderTargetIdentifier[] m_RTIDs1 = new RenderTargetIdentifier[1];
protected RenderTargetIdentifier[] m_RTIDs2 = new RenderTargetIdentifier[2];
protected RenderTargetIdentifier[] m_RTIDs3 = new RenderTargetIdentifier[3];
// Property block used for the resolves
MaterialPropertyBlock m_PropertyBlock = new MaterialPropertyBlock();
public SharedRTManager()
{
}
public void InitSharedBuffers(GBufferManager gbufferManager, RenderPipelineSettings settings, RenderPipelineResources resources)
{
// Set the flags
m_MSAASupported = settings.supportMSAA && settings.supportedLitShaderMode != RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly;
m_MSAASamples = m_MSAASupported ? settings.msaaSampleCount : MSAASamples.None;
m_MotionVectorsSupport = settings.supportMotionVectors;
m_ReuseGBufferMemory = settings.supportedLitShaderMode != RenderPipelineSettings.SupportedLitShaderMode.ForwardOnly;
// Create the depth/stencil buffer
m_CameraDepthStencilBuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, DepthBits.Depth32, dimension: TextureXR.dimension, useDynamicScale: true, name: "CameraDepthStencil");
// Create the mip chain buffer
m_CameraDepthBufferMipChainInfo = new HDUtils.PackedMipChainInfo();
m_CameraDepthBufferMipChainInfo.Allocate();
m_CameraDepthBufferMipChain = RTHandles.Alloc(ComputeDepthBufferMipChainSize, TextureXR.slices, colorFormat: GraphicsFormat.R32_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, name: "CameraDepthBufferMipChain");
if(settings.lowresTransparentSettings.enabled)
{
// Create the half res depth buffer used for low resolution transparency
m_CameraHalfResDepthBuffer = RTHandles.Alloc(Vector2.one * 0.5f, TextureXR.slices, DepthBits.Depth32, dimension: TextureXR.dimension, useDynamicScale: true, name: "LowResDepthBuffer");
}
if (m_MotionVectorsSupport)
{
m_MotionVectorsRT = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: Builtin.GetMotionVectorFormat(), dimension: TextureXR.dimension, useDynamicScale: true, name: "MotionVectors");
if (m_MSAASupported)
{
m_MotionVectorsMSAART = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: Builtin.GetMotionVectorFormat(), dimension: TextureXR.dimension, enableMSAA: true, bindTextureMS: true, useDynamicScale: true, name: "MotionVectorsMSAA");
}
}
// Allocate the additional textures only if MSAA is supported
if (m_MSAASupported)
{
// Let's create the MSAA textures
m_CameraDepthStencilMSAABuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, DepthBits.Depth24, dimension: TextureXR.dimension, bindTextureMS: true, enableMSAA: true, useDynamicScale: true, name: "CameraDepthStencilMSAA");
m_CameraDepthValuesBuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R32G32B32A32_SFloat, dimension: TextureXR.dimension, useDynamicScale: true, name: "DepthValuesBuffer");
m_DepthAsColorMSAART = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R32_SFloat, dimension: TextureXR.dimension, bindTextureMS: true, enableMSAA: true, useDynamicScale: true, name: "DepthAsColorMSAA");
m_StencilBufferResolved = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8_UInt, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, name: "StencilBufferResolved");
// We need to allocate this texture as long as msaa is supported because on both mode, one of the cameras can be forward only using the framesettings
m_NormalMSAART = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_UNorm, dimension: TextureXR.dimension, enableMSAA: true, bindTextureMS: true, useDynamicScale: true, name: "NormalBufferMSAA");
// Create the required resolve materials
m_DepthResolveMaterial = CoreUtils.CreateEngineMaterial(resources.shaders.depthValuesPS);
m_ColorResolveMaterial = CoreUtils.CreateEngineMaterial(resources.shaders.colorResolvePS);
}
AllocateCoarseStencilBuffer(RTHandles.maxWidth, RTHandles.maxHeight, TextureXR.slices);
// If we are in the forward only mode
if (!m_ReuseGBufferMemory)
{
// In case of full forward we must allocate the render target for normal buffer (or reuse one already existing)
// TODO: Provide a way to reuse a render target
m_NormalRT = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_UNorm, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, name: "NormalBuffer");
}
else
{
// When not forward only we should are using the normal buffer of the gbuffer
// In case of deferred, we must be in sync with NormalBuffer.hlsl and lit.hlsl files and setup the correct buffers
m_NormalRT = gbufferManager.GetNormalBuffer(0); // Normal + Roughness
}
}
public bool IsConsolePlatform()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12;
}
// Function that will return the set of buffers required for the prepass (depending on if msaa is enabled or not)
public RenderTargetIdentifier[] GetPrepassBuffersRTI(FrameSettings frameSettings)
{
if (frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
Debug.Assert(m_MSAASupported);
m_RTIDs2[0] = m_NormalMSAART.nameID;
m_RTIDs2[1] = m_DepthAsColorMSAART.nameID;
return m_RTIDs2;
}
else
{
m_RTIDs1[0] = m_NormalRT.nameID;
return m_RTIDs1;
}
}
// Function that will return the set of buffers required for the motion vector pass
public RenderTargetIdentifier[] GetMotionVectorsPassBuffersRTI(FrameSettings frameSettings)
{
Debug.Assert(m_MotionVectorsSupport);
if (frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
Debug.Assert(m_MSAASupported);
m_RTIDs3[0] = m_MotionVectorsMSAART.nameID;
m_RTIDs3[1] = m_NormalMSAART.nameID;
m_RTIDs3[2] = m_DepthAsColorMSAART.nameID;
return m_RTIDs3;
}
else
{
Debug.Assert(m_MotionVectorsSupport);
m_RTIDs2[0] = m_MotionVectorsRT.nameID;
m_RTIDs2[1] = m_NormalRT.nameID;
return m_RTIDs2;
}
}
// Request the normal buffer (MSAA or not)
public RTHandle GetNormalBuffer(bool isMSAA = false)
{
if (isMSAA)
{
Debug.Assert(m_MSAASupported);
return m_NormalMSAART;
}
else
{
return m_NormalRT;
}
}
// Request the motion vectors buffer (MSAA or not)
public RTHandle GetMotionVectorsBuffer(bool isMSAA = false)
{
Debug.Assert(m_MotionVectorsSupport);
if (isMSAA)
{
Debug.Assert(m_MSAASupported);
return m_MotionVectorsMSAART;
}
else
{
return m_MotionVectorsRT;
}
}
// Request the depth stencil buffer (MSAA or not)
public RTHandle GetDepthStencilBuffer(bool isMSAA = false)
{
if (isMSAA)
{
Debug.Assert(m_MSAASupported);
return m_CameraDepthStencilMSAABuffer;
}
else
{
return m_CameraDepthStencilBuffer;
}
}
public RTHandle GetStencilBuffer(bool isMSAA = false)
{
if (isMSAA)
{
Debug.Assert(m_MSAASupported);
return m_StencilBufferResolved;
}
else
{
return m_CameraDepthStencilBuffer;
}
}
public ComputeBuffer GetCoarseStencilBuffer()
{
return m_CoarseStencilBuffer;
}
public RTHandle GetLowResDepthBuffer()
{
return m_CameraHalfResDepthBuffer;
}
// Request the depth texture (MSAA or not)
public RTHandle GetDepthTexture(bool isMSAA = false)
{
if (isMSAA)
{
Debug.Assert(m_MSAASupported);
return m_DepthAsColorMSAART;
}
else
{
return m_CameraDepthBufferMipChain;
}
}
public RTHandle GetDepthValuesTexture()
{
Debug.Assert(m_MSAASupported);
return m_CameraDepthValuesBuffer;
}
public void SetNumMSAASamples(MSAASamples msaaSamples)
{
m_MSAASamples = msaaSamples;
}
public Vector2Int ComputeDepthBufferMipChainSize(Vector2Int screenSize)
{
m_CameraDepthBufferMipChainInfo.ComputePackedMipChainInfo(screenSize);
return m_CameraDepthBufferMipChainInfo.textureSize;
}
public HDUtils.PackedMipChainInfo GetDepthBufferMipChainInfo()
{
return m_CameraDepthBufferMipChainInfo;
}
public void Build(HDRenderPipelineAsset hdAsset)
{
}
public void AllocateCoarseStencilBuffer(int width, int height, int viewCount)
{
if(width > 8 && height > 8)
m_CoarseStencilBuffer = new ComputeBuffer(HDUtils.DivRoundUp(width, 8) * HDUtils.DivRoundUp(height, 8) * viewCount, sizeof(uint));
}
public void DisposeCoarseStencilBuffer()
{
CoreUtils.SafeRelease(m_CoarseStencilBuffer);
}
public void Cleanup()
{
if (!m_ReuseGBufferMemory)
{
RTHandles.Release(m_NormalRT);
}
if (m_MotionVectorsSupport)
{
RTHandles.Release(m_MotionVectorsRT);
if (m_MSAASupported)
{
RTHandles.Release(m_MotionVectorsMSAART);
}
}
RTHandles.Release(m_CameraDepthStencilBuffer);
RTHandles.Release(m_CameraDepthBufferMipChain);
RTHandles.Release(m_CameraHalfResDepthBuffer);
DisposeCoarseStencilBuffer();
if (m_MSAASupported)
{
RTHandles.Release(m_CameraDepthStencilMSAABuffer);
RTHandles.Release(m_CameraDepthValuesBuffer);
RTHandles.Release(m_StencilBufferResolved);
RTHandles.Release(m_NormalMSAART);
RTHandles.Release(m_DepthAsColorMSAART);
// Do not forget to release the materials
CoreUtils.Destroy(m_DepthResolveMaterial);
CoreUtils.Destroy(m_ColorResolveMaterial);
}
}
public static int SampleCountToPassIndex(MSAASamples samples)
{
switch (samples)
{
case MSAASamples.None:
return 0;
case MSAASamples.MSAA2x:
return 1;
case MSAASamples.MSAA4x:
return 2;
case MSAASamples.MSAA8x:
return 3;
};
return 0;
}
// Bind the normal buffer that is needed
public void BindNormalBuffer(CommandBuffer cmd, bool isMSAA = false)
{
// NormalBuffer can be access in forward shader, so need to set global texture
cmd.SetGlobalTexture(HDShaderIDs._NormalBufferTexture, GetNormalBuffer(isMSAA));
}
public void ResolveSharedRT(CommandBuffer cmd, HDCamera hdCamera)
{
if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
Debug.Assert(m_MSAASupported);
using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ResolveMSAADepth)))
{
// Grab the RTIs and set the output render targets
m_RTIDs3[0] = m_CameraDepthValuesBuffer.nameID;
m_RTIDs3[1] = m_NormalRT.nameID;
m_RTIDs3[2] = m_MotionVectorsRT.nameID;
CoreUtils.SetRenderTarget(cmd, m_RTIDs3, m_CameraDepthStencilBuffer);
// Set the input textures
Shader.SetGlobalTexture(HDShaderIDs._NormalTextureMS, m_NormalMSAART);
Shader.SetGlobalTexture(HDShaderIDs._DepthTextureMS, m_DepthAsColorMSAART);
Shader.SetGlobalTexture(HDShaderIDs._MotionVectorTextureMS, m_MotionVectorsMSAART);
// Resolve the depth and normal buffers
cmd.DrawProcedural(Matrix4x4.identity, m_DepthResolveMaterial, SampleCountToPassIndex(m_MSAASamples), MeshTopology.Triangles, 3, 1);
}
}
}
public void ResolveMSAAColor(CommandBuffer cmd, HDCamera hdCamera, RTHandle msaaTarget, RTHandle simpleTarget)
{
if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
Debug.Assert(m_MSAASupported);
using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ResolveMSAAColor)))
{
// Grab the RTIs and set the output render targets
CoreUtils.SetRenderTarget(cmd, simpleTarget);
// Set the input textures
m_PropertyBlock.SetTexture(HDShaderIDs._ColorTextureMS, msaaTarget);
// Resolve the depth and normal buffers
cmd.DrawProcedural(Matrix4x4.identity, m_ColorResolveMaterial, SampleCountToPassIndex(m_MSAASamples), MeshTopology.Triangles, 3, 1, m_PropertyBlock);
}
}
}
}
}
| 45.102362 | 264 | 0.611674 | [
"MIT"
] | WilsonRedSocks/OGPC13 | src/Library/PackageCache/com.unity.render-pipelines.high-definition@7.3.1/Runtime/Material/SharedRTManager.cs | 17,184 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.NET.HostModel.AppHost;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Microsoft.NET.HostModel.Bundle
{
/// <summary>
/// TargetInfo: Information about the target for which the single-file bundle is built.
///
/// Currently the TargetInfo only tracks:
/// - the target operating system
/// - the target architecture
/// - the target framework
/// - the default options for this target
/// - the assembly alignment for this target
/// </summary>
public class TargetInfo
{
public readonly OSPlatform OS;
public readonly Architecture Arch;
public readonly Version FrameworkVersion;
public readonly uint BundleMajorVersion;
public readonly BundleOptions DefaultOptions;
public readonly int AssemblyAlignment;
public TargetInfo(OSPlatform? os, Architecture? arch, Version targetFrameworkVersion)
{
OS = os ?? HostOS;
Arch = arch ?? RuntimeInformation.OSArchitecture;
FrameworkVersion = targetFrameworkVersion ?? net60;
Debug.Assert(IsLinux || IsOSX || IsWindows);
if (FrameworkVersion.CompareTo(net60) >= 0)
{
BundleMajorVersion = 6u;
DefaultOptions = BundleOptions.None;
}
else if (FrameworkVersion.CompareTo(net50) >= 0)
{
BundleMajorVersion = 2u;
DefaultOptions = BundleOptions.None;
}
else if (FrameworkVersion.Major == 3 && (FrameworkVersion.Minor == 0 || FrameworkVersion.Minor == 1))
{
BundleMajorVersion = 1u;
DefaultOptions = BundleOptions.BundleAllContent;
}
else
{
throw new ArgumentException($"Invalid input: Unsupported Target Framework Version {targetFrameworkVersion}");
}
if (IsLinux && Arch == Architecture.Arm64)
{
// We align assemblies in the bundle at 4K so that we can use mmap on Linux without changing the page alignment of ARM64 R2R code.
// This is only necessary for R2R assemblies, but we do it for all assemblies for simplicity.
// See https://github.com/dotnet/runtime/issues/41832.
AssemblyAlignment = 4096;
}
else if (IsWindows)
{
// We align assemblies in the bundle at 4K - per requirements of memory mapping API (MapViewOfFile3, et al).
// This is only necessary for R2R assemblies, but we do it for all assemblies for simplicity.
AssemblyAlignment = 4096;
}
else
{
// Otherwise, assemblies are 64 bytes aligned, so that their sections can be memory-mapped cache aligned.
AssemblyAlignment = 64;
}
}
public bool IsNativeBinary(string filePath)
{
return IsLinux ? ElfUtils.IsElfImage(filePath) : IsOSX ? MachOUtils.IsMachOImage(filePath) : PEUtils.IsPEImage(filePath);
}
public string GetAssemblyName(string hostName)
{
// This logic to calculate assembly name from hostName should be removed (and probably moved to test helpers)
// once the SDK in the correct assembly name.
return (IsWindows ? Path.GetFileNameWithoutExtension(hostName) : hostName);
}
public override string ToString()
{
string os = IsWindows ? "win" : IsLinux ? "linux" : "osx";
string arch = Arch.ToString().ToLowerInvariant();
return $"OS: {os} Arch: {arch} FrameworkVersion: {FrameworkVersion}";
}
private static OSPlatform HostOS => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? OSPlatform.Linux :
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? OSPlatform.OSX : OSPlatform.Windows;
public bool IsLinux => OS.Equals(OSPlatform.Linux);
public bool IsOSX => OS.Equals(OSPlatform.OSX);
public bool IsWindows => OS.Equals(OSPlatform.Windows);
// The .net core 3 apphost doesn't care about semantics of FileType -- all files are extracted at startup.
// However, the apphost checks that the FileType value is within expected bounds, so set it to the first enumeration.
public FileType TargetSpecificFileType(FileType fileType) => (BundleMajorVersion == 1) ? FileType.Unknown : fileType;
// In .net core 3.x, bundle processing happens within the AppHost.
// Therefore HostFxr and HostPolicy can be bundled within the single-file app.
// In .net 5, bundle processing happens in HostFxr and HostPolicy libraries.
// Therefore, these libraries themselves cannot be bundled into the single-file app.
// This problem is mitigated by statically linking these host components with the AppHost.
// https://github.com/dotnet/runtime/issues/32823
public bool ShouldExclude(string relativePath) =>
(FrameworkVersion.Major != 3) && (relativePath.Equals(HostFxr) || relativePath.Equals(HostPolicy));
private readonly Version net60 = new Version(6, 0);
private readonly Version net50 = new Version(5, 0);
private string HostFxr => IsWindows ? "hostfxr.dll" : IsLinux ? "libhostfxr.so" : "libhostfxr.dylib";
private string HostPolicy => IsWindows ? "hostpolicy.dll" : IsLinux ? "libhostpolicy.so" : "libhostpolicy.dylib";
}
}
| 45.519685 | 146 | 0.631898 | [
"MIT"
] | 333fred/runtime | src/installer/managed/Microsoft.NET.HostModel/Bundle/TargetInfo.cs | 5,781 | 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 ControlGallery.Xaml.SamplePages.Layout
{
/// <summary>
/// Interaction logic for RelativeCanvas.xaml
/// </summary>
public partial class RelativeCanvas : UserControl
{
public RelativeCanvas()
{
InitializeComponent();
}
}
}
| 23.344828 | 53 | 0.728213 | [
"MIT"
] | kalatchev/Celestial.UIToolkit | src/ControlGallery/Xaml/SamplePages/Layout/RelativeCanvas.xaml.cs | 679 | C# |
namespace Web.Sample
{
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
} | 23.421053 | 73 | 0.593258 | [
"MIT"
] | jmanuelcorral/APIMocker | src/sample/Web.Sample/Program.cs | 447 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace IronAHK.Rusty.Linux.X11.Events
{
internal enum XEventName
{
KeyPress = 2,
KeyRelease = 3,
ButtonPress = 4,
ButtonRelease = 5,
MotionNotify = 6,
EnterNotify = 7,
LeaveNotify = 8,
FocusIn = 9,
FocusOut = 10,
KeymapNotify = 11,
Expose = 12,
GraphicsExpose = 13,
NoExpose = 14,
VisibilityNotify = 15,
CreateNotify = 16,
DestroyNotify = 17,
UnmapNotify = 18,
MapNotify = 19,
MapRequest = 20,
ReparentNotify = 21,
ConfigureNotify = 22,
ConfigureRequest = 23,
GravityNotify = 24,
ResizeRequest = 25,
CirculateNotify = 26,
CirculateRequest = 27,
PropertyNotify = 28,
SelectionClear = 29,
SelectionRequest = 30,
SelectionNotify = 31,
ColormapNotify = 32,
ClientMessage = 33,
MappingNotify = 34,
TimerNotify = 100,
LASTEvent
}
}
| 23.212766 | 40 | 0.546288 | [
"BSD-2-Clause"
] | Paris/IronAHK | Rusty/Linux/X11/Events/XEventName.cs | 1,093 | C# |
namespace PenguinUpload.DataModels.Auth
{
public class RegistrationRequest
{
public string Username { get; set; }
public string Password { get; set; }
public string InviteKey { get; set; }
}
} | 25.444444 | 45 | 0.633188 | [
"Apache-2.0"
] | 0xFireball/PenguinUpload | src/PenguinUpload/DataModels/Auth/RegistrationRequest.cs | 231 | C# |
// Custom Renderer
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AtomicEngine;
namespace AtomicBlaster
{
[StructLayout(LayoutKind.Sequential)]
struct PositionColorUVVertex
{
public float X, Y, Z;
public uint Color;
public float U, V;
};
class Batch
{
public Texture2D Texture;
public uint VertexCount = 0;
public PositionColorUVVertex[] Vertices = new PositionColorUVVertex[256];
}
struct DrawItem
{
public Texture2D Texture;
public uint StartVertex;
public uint VertexCount;
}
static class CustomRenderer
{
// 250k max vertices
const uint maxVertices = 256 * 1024;
static uint totalVertex = 0;
static VertexBuffer vertexBuffer;
static ShaderVariation pixelShader;
static ShaderVariation vertexShader;
static SortedDictionary<float, Dictionary<Texture2D, Batch>> layerBatches = new SortedDictionary<float, Dictionary<Texture2D, Batch>>();
public static void Initialize()
{
var graphics = AtomicNET.GetSubsystem<Graphics>();
pixelShader = graphics.GetShader(ShaderType.PS, "Atomic2D");
vertexShader = graphics.GetShader(ShaderType.VS, "Atomic2D");
vertexBuffer = new VertexBuffer();
vertexBuffer.SetSize(maxVertices, Constants.MASK_POSITION | Constants.MASK_COLOR | Constants.MASK_TEXCOORD1, true);
}
public static void Begin()
{
totalVertex = 0;
// reset batches
foreach (var layer in layerBatches)
{
foreach (var batch in layer.Value.Values)
{
batch.VertexCount = 0;
}
}
}
unsafe public static void End()
{
List<DrawItem> drawList = new List<DrawItem>();
if (totalVertex == 0)
return;
IntPtr vertexData = vertexBuffer.Lock(0, totalVertex, true);
if (vertexData == IntPtr.Zero)
return;
uint startVertex = 0;
PositionColorUVVertex* vout = (PositionColorUVVertex*)vertexData;
foreach (var layer in layerBatches)
{
foreach (var batch in layer.Value.Values)
{
if (totalVertex + batch.VertexCount >= maxVertices)
{
throw new System.InvalidOperationException("Ran out of vertices");
}
if (batch.VertexCount == 0)
continue;
// faster blit possible?
for (uint i = 0; i < batch.VertexCount; i++, vout++)
{
*vout = batch.Vertices[i];
}
var item = new DrawItem();
item.Texture = batch.Texture;
item.StartVertex = startVertex;
item.VertexCount = batch.VertexCount;
startVertex += batch.VertexCount;
drawList.Add(item);
}
}
vertexBuffer.Unlock();
var renderer = AtomicNET.GetSubsystem<Renderer>();
var graphics = AtomicNET.GetSubsystem<Graphics>();
var view = renderer.GetViewport(0).View;
var camera = renderer.GetViewport(0).Camera;
if (view == null || camera == null)
return;
graphics.SetBlendMode(BlendMode.BLEND_ADDALPHA);
graphics.SetCullMode(CullMode.CULL_NONE);
graphics.SetFillMode(FillMode.FILL_SOLID);
graphics.SetDepthTest(CompareMode.CMP_ALWAYS);
graphics.SetShaders(vertexShader, pixelShader);
view.SetCameraShaderParameters(camera);
graphics.SetShaderParameter(ShaderParams.VSP_MODEL, Matrix3x4.IDENTITY);
graphics.SetShaderParameter(ShaderParams.PSP_MATDIFFCOLOR, Color.White);
graphics.SetVertexBuffer(vertexBuffer);
foreach (var item in drawList)
{
graphics.SetTexture((int) TextureUnit.TU_DIFFUSE, item.Texture);
graphics.Draw(PrimitiveType.TRIANGLE_LIST, item.StartVertex, item.VertexCount);
}
graphics.SetTexture(0, null);
}
public static void Draw(CustomSprite texture, Vector2 position, Color color, float rotation, Vector2 origin, float scale, float layerDepth)
{
var w = texture.Width * scale;
var h = texture.Height * scale;
DrawInternal(texture,
new Vector4(position.X, position.Y, w, h),
color,
rotation,
origin * scale,
layerDepth);
}
public static void Draw(CustomSprite texture, Vector2 position, Color color, float rotation, Vector2 origin, Vector2 scale, float layerDepth)
{
var w = texture.Width * scale.X;
var h = texture.Height * scale.Y;
DrawInternal(texture,
new Vector4(position.X, position.Y, w, h),
color,
rotation,
origin * scale,
layerDepth);
}
public static void DrawLine(Vector2 start, Vector2 end, Color color, float thickness = 2f)
{
Vector2 delta = end - start;
Draw(Art.Pixel, start, color, delta.ToAngle(), new Vector2(0, 0.5f), new Vector2(delta.Length, thickness), 0f);
}
static void DrawInternal(CustomSprite sprite, Vector4 destinationRectangle, Color color, float rotation, Vector2 origin, float depth)
{
Dictionary<Texture2D, Batch> batches;
if (!layerBatches.TryGetValue(depth, out batches))
{
batches = new Dictionary<Texture2D, Batch>();
layerBatches[depth] = batches;
}
Batch batch;
var texture = sprite.Texture;
if (!batches.TryGetValue(texture, out batch))
{
batch = new Batch();
batch.Texture = texture;
batches[texture] = batch;
}
if (totalVertex + 6 >= maxVertices)
{
throw new System.InvalidOperationException("Ran out of vertices");
}
totalVertex += 6;
if (batch.VertexCount + 6 >= batch.Vertices.Length)
{
Array.Resize(ref batch.Vertices, batch.Vertices.Length * 2);
}
if (rotation == 0f)
{
Set(batch.Vertices, ref batch.VertexCount, destinationRectangle.X - origin.X,
destinationRectangle.Y - origin.Y,
destinationRectangle.Z,
destinationRectangle.W,
color,
sprite.TexCoordTL,
sprite.TexCoordBR,
depth);
}
else
{
Set(batch.Vertices, ref batch.VertexCount, destinationRectangle.X,
destinationRectangle.Y,
-origin.X,
-origin.Y,
destinationRectangle.Z,
destinationRectangle.W,
(float)Math.Sin(rotation),
(float)Math.Cos(rotation),
color,
sprite.TexCoordTL,
sprite.TexCoordBR,
depth);
}
}
static Vector2 _texCoordTL = new Vector2(0, 0);
static Vector2 _texCoordBR = new Vector2(1, 1);
static PositionColorUVVertex vertexTL = new PositionColorUVVertex();
static PositionColorUVVertex vertexTR = new PositionColorUVVertex();
static PositionColorUVVertex vertexBL = new PositionColorUVVertex();
static PositionColorUVVertex vertexBR = new PositionColorUVVertex();
// Portions Copyright (C) The MonoGame Team
static public void Set(PositionColorUVVertex[] vertices, ref uint vertexCount, float x, float y, float dx, float dy, float w, float h, float sin, float cos, Color color, Vector2 texCoordTL, Vector2 texCoordBR, float depth)
{
uint ucolor = color.ToUInt();
vertexTL.X = x + dx * cos - dy * sin;
vertexTL.Y = y + dx * sin + dy * cos;
vertexTL.Z = depth;
vertexTL.Color = ucolor;
vertexTL.U = texCoordTL.X;
vertexTL.V = texCoordTL.Y;
vertexTR.X = x + (dx + w) * cos - dy * sin;
vertexTR.Y = y + (dx + w) * sin + dy * cos;
vertexTR.Z = depth;
vertexTR.Color = ucolor;
vertexTR.U = texCoordBR.X;
vertexTR.V = texCoordTL.Y;
vertexBL.X = x + dx * cos - (dy + h) * sin;
vertexBL.Y = y + dx * sin + (dy + h) * cos;
vertexBL.Z = depth;
vertexBL.Color = ucolor;
vertexBL.U = texCoordTL.X;
vertexBL.V = texCoordBR.Y;
vertexBR.X = x + (dx + w) * cos - (dy + h) * sin;
vertexBR.Y = y + (dx + w) * sin + (dy + h) * cos;
vertexBR.Z = depth;
vertexBR.Color = ucolor;
vertexBR.U = texCoordBR.X;
vertexBR.V = texCoordBR.Y;
vertices[vertexCount++] = vertexTL;
vertices[vertexCount++] = vertexTR;
vertices[vertexCount++] = vertexBL;
vertices[vertexCount++] = vertexTR;
vertices[vertexCount++] = vertexBR;
vertices[vertexCount++] = vertexBL;
}
static public void Set(PositionColorUVVertex[] vertices, ref uint vertexCount, float x, float y, float w, float h, Color color, Vector2 texCoordTL, Vector2 texCoordBR, float depth)
{
uint ucolor = color.ToUInt();
vertexTL.X = x;
vertexTL.Y = y;
vertexTL.Z = depth;
vertexTL.Color = ucolor;
vertexTL.U = texCoordTL.X;
vertexTL.V = texCoordTL.Y;
vertexTR.X = x + w;
vertexTR.Y = y;
vertexTR.Z = depth;
vertexTR.Color = ucolor;
vertexTR.U = texCoordBR.X;
vertexTR.V = texCoordTL.Y;
vertexBL.X = x;
vertexBL.Y = y + h;
vertexBL.Z = depth;
vertexBL.Color = ucolor;
vertexBL.U = texCoordTL.X;
vertexBL.V = texCoordBR.Y;
vertexBR.X = x + w;
vertexBR.Y = y + h;
vertexBR.Z = depth;
vertexBR.Color = ucolor;
vertexBR.U = texCoordBR.X;
vertexBR.V = texCoordBR.Y;
vertices[vertexCount++] = vertexTL;
vertices[vertexCount++] = vertexTR;
vertices[vertexCount++] = vertexBL;
vertices[vertexCount++] = vertexTR;
vertices[vertexCount++] = vertexBR;
vertices[vertexCount++] = vertexBL;
}
}
}
| 31.185083 | 230 | 0.528302 | [
"MIT"
] | AtomicGameEngine/AtomicExamples | AtomicBlaster/CSharp/Resources/Scripts/CustomRenderer.cs | 11,289 | C# |
using System;
namespace LogExpertSharp
{
public abstract class HttpService : IDisposable
{
protected readonly Connection Connection;
public HttpService(Connection connection)
{
Connection = connection;
}
public HttpService(string token)
{
Connection = new Connection(token);
}
public void Dispose() => Connection.Dispose();
}
} | 20.52381 | 54 | 0.600928 | [
"MIT"
] | Enhed/LogExpertSharp | HttpService.cs | 431 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.SpacingRules
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.SpacingRules;
using TestHelper;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1001CommasMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;
/// <summary>
/// This class contains unit tests for <see cref="SA1001CommasMustBeSpacedCorrectly"/> and
/// <see cref="TokenSpacingCodeFixProvider"/>.
/// </summary>
public class SA1001UnitTests
{
[Fact]
public async Task TestSpaceAfterCommaAsync()
{
string statement = "f(a, b);";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestNoSpaceAfterCommaAsync()
{
string statementWithoutSpace = @"f(a,b);";
string statementWithSpace = @"f(a, b);";
await this.TestCommaInStatementOrDeclAsync(statementWithSpace, DiagnosticResult.EmptyDiagnosticResults, statementWithSpace).ConfigureAwait(false);
DiagnosticResult expected = Diagnostic().WithArguments(string.Empty, "followed").WithLocation(7, 16);
await this.TestCommaInStatementOrDeclAsync(statementWithoutSpace, expected, statementWithSpace).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceBeforeCommaAsync()
{
string spaceBeforeComma = @"f(a , b);";
string spaceOnlyAfterComma = @"f(a, b);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 17);
await this.TestCommaInStatementOrDeclAsync(spaceBeforeComma, expected, spaceOnlyAfterComma).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceBeforeCommaAtEndOfLineAsync()
{
string spaceBeforeComma = $"f(a ,{Environment.NewLine}b);";
string spaceOnlyAfterComma = $"f(a,{Environment.NewLine}b);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 17);
await this.TestCommaInStatementOrDeclAsync(spaceBeforeComma, expected, spaceOnlyAfterComma).ConfigureAwait(false);
}
[Fact]
public async Task TestLastCommaInLineAsync()
{
string statement = $"f(a,{Environment.NewLine}b);";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestFirstCommaInLineAsync()
{
string testStatement = $"f(a{Environment.NewLine}, b);";
string fixedStatement = $"f(a,{Environment.NewLine}b);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(8, 1);
await this.TestCommaInStatementOrDeclAsync(testStatement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommentBeforeFirstCommaInLineAsync()
{
string testStatement = $"f(a // comment{Environment.NewLine}, b);";
string fixedStatement = $"f(a, // comment{Environment.NewLine}b);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(8, 1);
await this.TestCommaInStatementOrDeclAsync(testStatement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceBeforeCommaFollowedByAngleBracketInFuncTypeAsync()
{
string statement = @"var a = typeof(System.Func< ,>);";
string fixedStatement = @"var a = typeof(System.Func<,>);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 41);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedByAngleBracketInFuncTypeAsync()
{
string statement = @"var a = typeof(System.Func<,>);";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedBySpaceFollowedByAngleBracketInFuncTypeAsync()
{
// This is correct by SA1001, and reported as an error by SA1015
string statement = @"var a = typeof(System.Func<, >);";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceBeforeCommaFollowedByCommaInFuncTypeAsync()
{
string statement = @"var a = typeof(System.Func< ,,>);";
string fixedStatement = @"var a = typeof(System.Func<,,>);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 41);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedByCommaInFuncTypeAsync()
{
string statement = @"var a = typeof(System.Func<,,>);";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedBySpaceFollowedByCommaInFuncTypeAsync()
{
string statement = @"var a = typeof(System.Func<, ,>);";
string fixedStatement = @"var a = typeof(System.Func<,,>);";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 42);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedByBracketInArrayDeclAsync()
{
string statement = @"int[,] myArray;";
await this.TestCommaInStatementOrDeclAsync(statement, DiagnosticResult.EmptyDiagnosticResults, statement).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceBeforeCommaFollowedByBracketInArrayDeclAsync()
{
string statement = @"int[, ,] myArray;";
string fixedStatement = @"int[,,] myArray;";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 19);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
[WorkItem(2289, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2289")]
public async Task TestSpaceBeforeCommaWhenPartOfInterpolationAlignmentClauseAsync()
{
string statement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2] ,3}"";";
string fixedStatement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2],3}"";";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "preceded").WithLocation(8, 29);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
[WorkItem(2289, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2289")]
public async Task TestSpaceAfterCommaWhenPartOfInterpolationAlignmentClauseAsync()
{
string statement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2], 3}"";";
string fixedStatement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2],3}"";";
DiagnosticResult expected = Diagnostic().WithArguments(" not", "followed").WithLocation(8, 28);
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
[WorkItem(2289, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2289")]
public async Task TestSpaceBeforeAndAfterCommaWhenPartOfInterpolationAlignmentClauseAsync()
{
string statement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2] , 3}"";";
string fixedStatement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2],3}"";";
DiagnosticResult[] expected =
{
Diagnostic().WithArguments(" not", "preceded").WithLocation(8, 29),
Diagnostic().WithArguments(" not", "followed").WithLocation(8, 29),
};
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
[WorkItem(2289, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2289")]
public async Task TestSpaceAfterCommaWithMinusWhenPartOfInterpolationAlignmentClauseAsync()
{
string statement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2], -3}"";";
string fixedStatement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2],-3}"";";
DiagnosticResult[] expected =
{
Diagnostic().WithArguments(" not", "followed").WithLocation(8, 28),
};
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
[WorkItem(2289, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2289")]
public async Task TestSpaceAfterCommaWithPlusWhenPartOfInterpolationAlignmentClauseAsync()
{
string statement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2], +3}"";";
string fixedStatement = @"var x = new[] { 1, 2, 3, 4, 5, 6, 7 };
var t = $""{x[2],+3}"";";
DiagnosticResult[] expected =
{
Diagnostic().WithArguments(" not", "followed").WithLocation(8, 28),
};
await this.TestCommaInStatementOrDeclAsync(statement, expected, fixedStatement).ConfigureAwait(false);
}
[Fact]
public async Task TestSpaceOnlyBeforeCommaAsync()
{
string spaceOnlyBeforeComma = @"f(a ,b);";
string spaceOnlyAfterComma = @"f(a, b);";
DiagnosticResult[] expected =
{
Diagnostic().WithArguments(" not", "preceded").WithLocation(7, 17),
Diagnostic().WithArguments(string.Empty, "followed").WithLocation(7, 17),
};
await this.TestCommaInStatementOrDeclAsync(spaceOnlyBeforeComma, expected, spaceOnlyAfterComma).ConfigureAwait(false);
}
[Fact]
public async Task TestMissingCommaAsync()
{
string testCode = @"
class ClassName
{
void MethodName()
{
int[] exp = { 0 0 };
}
}
";
DiagnosticResult expected = DiagnosticResult.CompilerError("CS1003").WithMessage("Syntax error, ',' expected").WithLocation(6, 25);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestCommaFollowedByCommentAsync()
{
string testCode = @"
class ClassName
{
void MethodName()
{
int[] exp = { 0,/*comment*/ 0 };
}
}
";
string fixedCode = @"
class ClassName
{
void MethodName()
{
int[] exp = { 0, /*comment*/ 0 };
}
}
";
DiagnosticResult expected = Diagnostic().WithArguments(string.Empty, "followed").WithLocation(6, 24);
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
[WorkItem(2468, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2468")]
public async Task TestCodeFixCommaPlacementAsync()
{
var testCode = @"using System;
public class TestClass
{
public void TestMethod()
{
var test = (new[]
{
new Tuple<int, int>(1, 2)
,new Tuple<int, int>(3, 4)
,new Tuple<int, int>(5, 6)
}).ToString();
}
}
";
var fixedCode = @"using System;
public class TestClass
{
public void TestMethod()
{
var test = (new[]
{
new Tuple<int, int>(1, 2),
new Tuple<int, int>(3, 4),
new Tuple<int, int>(5, 6)
}).ToString();
}
}
";
DiagnosticResult[] expected =
{
Diagnostic().WithArguments(" not", "preceded").WithLocation(10, 12),
Diagnostic().WithArguments(string.Empty, "followed").WithLocation(10, 12),
Diagnostic().WithArguments(" not", "preceded").WithLocation(11, 12),
Diagnostic().WithArguments(string.Empty, "followed").WithLocation(11, 12),
};
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
}
private Task TestCommaInStatementOrDeclAsync(string originalStatement, DiagnosticResult expected, string fixedStatement)
{
return this.TestCommaInStatementOrDeclAsync(originalStatement, new[] { expected }, fixedStatement);
}
private async Task TestCommaInStatementOrDeclAsync(string originalStatement, DiagnosticResult[] expected, string fixedStatement)
{
string template = @"namespace Foo
{{
class Bar
{{
void Baz()
{{
{0}
}}
// The following fields and method are referenced by the tests and need definitions.
int a, b;
void f(int x, int y) {{ }}
}}
}}
";
string originalCode = string.Format(template, originalStatement);
string fixedCode = string.Format(template, fixedStatement);
var test = new CSharpTest
{
TestCode = originalCode,
FixedCode = fixedCode,
};
test.ExpectedDiagnostics.AddRange(expected);
await test.RunAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}
| 38.598446 | 158 | 0.614135 | [
"Apache-2.0"
] | Andreyul/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/SpacingRules/SA1001UnitTests.cs | 14,901 | C# |
using System;
using System.Globalization;
namespace Units
{
/// <summary>
/// Class ElectricCurrent.
/// Implements the <see cref="Unit{ElectricCurrent}" />
/// </summary>
/// <seealso cref="Unit{ElectricCurrent}" />
public class ElectricCurrent : Unit<ElectricCurrentUnit>
{
/// <summary>
/// Initializes a new instance of the <see cref="ElectricCurrent"/> class.
/// </summary>
/// <param name="unitValue">The unit value.</param>
public ElectricCurrent(double unitValue) : base(unitValue) { }
/// <summary>
/// Froms the amperes.
/// </summary>
/// <param name="amperes">The amperes.</param>
/// <returns>ElectricCurrent.</returns>
public static ElectricCurrent FromAmperes(double amperes)
{
return new ElectricCurrent(amperes);
}
/// <summary>
/// Gets the amperes.
/// </summary>
/// <value>The amperes.</value>
public double Amperes => UnitValue;
#region Operator overloads
/// <summary>
/// Implements the + operator.
/// </summary>
/// <param name="electricCurrent1">The electricCurrent1.</param>
/// <param name="electricCurrent2">The electricCurrent2.</param>
/// <returns>The result of the operator.</returns>
public static ElectricCurrent operator +(ElectricCurrent electricCurrent1, ElectricCurrent electricCurrent2)
{
return new ElectricCurrent(electricCurrent1.UnitValue + electricCurrent2.UnitValue);
}
/// <summary>
/// Implements the - operator.
/// </summary>
/// <param name="electricCurrent1">The electricCurrent1.</param>
/// <param name="electricCurrent2">The electricCurrent2.</param>
/// <returns>The result of the operator.</returns>
public static ElectricCurrent operator -(ElectricCurrent electricCurrent1, ElectricCurrent electricCurrent2)
{
return new ElectricCurrent(electricCurrent1.UnitValue - electricCurrent2.UnitValue);
}
/// <summary>
/// Implements the / operator.
/// </summary>
/// <param name="electricCurrent1">The electricCurrent1.</param>
/// <param name="value">The value.</param>
/// <returns>The result of the operator.</returns>
public static ElectricCurrent operator /(ElectricCurrent electricCurrent1, double value)
{
return new ElectricCurrent(electricCurrent1.UnitValue / value);
}
/// <summary>
/// Implements the * operator.
/// </summary>
/// <param name="electricCurrent1">The electricCurrent1.</param>
/// <param name="value">The value.</param>
/// <returns>The result of the operator.</returns>
public static ElectricCurrent operator *(ElectricCurrent electricCurrent1, double value)
{
return new ElectricCurrent(electricCurrent1.UnitValue * value);
}
#endregion
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="string" /> that represents this instance.</returns>
public override string ToString()
{
return ToString(ElectricCurrentUnit.Ampere, CultureInfo.InvariantCulture, DefaultStringFormat);
}
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <param name="unit">The unit.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="format">The format.</param>
/// <returns>A <see cref="string" /> that represents this instance.</returns>
/// <exception cref="NotImplementedException"></exception>
public override string ToString(ElectricCurrentUnit unit, IFormatProvider formatProvider, string format)
{
var value = UnitValue;
return string.Format(formatProvider, format, value, "A");
}
}
}
| 39.730769 | 116 | 0.607212 | [
"MIT"
] | bromnl/Units | sources/Units/ElectricCurrent.cs | 4,134 | C# |
using CssUI.CSS.Parser;
using CssUI.DOM;
using CssUI.DOM.Nodes;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace CssUI.CSS.Selectors
{
public class CssPseudoElementSelectorFunction : PseudoElementSelector
{
protected readonly List<CssToken> Args;
public CssPseudoElementSelectorFunction(string Name, List<CssToken> Args = null) : base(Name)
{
this.Args = Args;
}
/// <summary>
/// Returns whether the selector matches a specified element or index
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
override public bool Matches(Element E, params Node[] scopeElements)
{
switch (Name)
{
default:
throw new NotImplementedException($"Selector pseudo-element function ({Name}) logic not implemented!");
}
}
}
static class PseudoElementFunctions
{
}
}
| 27.297297 | 123 | 0.632673 | [
"MIT"
] | dsisco11/CssUI | CssUI/CSS/Selector/Types/PseudoElementSelectorFunctions.cs | 1,012 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float MovementSpeed = 5;
public float JumpSpeed = 5;
public float TurnSpeed = 5;
public float SneakMultiplier = 0.3f;
private int groundCount;
private int iceCount;
private new Rigidbody rigidbody;
private new Transform camera;
private Animator animator;
private Vector3 lastMovementDirection;
public bool OnGround { get { return groundCount > 0 || OnIce; } }
//public bool OnGround { get { return true; } }
public bool OnIce { get { return iceCount > 0; } }
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
camera = GameObject.FindGameObjectWithTag("MainCamera").transform;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
float horizontalAxis = Input.GetAxis("Horizontal");
float verticalAxis = Input.GetAxis("Vertical");
Vector3 forward = Vector3.ProjectOnPlane(camera.forward, transform.up).normalized;
Vector3 right = Vector3.ProjectOnPlane(camera.right, transform.up).normalized;
animator.SetFloat("Turn", TurnSpeed * Time.deltaTime, 0.1f, Time.deltaTime);
transform.forward = Vector3.RotateTowards(transform.forward, forward, TurnSpeed * Time.deltaTime, 0);
Vector3 direction = right * horizontalAxis + forward * verticalAxis;
direction.Normalize();
animator.SetFloat("Forward", verticalAxis, 0.1f, Time.deltaTime);
bool sneak = Input.GetButton("Sneak");
animator.SetBool("Crouch", sneak);
if (OnIce)
{
Vector3 movementDelta = MovementSpeed * Time.deltaTime * lastMovementDirection;
rigidbody.MovePosition(transform.position + movementDelta);
}
else
if (direction.sqrMagnitude > Mathf.Epsilon)
{
Vector3 movementDelta = MovementSpeed * Time.deltaTime * direction;
if (sneak)
{
rigidbody.MovePosition(transform.position + movementDelta * SneakMultiplier);
}
else
{
rigidbody.MovePosition(transform.position + movementDelta);
}
lastMovementDirection = direction;
}
bool jump = Input.GetButtonDown("Jump");
if (jump && OnGround)
{
rigidbody.velocity += transform.up * JumpSpeed;
}
}
public void UpdateGround()
{
animator.SetBool("OnGround", OnGround);
if (!OnGround)
{
animator.SetFloat("Jump", rigidbody.velocity.y);
}
}
public void AddIce()
{
++iceCount;
UpdateGround();
}
public void RemoveIce()
{
--iceCount;
UpdateGround();
}
public void AddGround()
{
++groundCount;
UpdateGround();
}
public void RemoveGround()
{
--groundCount;
UpdateGround();
}
}
| 27.45614 | 109 | 0.608946 | [
"MIT"
] | jschwarzwalder/OnlyOneCoin | Assets/Scripts/PlayerMovement.cs | 3,132 | C# |
using System.ComponentModel.Composition;
using System.Waf.Applications.Services;
namespace System.Waf.Presentation.Services
{
/// <summary>Service that is responsible to load and save user settings.</summary>
[Export(typeof(ISettingsService)), Export]
public sealed class SettingsService : SettingsServiceCore
{
}
}
| 28.166667 | 86 | 0.757396 | [
"MIT"
] | DotNetUz/waf | src/System.Waf/System.Waf/System.Waf.Wpf/Presentation/Services/SettingsService.cs | 340 | 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 Azure.Analytics.Synapse.Artifacts.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.Synapse.Models
{
public class PSNotebookKernelSpec
{
public PSNotebookKernelSpec(NotebookKernelSpec notebookKernelSpec)
{
this.Name = notebookKernelSpec?.Name;
this.DisplayName = notebookKernelSpec?.DisplayName;
this.AdditionalProperties = notebookKernelSpec?.AdditionalProperties;
}
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "display_name")]
public string DisplayName { get; set; }
[JsonExtensionData]
public IDictionary<string, object> AdditionalProperties { get; set; }
}
}
| 39.875 | 87 | 0.623197 | [
"MIT"
] | Agazoth/azure-powershell | src/Synapse/Synapse/Models/DataPlaneModels/Artifact/Notebooks/PSNotebookKernelSpec.cs | 1,558 | C# |
using System;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace UnitTests.Internal
{
public sealed class RequestScopedServiceProviderTests
{
[Fact]
public void When_http_context_is_unavailable_it_must_fail()
{
// Arrange
Type serviceType = typeof(IIdentifiable<Model>);
var provider = new RequestScopedServiceProvider(new HttpContextAccessor());
// Act
Action action = () => provider.GetRequiredService(serviceType);
// Assert
var exception = Assert.Throws<InvalidOperationException>(action);
Assert.StartsWith($"Cannot resolve scoped service '{serviceType.FullName}' outside the context of an HTTP request.", exception.Message);
}
[UsedImplicitly(ImplicitUseTargetFlags.Itself)]
private sealed class Model : Identifiable
{
}
}
}
| 29.583333 | 148 | 0.682629 | [
"MIT"
] | json-api-dotnet/JsonApiDotNetCore | test/UnitTests/Internal/RequestScopedServiceProviderTests.cs | 1,065 | C# |
using Rg.Plugins.Popup.Contracts;
using Rg.Plugins.Popup.Events;
using Rg.Plugins.Popup.Pages;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Bit.Client.Xamarin.Controls.Implementations
{
public class BitPopupNavigation : IPopupNavigation
{
public IPopupNavigation OriginalImplementation { get; set; } = default!;
public IReadOnlyList<PopupPage> PopupStack => OriginalImplementation.PopupStack;
public event EventHandler<PopupNavigationEventArgs> Pushing
{
add => OriginalImplementation.Pushing += value;
remove => OriginalImplementation.Pushing -= value;
}
public event EventHandler<PopupNavigationEventArgs> Pushed
{
add => OriginalImplementation.Pushed += value;
remove => OriginalImplementation.Pushed -= value;
}
public event EventHandler<PopupNavigationEventArgs> Popping
{
add => OriginalImplementation.Popping += value;
remove => OriginalImplementation.Popping -= value;
}
public event EventHandler<PopupNavigationEventArgs> Popped
{
add => OriginalImplementation.Popped += value;
remove => OriginalImplementation.Popped -= value;
}
public async Task PopAllAsync(bool animate = true)
{
try
{
await OriginalImplementation.PopAllAsync(animate);
}
catch (IndexOutOfRangeException exp) when (exp.Message == "No Page in PopupStack")
{
}
}
public async Task PopAsync(bool animate = true)
{
try
{
await OriginalImplementation.PopAsync(animate);
}
catch (IndexOutOfRangeException exp) when (exp.Message == "No Page in PopupStack")
{
}
}
public async Task PushAsync(PopupPage page, bool animate = true)
{
await OriginalImplementation.PushAsync(page, animate);
}
public async Task RemovePageAsync(PopupPage page, bool animate = true)
{
await OriginalImplementation.RemovePageAsync(page, animate);
}
}
}
| 30.28 | 94 | 0.612065 | [
"MIT"
] | ShahryarSaljoughi/bitframework | src/Client/Xamarin/Bit.Client.Xamarin.Controls/Implementations/BitPopupNavigation.cs | 2,273 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.ElasticSearch.Inputs
{
public sealed class DomainAutoTuneOptionsMaintenanceScheduleDurationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The unit of time specifying the duration of an Auto-Tune maintenance window. Valid values: `HOURS`.
/// </summary>
[Input("unit", required: true)]
public Input<string> Unit { get; set; } = null!;
/// <summary>
/// An integer specifying the value of the duration of an Auto-Tune maintenance window.
/// </summary>
[Input("value", required: true)]
public Input<int> Value { get; set; } = null!;
public DomainAutoTuneOptionsMaintenanceScheduleDurationArgs()
{
}
}
}
| 33 | 111 | 0.660985 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/ElasticSearch/Inputs/DomainAutoTuneOptionsMaintenanceScheduleDurationArgs.cs | 1,056 | 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-11-06.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CloudFront.Model
{
///<summary>
/// CloudFront exception
/// </summary>
public class NoSuchStreamingDistributionException : AmazonCloudFrontException
{
/// <summary>
/// Constructs a new NoSuchStreamingDistributionException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public NoSuchStreamingDistributionException(string message)
: base(message) {}
/// <summary>
/// Construct instance of NoSuchStreamingDistributionException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public NoSuchStreamingDistributionException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of NoSuchStreamingDistributionException
/// </summary>
/// <param name="innerException"></param>
public NoSuchStreamingDistributionException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of NoSuchStreamingDistributionException
/// </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 NoSuchStreamingDistributionException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of NoSuchStreamingDistributionException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NoSuchStreamingDistributionException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
}
} | 40.734177 | 178 | 0.646675 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/NoSuchStreamingDistributionException.cs | 3,218 | 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextDiffing
{
[ExportWorkspaceService(typeof(IDocumentTextDifferencingService), ServiceLayer.Host), Shared]
internal class EditorTextDifferencingService : IDocumentTextDifferencingService
{
private readonly ITextBufferFactoryService _textBufferFactoryService;
private readonly ITextDifferencingSelectorService _differenceSelectorService;
[ImportingConstructor]
public EditorTextDifferencingService(ITextBufferFactoryService textBufferFactoryService, ITextDifferencingSelectorService differenceSelectorService)
{
_textBufferFactoryService = textBufferFactoryService;
_differenceSelectorService = differenceSelectorService;
}
public async Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken)
{
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var diffService = _differenceSelectorService.GetTextDifferencingService(oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType())
?? _differenceSelectorService.DefaultTextDifferencingService;
var differenceOptions = new StringDifferenceOptions()
{
DifferenceType = StringDifferenceTypes.Word
};
var oldTextSnapshot = oldText.FindCorrespondingEditorTextSnapshot();
var newTextSnapshot = newText.FindCorrespondingEditorTextSnapshot();
var useSnapshots = oldTextSnapshot != null && newTextSnapshot != null;
var diffResult = useSnapshots
? diffService.DiffSnapshotSpans(oldTextSnapshot.GetFullSpan(), newTextSnapshot.GetFullSpan(), differenceOptions)
: diffService.DiffStrings(oldText.ToString(), newText.ToString(), differenceOptions);
return diffResult.Differences.Select(d =>
new TextChange(
diffResult.LeftDecomposition.GetSpanInOriginal(d.Left).ToTextSpan(),
newText.GetSubText(diffResult.RightDecomposition.GetSpanInOriginal(d.Right).ToTextSpan()).ToString())).ToImmutableArray();
}
}
}
| 51.241379 | 187 | 0.750673 | [
"Apache-2.0"
] | AdamSpeight2008/roslyn-1 | src/EditorFeatures/Core/Implementation/TextDiffing/EditorTextDifferencingService.cs | 2,974 | C# |
namespace WebApi
{
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NSwag;
using NSwag.Generation.Processors.Security;
using Services;
using Filters;
using Infrastructure;
using Application.Common.Interfaces;
using Application;
using Infrastructure.Persistence;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
//public IWebHostEnvironment Environment { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication();
services.AddInfrastructure(Configuration);//, Environment);
services.AddScoped<ICurrentUserService, CurrentUserService>();
services.AddHttpContextAccessor();
services.AddHealthChecks()
.AddDbContextCheck<ApplicationDbContext>();
services.AddControllers(options => options.Filters.Add(new ApiExceptionFilter()));
// Customise default API behaviour
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddOpenApiDocument(configure =>
{
configure.Title = "CleanArchitecture API";
configure.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Type into the textbox: Bearer {your JWT token}."
});
configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHealthChecks("/health");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseOpenApi();
app.UseSwaggerUi3(settings =>
{
settings.Path = "/api";
settings.DocumentPath = "/api/specification.json";
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.509091 | 143 | 0.579791 | [
"MIT"
] | ahmetsaiderdem/CleanArchitecture | src/Apps/WebApi/Startup.cs | 3,246 | 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.MarkdownLite
{
using System.Text.RegularExpressions;
public class GfmEmInlineRule : MarkdownEmInlineRule
{
public override string Name => "Inline.Gfm.Em";
public override Regex Em => Regexes.Inline.Gfm.Em;
}
}
| 29.4 | 102 | 0.70068 | [
"MIT"
] | 928PJY/docfx | src/Microsoft.DocAsCode.MarkdownLite/Gfm/GfmEmInlineRule.cs | 429 | C# |
#region License, Terms and Conditions
//
// Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
// Written by Atif Aziz (atif.aziz@skybow.com)
// Copyright (c) 2005 Atif Aziz. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// 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 Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace EZOper.NetSiteUtilities.Jayrock
{
#region Imports
using System;
#endregion
public abstract class ExporterBase : IExporter
{
private readonly Type _inputType;
protected ExporterBase(Type inputType)
{
if (inputType == null)
throw new ArgumentNullException("inputType");
_inputType = inputType;
}
public Type InputType
{
get { return _inputType; }
}
public virtual void Export(ExportContext context, object value, JsonWriter writer)
{
if (context == null)
throw new ArgumentNullException("context");
if (writer == null)
throw new ArgumentNullException("writer");
if (JsonNull.LogicallyEquals(value))
writer.WriteNull();
else
ExportValue(context, value, writer);
}
protected abstract void ExportValue(ExportContext context, object value, JsonWriter writer);
}
} | 31.875 | 100 | 0.651471 | [
"MIT"
] | erikzhouxin/CSharpSolution | NetSiteUtilities/Jayrock/Json/Json/Conversion/Converters/ExporterBase.cs | 2,040 | C# |
// Copyright (c) All contributors. All rights reserved. Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tinyhand;
using Xunit;
namespace Tinyhand.Tests
{
public enum MyEnum { One, Two, Three }
[TinyhandObject]
public partial class EnumTestClass
{
[Key(1)]
public MyEnum Item1 { get; set; }
[Key(2)]
public MyEnum Item2 { get; set; }
[Key(3)]
public MyEnum Item3 { get; set; }
}
public class EnumTest
{
[Fact]
public void MultipleEnumTest()
{
var t = new EnumTestClass();
t.Item2 = MyEnum.Two;
t.Item3 = MyEnum.Three;
var t2 = TestHelper.Convert(t);
t2.IsStructuralEqual(t);
}
}
}
| 21.097561 | 88 | 0.583815 | [
"BSD-2-Clause",
"MIT"
] | archi-Doc/Tinyhand | XUnitTest/Tests/EnumTest.cs | 867 | C# |
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace QueryEncapsulation.Web
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
EFConfig.Initialize();
SeedData.Init();
}
}
}
| 21.944444 | 59 | 0.64557 | [
"Apache-2.0"
] | MattHoneycutt/asp.net-samples | QueryEncapsulation/QueryEncapsulation.Web/Global.asax.cs | 397 | C# |
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2019 Narvalo.Org. All rights reserved.
namespace Abc.Linq.Linq
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
// Apply standard LINQ ops to an inner enumerable.
// Maybe not a good idea. For instance Select() will be very confusing (to
// say the least): is it the one from Maybe<T> or the LINQ op defined here?
// Of course, it is OK when the signatures differ which is for instance the
// case w/ SelectMany().
public static partial class MaybeEnumerable { }
public partial class MaybeEnumerable
{
[Pure]
[RejectedApi]
public static Maybe<IEnumerable<TResult>> Select<T, TResult>(
this Maybe<IEnumerable<T>> source,
Func<T, TResult> selector)
{
return source.Select(seq => seq.Select(selector));
}
[Pure]
[RejectedApi]
public static Maybe<IEnumerable<T>> Where<T>(
this Maybe<IEnumerable<T>> source,
Func<T, bool> predicate)
{
return source.Select(seq => seq.Where(predicate));
}
[Pure]
[RejectedApi]
public static Maybe<IEnumerable<TResult>> SelectMany<T, TMiddle, TResult>(
this Maybe<IEnumerable<T>> source,
Func<T, IEnumerable<TMiddle>> selector,
Func<T, TMiddle, TResult> resultSelector)
{
return source.Select(seq => seq.SelectMany(selector, resultSelector));
}
}
}
| 32.408163 | 82 | 0.61335 | [
"BSD-3-Clause"
] | chtoucas/Abc.Maybe | src/Abc.Sketches/Linq/Linq/MaybeEnumerable.cs | 1,590 | C# |
using Braintree.Exceptions;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Braintree.Tests.Integration
{
[TestFixture]
public class AddressIntegrationTest
{
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
}
[Test]
public void Create_CreatesAddressForGivenCustomerId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840",
CountryName = "United States of America"
};
Address address = gateway.Address.Create(customer.Id, addressRequest).Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
Assert.AreEqual("United States of America", address.CountryName);
Assert.IsNotNull(address.CreatedAt);
Assert.IsNotNull(address.UpdatedAt);
}
[Test]
#if netcore
public async Task CreateAsync_CreatesAddressForGivenCustomerId()
#else
public void CreateAsync_CreatesAddressForGivenCustomerId()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840",
CountryName = "United States of America"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address address = addressResult.Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
Assert.AreEqual("United States of America", address.CountryName);
Assert.IsNotNull(address.CreatedAt);
Assert.IsNotNull(address.UpdatedAt);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Find_FindsAddress()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
};
Address createdAddress = gateway.Address.Create(customer.Id, addressRequest).Target;
Address address = gateway.Address.Find(customer.Id, createdAddress.Id);
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
}
[Test]
#if netcore
public async Task FindAsync_FindsAddress()
#else
public void FindAsync_FindsAddress()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address createdAddress = addressResult.Target;
Address address = await gateway.Address.FindAsync(customer.Id, createdAddress.Id);
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Update_UpdatesAddressForGivenCustomerIdAndAddressId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Address originalAddress = gateway.Address.Create(customer.Id, addressCreateRequest).Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840"
};
Address address = gateway.Address.Update(customer.Id, originalAddress.Id, addressUpdateRequest).Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
}
[Test]
#if netcore
public async Task UpdateAsync_UpdatesAddressForGivenCustomerIdAndAddressId()
#else
public void UpdateAsync_UpdatesAddressForGivenCustomerIdAndAddressId()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressCreateRequest);
Address originalAddress = addressResult.Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840"
};
addressResult = await gateway.Address.UpdateAsync(customer.Id, originalAddress.Id, addressUpdateRequest);
Address address = addressResult.Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Update_ReturnsAnErrorResult_ForInconsistenCountry()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Address originalAddress = gateway.Address.Create(customer.Id, addressCreateRequest).Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha3 = "MEX"
};
Result<Address> result = gateway.Address.Update(customer.Id, originalAddress.Id, addressUpdateRequest);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_INCONSISTENT_COUNTRY,
result.Errors.ForObject("Address").OnField("Base")[0].Code
);
}
[Test]
public void Delete_DeletesTheAddress()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
};
Address createdAddress = gateway.Address.Create(customer.Id, addressRequest).Target;
Assert.AreEqual(createdAddress.Id, gateway.Address.Find(customer.Id, createdAddress.Id).Id);
try {
Result<Address> result = gateway.Address.Delete(customer.Id, createdAddress.Id);
Assert.IsTrue(result.IsSuccess());
} catch (NotFoundException) {
Assert.Fail("Unable to delete the created address");
}
Assert.Throws<NotFoundException> (() => gateway.Address.Find(customer.Id, createdAddress.Id));
}
[Test]
#if netcore
public async Task DeleteAsync_DeletesTheAddress()
#else
public void DeleteAsync_DeletesTheAddress()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address createdAddress = addressResult.Target;
Assert.AreEqual(createdAddress.Id, gateway.Address.Find(customer.Id, createdAddress.Id).Id);
try {
Result<Address> result = await gateway.Address.DeleteAsync(customer.Id, createdAddress.Id);
Assert.IsTrue(result.IsSuccess());
} catch (NotFoundException) {
Assert.Fail("Unable to delete the created address");
}
Assert.Throws<NotFoundException> (() => gateway.Address.Find(customer.Id, createdAddress.Id));
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Create_ReturnsAnErrorResult()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest() { CountryName = "United States of Hammer" };
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Dictionary<string, string> parameters = createResult.Parameters;
Assert.AreEqual("integration_merchant_id", parameters["merchant_id"]);
Assert.AreEqual(customer.Id, parameters["customer_id"]);
Assert.AreEqual("United States of Hammer", parameters["address[country_name]"]);
}
[Test]
public void Create_ReturnsAnErrorResult_ForInconsistentCountry()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryName = "United States of America",
CountryCodeAlpha2 = "BZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_INCONSISTENT_COUNTRY,
createResult.Errors.ForObject("Address").OnField("Base")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectAlpha2()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeAlpha2 = "ZZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeAlpha2")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectAlpha3()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeAlpha3 = "ZZZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeAlpha3")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectNumeric()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeNumeric = "000"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeNumeric")[0].Code
);
}
}
}
| 39.558648 | 117 | 0.570057 | [
"MIT"
] | Ethernodes-org/braintree_dotnet | test/Braintree.Tests.Integration/AddressIntegrationTest.cs | 19,898 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using MyNoSqlServer.Abstractions;
using Service.IndexPrices.Client;
using Service.Liquidity.Portfolio.Domain.Models;
using Service.Liquidity.PortfolioHedger.Domain.Models;
namespace Service.Liquidity.PortfolioHedger.Services
{
public class PortfolioHandler
{
private readonly IIndexPricesClient _indexPricesClient;
private const string UsdAssetName = "USD";
private readonly IMyNoSqlServerDataReader<AssetPortfolioBalanceNoSql> _assetPortfolioBalanceDataReader;
public PortfolioHandler(IIndexPricesClient indexPricesClient,
IMyNoSqlServerDataReader<AssetPortfolioBalanceNoSql> assetPortfolioBalanceDataReader)
{
_indexPricesClient = indexPricesClient;
_assetPortfolioBalanceDataReader = assetPortfolioBalanceDataReader;
}
public List<AvailableOppositeAsset> GetAvailableOppositeAssets(AssetPortfolio portfolioSnapshot, string fromAsset, decimal fromVolume)
{
var response = new List<AvailableOppositeAsset>();
if (fromAsset != UsdAssetName)
{
response.Add(new AvailableOppositeAsset()
{
Asset = UsdAssetName,
Order = 999,
Volume = int.MaxValue // todo: вынести в конфиг
});
}
if (portfolioSnapshot == null)
{
return response;
}
if (fromVolume < 0)
{
var orderedPortfolio = portfolioSnapshot.BalanceByAsset
.Where(e => e.Asset != fromAsset && e.UsdVolume < 0)
.OrderBy(e => e.UsdVolume)
.ToList();
for (var index = 0; index < orderedPortfolio.Count; index++)
{
var balanceByAsset = orderedPortfolio[index];
response.Add(new AvailableOppositeAsset()
{
Order = index,
Asset = balanceByAsset.Asset,
Volume = GetOppositeVolume(portfolioSnapshot, fromAsset, balanceByAsset.Asset, fromVolume)
});
}
}
else
{
var orderedPortfolio = portfolioSnapshot.BalanceByAsset
.Where(e => e.Asset != fromAsset && e.UsdVolume > 0)
.OrderBy(e => e.UsdVolume)
.ToList();
for (var index = 0; index < orderedPortfolio.Count; index++)
{
var balanceByAsset = orderedPortfolio[index];
response.Add(new AvailableOppositeAsset()
{
Order = index,
Asset = balanceByAsset.Asset,
Volume = GetOppositeVolume(portfolioSnapshot ,fromAsset, balanceByAsset.Asset, fromVolume)
});
}
}
return response;
}
public AssetPortfolio GetPortfolioSnapshot()
{
var noSqlEntity = _assetPortfolioBalanceDataReader.Get().FirstOrDefault();
if (noSqlEntity == null)
throw new Exception("Asset portfolio not found in NoSql");
return noSqlEntity.Balance;
}
private decimal GetOppositeVolume(AssetPortfolio portfolioSnapshot, string fromAsset, string toAsset,
decimal fromVolume)
{
var fromAssetPrice = _indexPricesClient.GetIndexPriceByAssetAsync(fromAsset);
var toAssetPrice = _indexPricesClient.GetIndexPriceByAssetAsync(toAsset);
var volumeInPortfolio = portfolioSnapshot.BalanceByAsset.FirstOrDefault(e => e.Asset == toAsset)?.Volume ?? 0;
var toVolumeAbs = Math.Abs(fromVolume) * (fromAssetPrice.UsdPrice / toAssetPrice.UsdPrice);
var volumeInPortfolioAbs = Math.Abs(volumeInPortfolio);
if (fromVolume > 0)
{
var response = Math.Max(volumeInPortfolio, toVolumeAbs);
return Math.Abs(response);
}
else
{
var response = Math.Min(volumeInPortfolioAbs, toVolumeAbs);
return response;
}
}
public decimal GetRemainder(AssetPortfolio portfolioSnapshot, AssetPortfolio newPortfolio, string fromAsset, decimal fromAssetVolume)
{
var fromAssetBalanceBefore = portfolioSnapshot.BalanceByAsset.FirstOrDefault(e => e.Asset == fromAsset);
var fromAssetBalanceAfter = newPortfolio.BalanceByAsset.FirstOrDefault(e => e.Asset == fromAsset);
var targetBalance = (fromAssetBalanceBefore?.Volume ?? 0) + fromAssetVolume;
var remainder = targetBalance - fromAssetBalanceAfter?.Volume;
return remainder ?? 0;
}
public AnalysisResult GetAnalysisResult(AssetPortfolio requestPortfolioSnapshot)
{
var problemVolume = 10000;
var mostProblemAsset = requestPortfolioSnapshot.BalanceByAsset
.Where(e => Math.Abs(e.UsdVolume) > problemVolume)
.OrderByDescending(e => Math.Abs(e.UsdVolume))
.FirstOrDefault();
return new AnalysisResult()
{
HedgeIsNeeded = mostProblemAsset != null,
FromAsset = mostProblemAsset?.Asset ?? string.Empty,
FromAssetVolume = -(mostProblemAsset?.Volume ?? 0)
};
}
}
} | 40.595745 | 142 | 0.573725 | [
"MIT"
] | MyJetWallet/Service.Liquidity.PortfolioHedger | src/Service.Liquidity.PortfolioHedger/Services/PortfolioHandler.cs | 5,738 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.WhiteSpaces.AdminNotificationSystem
{
using System;
using Microsoft.WhiteSpaces.AdminNotificationSystem;
public interface INotificationClient : IDisposable
{
bool NotifyClient(Notification notification);
}
}
| 25.285714 | 60 | 0.759887 | [
"MIT"
] | richstep/TVWS-DB-Code | src/AdminNotificationSystem/INotificationClient.cs | 354 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.