content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IManagedAppStatusRequestBuilder.
/// </summary>
public partial interface IManagedAppStatusRequestBuilder : IEntityRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IManagedAppStatusRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IManagedAppStatusRequest Request(IEnumerable<Option> options);
}
}
| 35.6 | 153 | 0.576244 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IManagedAppStatusRequestBuilder.cs | 1,246 | C# |
using TraceabilityEngine.Interfaces.Models.Common;
using TraceabilityEngine.StaticData;
using System;
using System.Collections.Generic;
using System.Text;
using TraceabilityEngine.Interfaces.DB.DocumentDB;
namespace TraceabilityEngine.Interfaces.Models.Products
{
public interface ITEProduct : ITEProductLite, ITEDocumentObject
{
ITEProductAllergensAndAdditives AllergensAndAdditives { get; set; }
List<ITEAttachment> Attachments { get; set; }
List<ITEProductAvailability> Availabilities { get; set; }
ITEProductBeverage Beverage { get; set; }
List<ITEProductCase> Cases { get; set; }
List<GS1Category> Categories { get; set; }
string Category { get; set; }
List<ITECertificate> Certificates { get; set; }
List<ITEProductChild> Children { get; set; }
List<ProductClaim> Claims { get; set; }
ITEProductDairy Dairy { get; set; }
ITEProductFruitsAndVegetables FruitsAndVegetables { get; set; }
List<ITEPhoto> Images { get; set; }
ITEProductInfo Info { get; set; }
ITEProductIngredients Ingredients { get; set; }
ITEProductInstructions Instructions { get; set; }
string InternalID { get; set; }
ITEProductMeasurements Measurements { get; set; }
ITEProductMeat Meat { get; set; }
ITEProductNutrition Nutrition { get; set; }
ITEProductPackaging Packaging { get; set; }
ITEProductPreparation Preparation { get; set; }
ProductTypeCode ProductType { get; set; }
ITEProductProvenance Provenance { get; set; }
ITEProductSeafood Seafood { get; set; }
List<Species> Species { get; set; }
List<ITEProductTreatment> Treatments { get; set; }
}
}
| 42.926829 | 75 | 0.676705 | [
"MIT"
] | TraceabilityInternet/TraceabilityDriver | TEInterfaces/Models/Products/ITEProduct.cs | 1,762 | C# |
namespace AngleSharp.Css
{
using System;
/// <summary>
/// The collection of (known / used) property names.
/// </summary>
public static class PropertyNames
{
/// <summary>
/// The align-content declaration.
/// </summary>
public static readonly String AlignContent = "align-content";
/// <summary>
/// The align-items declaration.
/// </summary>
public static readonly String AlignItems = "align-items";
/// <summary>
/// The align-baseline declaration.
/// </summary>
public static readonly String AlignBaseline = "alignment-baseline";
/// <summary>
/// The align-self declaration.
/// </summary>
public static readonly String AlignSelf = "align-self";
/// <summary>
/// The accelerator declaration.
/// </summary>
public static readonly String Accelerator = "accelerator";
/// <summary>
/// The animation declaration.
/// </summary>
public static readonly String Animation = "animation";
/// <summary>
/// The animation-delay declaration.
/// </summary>
public static readonly String AnimationDelay = "animation-delay";
/// <summary>
/// The animation-direction declaration.
/// </summary>
public static readonly String AnimationDirection = "animation-direction";
/// <summary>
/// The animation-duration declaration.
/// </summary>
public static readonly String AnimationDuration = "animation-duration";
/// <summary>
/// The animation-fill-mode declaration.
/// </summary>
public static readonly String AnimationFillMode = "animation-fill-mode";
/// <summary>
/// The animation-iteration-count declaration.
/// </summary>
public static readonly String AnimationIterationCount = "animation-iteration-count";
/// <summary>
/// The animation-name declaration.
/// </summary>
public static readonly String AnimationName = "animation-name";
/// <summary>
/// The animation-play-state declaration.
/// </summary>
public static readonly String AnimationPlayState = "animation-play-state";
/// <summary>
/// The animation-timing-function declaration.
/// </summary>
public static readonly String AnimationTimingFunction = "animation-timing-function";
/// <summary>
/// The background-attachment declaration.
/// </summary>
public static readonly String BackgroundAttachment = "background-attachment";
/// <summary>
/// The background-color declaration.
/// </summary>
public static readonly String BackgroundColor = "background-color";
/// <summary>
/// The background-clip declaration.
/// </summary>
public static readonly String BackgroundClip = "background-clip";
/// <summary>
/// The background-origin declaration.
/// </summary>
public static readonly String BackgroundOrigin = "background-origin";
/// <summary>
/// The background-size declaration.
/// </summary>
public static readonly String BackgroundSize = "background-size";
/// <summary>
/// The background-image declaration.
/// </summary>
public static readonly String BackgroundImage = "background-image";
/// <summary>
/// The background-position declaration.
/// </summary>
public static readonly String BackgroundPosition = "background-position";
/// <summary>
/// The background-position-x declaration.
/// </summary>
public static readonly String BackgroundPositionX = "background-position-x";
/// <summary>
/// The background-position-y declaration.
/// </summary>
public static readonly String BackgroundPositionY = "background-position-y";
/// <summary>
/// The background-repeat declaration.
/// </summary>
public static readonly String BackgroundRepeat = "background-repeat";
/// <summary>
/// The background-repeat-x declaration.
/// </summary>
public static readonly String BackgroundRepeatX = "background-repeat-x";
/// <summary>
/// The background-repeat-y declaration.
/// </summary>
public static readonly String BackgroundRepeatY = "background-repeat-y";
/// <summary>
/// The background declaration.
/// </summary>
public static readonly String Background = "background";
/// <summary>
/// The behavior declaration.
/// </summary>
public static readonly String Behavior = "behavior";
/// <summary>
/// The baseline-shift declaration.
/// </summary>
public static readonly String BaselineShift = "baseline-shift";
/// <summary>
/// The border-color declaration.
/// </summary>
public static readonly String BorderColor = "border-color";
/// <summary>
/// The border-spacing declaration.
/// </summary>
public static readonly String BorderSpacing = "border-spacing";
/// <summary>
/// The border-collapse declaration.
/// </summary>
public static readonly String BorderCollapse = "border-collapse";
/// <summary>
/// The border-style declaration.
/// </summary>
public static readonly String BorderStyle = "border-style";
/// <summary>
/// The border-radius declaration.
/// </summary>
public static readonly String BorderRadius = "border-radius";
/// <summary>
/// The border-top-left-radius declaration.
/// </summary>
public static readonly String BorderTopLeftRadius = "border-top-left-radius";
/// <summary>
/// The border-top-right-radius declaration.
/// </summary>
public static readonly String BorderTopRightRadius = "border-top-right-radius";
/// <summary>
/// The border-bottom-left-radius declaration.
/// </summary>
public static readonly String BorderBottomLeftRadius = "border-bottom-left-radius";
/// <summary>
/// The border-bottom-right-radius declaration.
/// </summary>
public static readonly String BorderBottomRightRadius = "border-bottom-right-radius";
/// <summary>
/// The box-shadow declaration.
/// </summary>
public static readonly String BoxShadow = "box-shadow";
/// <summary>
/// The box-sizing declaration.
/// </summary>
public static readonly String BoxSizing = "box-sizing";
/// <summary>
/// The box-decoration-break declaration.
/// </summary>
public static readonly String BoxDecorationBreak = "box-decoration-break";
/// <summary>
/// The break-after declaration.
/// </summary>
public static readonly String BreakAfter = "break-after";
/// <summary>
/// The break-before declaration.
/// </summary>
public static readonly String BreakBefore = "break-before";
/// <summary>
/// The break-inside declaration.
/// </summary>
public static readonly String BreakInside = "break-inside";
/// <summary>
/// The backface-visibility declaration.
/// </summary>
public static readonly String BackfaceVisibility = "backface-visibility";
/// <summary>
/// The border-image declaration.
/// </summary>
public static readonly String BorderImage = "border-image";
/// <summary>
/// The border-image-outset declaration.
/// </summary>
public static readonly String BorderImageOutset = "border-image-outset";
/// <summary>
/// The border-image-repeat declaration.
/// </summary>
public static readonly String BorderImageRepeat = "border-image-repeat";
/// <summary>
/// The border-image-source declaration.
/// </summary>
public static readonly String BorderImageSource = "border-image-source";
/// <summary>
/// The border-image-slice declaration.
/// </summary>
public static readonly String BorderImageSlice = "border-image-slice";
/// <summary>
/// The border-image-width declaration.
/// </summary>
public static readonly String BorderImageWidth = "border-image-width";
/// <summary>
/// The border-top declaration.
/// </summary>
public static readonly String BorderTop = "border-top";
/// <summary>
/// The border-right declaration.
/// </summary>
public static readonly String BorderRight = "border-right";
/// <summary>
/// The border-bottom declaration.
/// </summary>
public static readonly String BorderBottom = "border-bottom";
/// <summary>
/// The border-left declaration.
/// </summary>
public static readonly String BorderLeft = "border-left";
/// <summary>
/// The border-top-color declaration.
/// </summary>
public static readonly String BorderTopColor = "border-top-color";
/// <summary>
/// The border-left-color declaration.
/// </summary>
public static readonly String BorderLeftColor = "border-left-color";
/// <summary>
/// The border-right-color declaration.
/// </summary>
public static readonly String BorderRightColor = "border-right-color";
/// <summary>
/// The border-bottom-color declaration.
/// </summary>
public static readonly String BorderBottomColor = "border-bottom-color";
/// <summary>
/// The border-top-style declaration.
/// </summary>
public static readonly String BorderTopStyle = "border-top-style";
/// <summary>
/// The border-left-style declaration.
/// </summary>
public static readonly String BorderLeftStyle = "border-left-style";
/// <summary>
/// The border-right-style declaration.
/// </summary>
public static readonly String BorderRightStyle = "border-right-style";
/// <summary>
/// The border-bottom-style declaration.
/// </summary>
public static readonly String BorderBottomStyle = "border-bottom-style";
/// <summary>
/// The border-top-width declaration.
/// </summary>
public static readonly String BorderTopWidth = "border-top-width";
/// <summary>
/// The border-left-width declaration.
/// </summary>
public static readonly String BorderLeftWidth = "border-left-width";
/// <summary>
/// The border-right-width declaration.
/// </summary>
public static readonly String BorderRightWidth = "border-right-width";
/// <summary>
/// The border-bottom-width declaration.
/// </summary>
public static readonly String BorderBottomWidth = "border-bottom-width";
/// <summary>
/// The border-width declaration.
/// </summary>
public static readonly String BorderWidth = "border-width";
/// <summary>
/// The border declaration.
/// </summary>
public static readonly String Border = "border";
/// <summary>
/// The bottom declaration.
/// </summary>
public static readonly String Bottom = "bottom";
/// <summary>
/// The columns declaration.
/// </summary>
public static readonly String Columns = "columns";
/// <summary>
/// The column-count declaration.
/// </summary>
public static readonly String ColumnCount = "column-count";
/// <summary>
/// The column-fill declaration.
/// </summary>
public static readonly String ColumnFill = "column-fill";
/// <summary>
/// The column-rule declaration.
/// </summary>
public static readonly String ColumnRule = "column-rule";
/// <summary>
/// The column-rule-color declaration.
/// </summary>
public static readonly String ColumnRuleColor = "column-rule-color";
/// <summary>
/// The column-rule-style declaration.
/// </summary>
public static readonly String ColumnRuleStyle = "column-rule-style";
/// <summary>
/// The column-rule-width declaration.
/// </summary>
public static readonly String ColumnRuleWidth = "column-rule-width";
/// <summary>
/// The column-span declaration.
/// </summary>
public static readonly String ColumnSpan = "column-span";
/// <summary>
/// The column-width declaration.
/// </summary>
public static readonly String ColumnWidth = "column-width";
/// <summary>
/// The column-gap declaration.
/// </summary>
public static readonly String ColumnGap = "column-gap";
/// <summary>
/// The grid-row-gap declaration.
/// </summary>
public static readonly String RowGap = "row-gap";
/// <summary>
/// The gap declaration.
/// </summary>
public static readonly String Gap = "gap";
/// <summary>
/// The caption-side declaration.
/// </summary>
public static readonly String CaptionSide = "caption-side";
/// <summary>
/// The clear declaration.
/// </summary>
public static readonly String Clear = "clear";
/// <summary>
/// The clip declaration.
/// </summary>
public static readonly String Clip = "clip";
/// <summary>
/// The clip-left declaration.
/// </summary>
public static readonly String ClipLeft = "clip-left";
/// <summary>
/// The clip-top declaration.
/// </summary>
public static readonly String ClipTop = "clip-top";
/// <summary>
/// The clip-right declaration.
/// </summary>
public static readonly String ClipRight = "clip-right";
/// <summary>
/// The clip-bottom declaration.
/// </summary>
public static readonly String ClipBottom = "clip-bottom";
/// <summary>
/// The clip-path declaration.
/// </summary>
public static readonly String ClipPath = "clip-path";
/// <summary>
/// The clip-rule declaration.
/// </summary>
public static readonly String ClipRule = "clip-rule";
/// <summary>
/// The color declaration.
/// </summary>
public static readonly String Color = "color";
/// <summary>
/// The color-interpolation-filters declaration.
/// </summary>
public static readonly String ColorInterpolationFilters = "color-interpolation-filters";
/// <summary>
/// The content declaration.
/// </summary>
public static readonly String Content = "content";
/// <summary>
/// The content-visibility declaration.
/// </summary>
public static readonly String ContentVisibility = "content-visibility";
/// <summary>
/// The counter-increment declaration.
/// </summary>
public static readonly String CounterIncrement = "counter-increment";
/// <summary>
/// The counter-reset declaration.
/// </summary>
public static readonly String CounterReset = "counter-reset";
/// <summary>
/// The cursor declaration.
/// </summary>
public static readonly String Cursor = "cursor";
/// <summary>
/// The direction declaration.
/// </summary>
public static readonly String Direction = "direction";
/// <summary>
/// The display declaration.
/// </summary>
public static readonly String Display = "display";
/// <summary>
/// The dominant-baseline declaration.
/// </summary>
public static readonly String DominantBaseline = "dominant-baseline";
/// <summary>
/// The empty-cells declaration.
/// </summary>
public static readonly String EmptyCells = "empty-cells";
/// <summary>
/// The enable-background declaration.
/// </summary>
public static readonly String EnableBackground = "enable-background";
/// <summary>
/// The fill declaration.
/// </summary>
public static readonly String Fill = "fill";
/// <summary>
/// The fill-opacity declaration.
/// </summary>
public static readonly String FillOpacity = "fill-opacity";
/// <summary>
/// The fill-rule declaration.
/// </summary>
public static readonly String FillRule = "fill-rule";
/// <summary>
/// The filter declaration.
/// </summary>
public static readonly String Filter = "filter";
/// <summary>
/// The flex declaration.
/// </summary>
public static readonly String Flex = "flex";
/// <summary>
/// The flex-basis declaration.
/// </summary>
public static readonly String FlexBasis = "flex-basis";
/// <summary>
/// The flex-direction declaration.
/// </summary>
public static readonly String FlexDirection = "flex-direction";
/// <summary>
/// The flex-flow declaration.
/// </summary>
public static readonly String FlexFlow = "flex-flow";
/// <summary>
/// The flex-grow declaration.
/// </summary>
public static readonly String FlexGrow = "flex-grow";
/// <summary>
/// The flex-shrink declaration.
/// </summary>
public static readonly String FlexShrink = "flex-shrink";
/// <summary>
/// The flex-wrap declaration.
/// </summary>
public static readonly String FlexWrap = "flex-wrap";
/// <summary>
/// The float declaration.
/// </summary>
public static readonly String Float = "float";
/// <summary>
/// The font-family declaration.
/// </summary>
public static readonly String FontFamily = "font-family";
/// <summary>
/// The font-feature-settings declaration.
/// </summary>
public static readonly String FontFeatureSettings = "font-feature-settings";
/// <summary>
/// The font-size declaration.
/// </summary>
public static readonly String FontSize = "font-size";
/// <summary>
/// The font-size-adjust declaration.
/// </summary>
public static readonly String FontSizeAdjust = "font-size-adjust";
/// <summary>
/// The font-style declaration.
/// </summary>
public static readonly String FontStyle = "font-style";
/// <summary>
/// The font-stretch declaration.
/// </summary>
public static readonly String FontStretch = "font-stretch";
/// <summary>
/// The font-variant declaration.
/// </summary>
public static readonly String FontVariant = "font-variant";
/// <summary>
/// The font-weight declaration.
/// </summary>
public static readonly String FontWeight = "font-weight";
/// <summary>
/// The font declaration.
/// </summary>
public static readonly String Font = "font";
/// <summary>
/// The glyph-orientation-horizontal declaration.
/// </summary>
public static readonly String GlyphOrientationHorizontal = "glyph-orientation-horizontal";
/// <summary>
/// The glyph-orientation-vertical declaration.
/// </summary>
public static readonly String GlyphOrientationVertical = "glyph-orientation-vertical";
/// <summary>
/// The height declaration.
/// </summary>
public static readonly String Height = "height";
/// <summary>
/// The ime-mode declaration.
/// </summary>
public static readonly String ImeMode = "ime-mode";
/// <summary>
/// The justify-content declaration.
/// </summary>
public static readonly String JustifyContent = "justify-content";
/// <summary>
/// The layout-grid declaration.
/// </summary>
public static readonly String LayoutGrid = "layout-grid";
/// <summary>
/// The layout-grid-char declaration.
/// </summary>
public static readonly String LayoutGridChar = "layout-grid-char";
/// <summary>
/// The layout-grid-type declaration.
/// </summary>
public static readonly String LayoutGridType = "layout-grid-type";
/// <summary>
/// The layout-grid-mode declaration.
/// </summary>
public static readonly String LayoutGridMode = "layout-grid-mode";
/// <summary>
/// The layout-grid-line declaration.
/// </summary>
public static readonly String LayoutGridLine = "layout-grid-line";
/// <summary>
/// The grid-template-rows declaration.
/// </summary>
public static readonly String GridTemplateRows = "grid-template-rows";
/// <summary>
/// The grid-template-columns declaration.
/// </summary>
public static readonly String GridTemplateColumns = "grid-template-columns";
/// <summary>
/// The grid-template-areas declaration.
/// </summary>
public static readonly String GridTemplateAreas = "grid-template-areas";
/// <summary>
/// The grid-template declaration.
/// </summary>
public static readonly String GridTemplate = "grid-template";
/// <summary>
/// The grid-auto-columns declaration.
/// </summary>
public static readonly String GridAutoColumns = "grid-auto-columns";
/// <summary>
/// The grid-auto-rows declaration.
/// </summary>
public static readonly String GridAutoRows = "grid-auto-rows";
/// <summary>
/// The grid-auto-flow declaration.
/// </summary>
public static readonly String GridAutoFlow = "grid-auto-flow";
/// <summary>
/// The grid declaration.
/// </summary>
public static readonly String Grid = "grid";
/// <summary>
/// The grid-row-start declaration.
/// </summary>
public static readonly String GridRowStart = "grid-row-start";
/// <summary>
/// The grid-column-start declaration.
/// </summary>
public static readonly String GridColumnStart = "grid-column-start";
/// <summary>
/// The grid-row-end declaration.
/// </summary>
public static readonly String GridRowEnd = "grid-row-end";
/// <summary>
/// The grid-column-end declaration.
/// </summary>
public static readonly String GridColumnEnd = "grid-column-end";
/// <summary>
/// The grid-row declaration.
/// </summary>
public static readonly String GridRow = "grid-row";
/// <summary>
/// The grid-column declaration.
/// </summary>
public static readonly String GridColumn = "grid-column";
/// <summary>
/// The grid-area declaration.
/// </summary>
public static readonly String GridArea = "grid-area";
/// <summary>
/// The grid-row-gap declaration.
/// </summary>
public static readonly String GridRowGap = "grid-row-gap";
/// <summary>
/// The grid-column-gap declaration.
/// </summary>
public static readonly String GridColumnGap = "grid-column-gap";
/// <summary>
/// The grid-gap declaration.
/// </summary>
public static readonly String GridGap = "grid-gap";
/// <summary>
/// The left declaration.
/// </summary>
public static readonly String Left = "left";
/// <summary>
/// The letter-spacing declaration.
/// </summary>
public static readonly String LetterSpacing = "letter-spacing";
/// <summary>
/// The line-height declaration.
/// </summary>
public static readonly String LineHeight = "line-height";
/// <summary>
/// The list-style-image declaration.
/// </summary>
public static readonly String ListStyleImage = "list-style-image";
/// <summary>
/// The list-style-position declaration.
/// </summary>
public static readonly String ListStylePosition = "list-style-position";
/// <summary>
/// The list-style-type declaration.
/// </summary>
public static readonly String ListStyleType = "list-style-type";
/// <summary>
/// The list-style declaration.
/// </summary>
public static readonly String ListStyle = "list-style";
/// <summary>
/// The margin-right declaration.
/// </summary>
public static readonly String MarginRight = "margin-right";
/// <summary>
/// The margin-left declaration.
/// </summary>
public static readonly String MarginLeft = "margin-left";
/// <summary>
/// The margin-top declaration.
/// </summary>
public static readonly String MarginTop = "margin-top";
/// <summary>
/// The margin-bottom declaration.
/// </summary>
public static readonly String MarginBottom = "margin-bottom";
/// <summary>
/// The margin declaration.
/// </summary>
public static readonly String Margin = "margin";
/// <summary>
/// The marker declaration.
/// </summary>
public static readonly String Marker = "marker";
/// <summary>
/// The marker-end declaration.
/// </summary>
public static readonly String MarkerEnd = "marker-end";
/// <summary>
/// The marker-mid declaration.
/// </summary>
public static readonly String MarkerMid = "marker-mid";
/// <summary>
/// The marker-start declaration.
/// </summary>
public static readonly String MarkerStart = "marker-start";
/// <summary>
/// The mask declaration.
/// </summary>
public static readonly String Mask = "mask";
/// <summary>
/// The max-height declaration.
/// </summary>
public static readonly String MaxHeight = "max-height";
/// <summary>
/// The max-width declaration.
/// </summary>
public static readonly String MaxWidth = "max-width";
/// <summary>
/// The min-height declaration.
/// </summary>
public static readonly String MinHeight = "min-height";
/// <summary>
/// The min-width declaration.
/// </summary>
public static readonly String MinWidth = "min-width";
/// <summary>
/// The opacity declaration.
/// </summary>
public static readonly String Opacity = "opacity";
/// <summary>
/// The order declaration.
/// </summary>
public static readonly String Order = "order";
/// <summary>
/// The orphans declaration.
/// </summary>
public static readonly String Orphans = "orphans";
/// <summary>
/// The outline-color declaration.
/// </summary>
public static readonly String OutlineColor = "outline-color";
/// <summary>
/// The outline-style declaration.
/// </summary>
public static readonly String OutlineStyle = "outline-style";
/// <summary>
/// The outline-width declaration.
/// </summary>
public static readonly String OutlineWidth = "outline-width";
/// <summary>
/// The outline declaration.
/// </summary>
public static readonly String Outline = "outline";
/// <summary>
/// The overflow declaration.
/// </summary>
public static readonly String Overflow = "overflow";
/// <summary>
/// The overflow-x declaration.
/// </summary>
public static readonly String OverflowX = "overflow-x";
/// <summary>
/// The overflow-y declaration.
/// </summary>
public static readonly String OverflowY = "overflow-y";
/// <summary>
/// The overflow-wrap declaration.
/// </summary>
public static readonly String OverflowWrap = "overflow-wrap";
/// <summary>
/// The padding-top declaration.
/// </summary>
public static readonly String PaddingTop = "padding-top";
/// <summary>
/// The padding-right declaration.
/// </summary>
public static readonly String PaddingRight = "padding-right";
/// <summary>
/// The padding-left declaration.
/// </summary>
public static readonly String PaddingLeft = "padding-left";
/// <summary>
/// The padding-bottom declaration.
/// </summary>
public static readonly String PaddingBottom = "padding-bottom";
/// <summary>
/// The padding declaration.
/// </summary>
public static readonly String Padding = "padding";
/// <summary>
/// The page-break-after declaration.
/// </summary>
public static readonly String PageBreakAfter = "page-break-after";
/// <summary>
/// The page-break-before declaration.
/// </summary>
public static readonly String PageBreakBefore = "page-break-before";
/// <summary>
/// The page-break-inside declaration.
/// </summary>
public static readonly String PageBreakInside = "page-break-inside";
/// <summary>
/// The perspective declaration.
/// </summary>
public static readonly String Perspective = "perspective";
/// <summary>
/// The perspective-origin declaration.
/// </summary>
public static readonly String PerspectiveOrigin = "perspective-origin";
/// <summary>
/// The pointer-events declaration.
/// </summary>
public static readonly String PointerEvents = "pointer-events";
/// <summary>
/// The position declaration.
/// </summary>
public static readonly String Position = "position";
/// <summary>
/// The quotes declaration.
/// </summary>
public static readonly String Quotes = "quotes";
/// <summary>
/// The resize declaration.
/// </summary>
public static readonly String Resize = "resize";
/// <summary>
/// The right declaration.
/// </summary>
public static readonly String Right = "right";
/// <summary>
/// The ruby-align declaration.
/// </summary>
public static readonly String RubyAlign = "ruby-align";
/// <summary>
/// The ruby-overhang declaration.
/// </summary>
public static readonly String RubyOverhang = "ruby-overhang";
/// <summary>
/// The ruby-position declaration.
/// </summary>
public static readonly String RubyPosition = "ruby-position";
/// <summary>
/// The scrollbar3d-light-color declaration.
/// </summary>
public static readonly String Scrollbar3dLightColor = "scrollbar3d-light-color";
/// <summary>
/// The scrollbar-base-color declaration.
/// </summary>
public static readonly String ScrollbarBaseColor = "scrollbar-base-color";
/// <summary>
/// The scrollbar-arrow-color declaration.
/// </summary>
public static readonly String ScrollbarArrowColor = "scrollbar-arrow-color";
/// <summary>
/// The scrollbar-dark-shadow-color declaration.
/// </summary>
public static readonly String ScrollbarDarkShadowColor = "scrollbar-dark-shadow-color";
/// <summary>
/// The scrollbar-face-color declaration.
/// </summary>
public static readonly String ScrollbarFaceColor = "scrollbar-face-color";
/// <summary>
/// The scrollbar-highlight-color declaration.
/// </summary>
public static readonly String ScrollbarHighlightColor = "scrollbar-highlight-color";
/// <summary>
/// The scrollbar-shadow-color declaration.
/// </summary>
public static readonly String ScrollbarShadowColor = "scrollbar-shadow-color";
/// <summary>
/// The scrollbar-track-color declaration.
/// </summary>
public static readonly String ScrollbarTrackColor = "scrollbar-track-color";
/// <summary>
/// The stroke declaration.
/// </summary>
public static readonly String Stroke = "stroke";
/// <summary>
/// The stroke-dasharray declaration.
/// </summary>
public static readonly String StrokeDasharray = "stroke-dasharray";
/// <summary>
/// The stroke-dashoffset declaration.
/// </summary>
public static readonly String StrokeDashoffset = "stroke-dashoffset";
/// <summary>
/// The stroke-linecap declaration.
/// </summary>
public static readonly String StrokeLinecap = "stroke-linecap";
/// <summary>
/// The stroke-linejoin declaration.
/// </summary>
public static readonly String StrokeLinejoin = "stroke-linejoin";
/// <summary>
/// The stroke-miterlimit declaration.
/// </summary>
public static readonly String StrokeMiterlimit = "stroke-miterlimit";
/// <summary>
/// The stroke-opacity declaration.
/// </summary>
public static readonly String StrokeOpacity = "stroke-opacity";
/// <summary>
/// The stroke-width declaration.
/// </summary>
public static readonly String StrokeWidth = "stroke-width";
/// <summary>
/// The table-layout declaration.
/// </summary>
public static readonly String TableLayout = "table-layout";
/// <summary>
/// The text-align declaration.
/// </summary>
public static readonly String TextAlign = "text-align";
/// <summary>
/// The text-align-last declaration.
/// </summary>
public static readonly String TextAlignLast = "text-align-last";
/// <summary>
/// The text-anchor declaration.
/// </summary>
public static readonly String TextAnchor = "text-anchor";
/// <summary>
/// The text-autospace declaration.
/// </summary>
public static readonly String TextAutospace = "text-autospace";
/// <summary>
/// The text-decoration declaration.
/// </summary>
public static readonly String TextDecoration = "text-decoration";
/// <summary>
/// The text-decoration-color declaration.
/// </summary>
public static readonly String TextDecorationColor = "text-decoration-color";
/// <summary>
/// The text-decoration-line declaration.
/// </summary>
public static readonly String TextDecorationLine = "text-decoration-line";
/// <summary>
/// The text-decoration-style declaration.
/// </summary>
public static readonly String TextDecorationStyle = "text-decoration-style";
/// <summary>
/// The text-indent declaration.
/// </summary>
public static readonly String TextIndent = "text-indent";
/// <summary>
/// The text-justify declaration.
/// </summary>
public static readonly String TextJustify = "text-justify";
/// <summary>
/// The text-overflow declaration.
/// </summary>
public static readonly String TextOverflow = "text-overflow";
/// <summary>
/// The text-shadow declaration.
/// </summary>
public static readonly String TextShadow = "text-shadow";
/// <summary>
/// The text-transform declaration.
/// </summary>
public static readonly String TextTransform = "text-transform";
/// <summary>
/// The text-underline-position declaration.
/// </summary>
public static readonly String TextUnderlinePosition = "text-underline-position";
/// <summary>
/// The transform declaration.
/// </summary>
public static readonly String Transform = "transform";
/// <summary>
/// The transform-origin declaration.
/// </summary>
public static readonly String TransformOrigin = "transform-origin";
/// <summary>
/// The transform-style declaration.
/// </summary>
public static readonly String TransformStyle = "transform-style";
/// <summary>
/// The transition declaration.
/// </summary>
public static readonly String Transition = "transition";
/// <summary>
/// The transition-delay declaration.
/// </summary>
public static readonly String TransitionDelay = "transition-delay";
/// <summary>
/// The transition-duration declaration.
/// </summary>
public static readonly String TransitionDuration = "transition-duration";
/// <summary>
/// The transition-timing-function declaration.
/// </summary>
public static readonly String TransitionTimingFunction = "transition-timing-function";
/// <summary>
/// The transition-property declaration.
/// </summary>
public static readonly String TransitionProperty = "transition-property";
/// <summary>
/// The top declaration.
/// </summary>
public static readonly String Top = "top";
/// <summary>
/// The unicode-bidi declaration.
/// </summary>
public static readonly String UnicodeBidi = "unicode-bidi";
/// <summary>
/// The vertical-align declaration.
/// </summary>
public static readonly String VerticalAlign = "vertical-align";
/// <summary>
/// The visibility declaration.
/// </summary>
public static readonly String Visibility = "visibility";
/// <summary>
/// The white-space declaration.
/// </summary>
public static readonly String WhiteSpace = "white-space";
/// <summary>
/// The widows declaration.
/// </summary>
public static readonly String Widows = "widows";
/// <summary>
/// The width declaration.
/// </summary>
public static readonly String Width = "width";
/// <summary>
/// The word-break declaration.
/// </summary>
public static readonly String WordBreak = "word-break";
/// <summary>
/// The word-spacing declaration.
/// </summary>
public static readonly String WordSpacing = "word-spacing";
/// <summary>
/// The word-wrap declaration.
/// </summary>
public static readonly String WordWrap = "word-wrap";
/// <summary>
/// The writing-mode declaration.
/// </summary>
public static readonly String WritingMode = "writing-mode";
/// <summary>
/// The z-index declaration.
/// </summary>
public static readonly String ZIndex = "z-index";
/// <summary>
/// The zoom declaration.
/// </summary>
public static readonly String Zoom = "zoom";
/// <summary>
/// The unicode-range declaration.
/// </summary>
public static readonly String UnicodeRange = "unicode-range";
/// <summary>
/// The src declaration.
/// </summary>
public static readonly String Src = "src";
/// <summary>
/// The object-fit declaration.
/// </summary>
public static readonly String ObjectFit = "object-fit";
/// <summary>
/// The object-position declaration.
/// </summary>
public static readonly String ObjectPosition = "object-position";
/// <summary>
/// The min-zoom declaration.
/// </summary>
public static readonly String MinZoom = "min-zoom";
/// <summary>
/// The max-zoom declaration.
/// </summary>
public static readonly String MaxZoom = "max-zoom";
/// <summary>
/// The user-zoom declaration.
/// </summary>
public static readonly String UserZoom = "user-zoom";
/// <summary>
/// The orientation declaration.
/// </summary>
public static readonly String Orientation = "orientation";
/// <summary>
/// The string-set declaration.
/// </summary>
public static readonly String StringSet = "string-set";
/// <summary>
/// The running declaration.
/// </summary>
public static readonly String Running = "running";
/// <summary>
/// The footnote-display declaration.
/// </summary>
public static readonly String FootnoteDisplay = "footnote-display";
/// <summary>
/// The footnote-policy declaration.
/// </summary>
public static readonly String FootnotePolicy = "footnote-policy";
/// <summary>
/// The bookmark-level declaration.
/// </summary>
public static readonly String BookmarkLevel = "bookmark-level";
/// <summary>
/// The bookmark-label declaration.
/// </summary>
public static readonly String BookmarkLabel = "bookmark-label";
/// <summary>
/// The bookmark-state declaration.
/// </summary>
public static readonly String BookmarkState = "bookmark-state";
}
}
| 31.75 | 98 | 0.566557 | [
"MIT"
] | AngleSharp/AngleSharp.Css | src/AngleSharp.Css/Constants/PropertyNames.cs | 43,053 | C# |
using System;
using Xunit;
namespace HotChocolate.Types
{
public class MultiplierPathStringTests
{
[Fact]
public void Create_DefaultConstructor_IsEmpty()
{
// arrange
// act
var nameString = new MultiplierPathString();
// assert
Assert.True(nameString.IsEmpty);
Assert.False(nameString.HasValue);
Assert.Null(nameString.Value);
}
[InlineData("_")]
[InlineData("_Test")]
[InlineData("_1Test")]
[InlineData("Test")]
[InlineData("Test_Test")]
[InlineData("Test_Test.Test")]
[Theory]
public void Create_WithValidName_HasValue(string value)
{
// arrange
// act
var nameString = new MultiplierPathString(value);
// assert
Assert.Equal(nameString.Value, value);
Assert.True(nameString.HasValue);
Assert.False(nameString.IsEmpty);
}
[InlineData("1Test")]
[InlineData("Test-Test")]
[InlineData(".Test-Test")]
[Theory]
public void Create_WithInvalidName_ArgumentException(string value)
{
// arrange
// act
Action a = () => new MultiplierPathString(value);
// assert
Assert.Throws<ArgumentException>(a);
}
[InlineData("_")]
[InlineData("_Test")]
[InlineData("_1Test")]
[InlineData("Test")]
[InlineData("Test_Test")]
[InlineData("Test_Test.Test")]
[Theory]
public void ImplicitCast_ValidName_MultiplierPathString(string name)
{
// arrange
// act
MultiplierPathString nameString = name;
// assert
Assert.Equal(name, nameString.Value);
}
[InlineData("1Test")]
[InlineData("Test-Test")]
[InlineData("Täst")]
[InlineData(".Test-Test")]
[Theory]
public void ImplicitCast_InvalidName_MultiplierPathString(string name)
{
// arrange
// act
Action a = () => { MultiplierPathString nameString = name; };
// assert
Assert.Throws<ArgumentException>(a);
}
[Fact]
public void ImplicitCast_MultiplierPathString_String()
{
// arrange
var nameString = new MultiplierPathString("Foo");
// act
string name = nameString;
// assert
Assert.Equal(nameString.Value, name);
}
[Fact]
public void ToString_ReturnsValue()
{
// arrange
var nameString = new MultiplierPathString("Foo");
// act
string value = nameString.ToString(); ;
// assert
Assert.Equal(nameString.Value, value);
}
[Fact]
public void Append_MultiplierPathString_CombinedMultiplierPathString()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Bar");
// act
MultiplierPathString combined = a.Add(b);
// assert
Assert.Equal("FooBar", combined.ToString());
}
[Fact]
public void AddOp_MultiplierPathString_CombinedMultiplierPathString()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Bar");
// act
MultiplierPathString combined = a + b;
// assert
Assert.Equal("FooBar", combined.ToString());
}
[Fact]
public void AddOp_String_CombinedMultiplierPathString()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Bar";
// act
MultiplierPathString combined = a + b;
// assert
Assert.Equal("FooBar", combined.ToString());
}
[Fact]
public void Equals_MultiplierPathStringWithSameValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Foo");
// act
bool result = a.Equals(b);
// assert
Assert.True(result);
}
[Fact]
public void Equals_SameInstance_True()
{
// arrange
var a = new MultiplierPathString("Foo");
// act
bool result = a.Equals(a);
// assert
Assert.True(result);
}
[Fact]
public void EqualsIgnoreCasing_MultiplierPathStringWithDifferentCasing_True()
{
// arrange
var a = new MultiplierPathString("FOO");
var b = new MultiplierPathString("foo");
// act
bool result = a.Equals(b, StringComparison.OrdinalIgnoreCase);
// assert
Assert.True(result);
}
[Fact]
public void Equals_MultiplierPathStringDifferentValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Bar");
// act
bool result = a.Equals(b);
// assert
Assert.False(result);
}
[Fact]
public void Equals_StringWithSameValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Foo";
// act
bool result = a.Equals(b);
// assert
Assert.True(result);
}
[Fact]
public void Equals_StringDifferentValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Bar";
// act
bool result = a.Equals(b);
// assert
Assert.False(result);
}
[Fact]
public void EqualsOp_MultiplierPathStringWithSameValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Foo");
// act
bool result = a == b;
// assert
Assert.True(result);
}
[Fact]
public void EqualsOp_SameInstance_True()
{
// arrange
var a = new MultiplierPathString("Foo");
MultiplierPathString b = a;
// act
bool result = a == b;
// assert
Assert.True(result);
}
[Fact]
public void EqualsOp_MultiplierPathStringDifferentValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Bar");
// act
bool result = a == b;
// assert
Assert.False(result);
}
[Fact]
public void EqualsOp_StringWithSameValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Foo";
// act
bool result = a == b;
// assert
Assert.True(result);
}
[Fact]
public void EqualsOp_StringDifferentValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Bar";
// act
bool result = a == b;
// assert
Assert.False(result);
}
[Fact]
public void NotEqualsOp_MultiplierPathStringWithSameValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Foo");
// act
bool result = a != b;
// assert
Assert.False(result);
}
[Fact]
public void NotEqualsOp_SameInstance_False()
{
// arrange
var a = new MultiplierPathString("Foo");
MultiplierPathString b = a;
// act
bool result = a != b;
// assert
Assert.False(result);
}
[Fact]
public void NotEqualsOp_MultiplierPathStringDifferentValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = new MultiplierPathString("Bar");
// act
bool result = a != b;
// assert
Assert.True(result);
}
[Fact]
public void NotEqualsOp_StringWithSameValue_False()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Foo";
// act
bool result = a != b;
// assert
Assert.False(result);
}
[Fact]
public void NotEqualsOp_StringDifferentValue_True()
{
// arrange
var a = new MultiplierPathString("Foo");
var b = "Bar";
// act
bool result = a != b;
// assert
Assert.True(result);
}
}
}
| 24.695767 | 85 | 0.487306 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Core/test/Types.Tests/Types/Directives/MultiplierPathStringTests.cs | 9,338 | C# |
namespace Gu.Analyzers.Test.CodeFixes;
using System.Collections.Immutable;
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
internal static partial class MakeStaticFixTests
{
private static readonly FakeFxCopAnalyzer Analyzer = new();
// ReSharper disable once InconsistentNaming
private static readonly ExpectedDiagnostic CA1052 = ExpectedDiagnostic.Create(FakeFxCopAnalyzer.Descriptor);
[TestCase("public")]
[TestCase("internal")]
public static void StaticHolderClass(string modifier)
{
var before = @"
namespace N
{
public class ↓C
{
public static void M()
{
}
}
}".AssertReplace("public", modifier);
var after = @"
namespace N
{
public static class C
{
public static void M()
{
}
}
}".AssertReplace("public", modifier);
RoslynAssert.CodeFix(Analyzer, Fix, CA1052, before, after);
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
private class FakeFxCopAnalyzer : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor Descriptor = new("CA1052", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
Descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterSyntaxNodeAction(c => Handle(c), SyntaxKind.ClassDeclaration);
}
private static void Handle(SyntaxNodeAnalysisContext context)
{
if (context.Node is ClassDeclarationSyntax { Identifier: { } identifier })
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, identifier.GetLocation()));
}
}
}
}
| 29.726027 | 167 | 0.689862 | [
"MIT"
] | JohanLarsson/Gu.Analyzers | Gu.Analyzers.Test/CodeFixes/MakeStaticFixTests.CA1052.cs | 2,174 | C# |
using ClickerGame.Masters;
using System;
using System.Collections.Generic;
namespace ClickerGame.Models
{
/// <summary>
/// 強化インベントリー。
/// </summary>
public class EnhancerInventory
{
/// <summary>
/// 強化一覧。
/// </summary>
public IReadOnlyCollection<EnhancerMaster> Enhancers => _enhancers;
private readonly HashSet<EnhancerMaster> _enhancers = new HashSet<EnhancerMaster>();
/// <summary>
/// 1秒間の生産量。
/// </summary>
public IDictionary<ItemMaster, double> ItemFactors => _itemFactors;
private Dictionary<ItemMaster, double> _itemFactors = new Dictionary<ItemMaster, double>();
/// <summary>
/// 強化が追加された。
/// </summary>
public event Action<EnhancerMaster> Added;
public EnhancerInventory()
{
}
/// <summary>
/// 強化を追加する。
/// </summary>
/// <param name="enhancer">追加する強化マスター。</param>
public void Add(EnhancerMaster enhancer)
{
if (enhancer == null) { throw new ArgumentNullException(nameof(enhancer)); }
if (enhancer.ItemMaster != null)
{
if (_itemFactors.TryGetValue(enhancer.ItemMaster, out var factor))
{
_itemFactors[enhancer.ItemMaster] = factor + enhancer.Factor;
}
else { _itemFactors.Add(enhancer.ItemMaster, enhancer.Factor); }
}
_enhancers.Add(enhancer);
Added?.Invoke(enhancer);
}
/// <summary>
/// 強化を所有しているかどうか。
/// </summary>
/// <param name="enhancer">強化マスター。</param>
/// <returns>所有していれば true。</returns>
public bool HasEnhancer(EnhancerMaster enhancer)
{
if (enhancer == null) { throw new ArgumentNullException(nameof(enhancer)); }
return _enhancers.Contains(enhancer);
}
/// <summary>
/// 価格を取得する。
/// </summary>
/// <param name="enhancer">強化マスター。</param>
/// <returns>指定の強化マスターを購入するために必要な価格。</returns>
public Currency GetPrice(EnhancerMaster enhancer)
{
if (enhancer == null) { throw new ArgumentNullException(nameof(enhancer)); }
return enhancer.Price;
}
/// <summary>
/// 指定のアイテムに対する総強化倍率を取得する。
/// </summary>
/// <param name="item">アイテムマスター。</param>
/// <returns>総強化倍率。</returns>
public double GetTotalFactor(ItemMaster item)
{
if (ItemFactors.TryGetValue(item, out var factor))
{
return factor;
}
return 0;
}
}
}
| 29.901099 | 99 | 0.54355 | [
"MIT"
] | KuniTatsu/GameJam | Assets/Scripts/Models/EnhancerInventory.cs | 3,031 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace StringConcatBenchmark
{
class Program
{
static void Main(string[] args)
{
// Generate source
var source = new List<string>();
for (int i = 0; i < 30000; i++)
{
source.Add(i.ToString());
}
var stopwatch = new Stopwatch();
// Benchmark 1
stopwatch.Restart();
StringJoin(source);
stopwatch.Stop();
Console.WriteLine($"Benchmark 1 runs for {stopwatch.Elapsed}");
// Benchmark 2
stopwatch.Restart();
StringBuilder(source);
stopwatch.Stop();
Console.WriteLine($"Benchmark 2 runs for {stopwatch.Elapsed}");
// Benchmark 3
stopwatch.Restart();
PlusOperator(source);
stopwatch.Stop();
Console.WriteLine($"Benchmark 3 runs for {stopwatch.Elapsed}");
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
static void StringJoin(List<string> source)
{
var result = string.Join(";", source);
}
static void StringBuilder(List<string> source)
{
var result = new StringBuilder();
foreach (var item in source)
{
result.Append(item);
result.Append(";");
}
}
static void PlusOperator(List<string> source)
{
var result = string.Empty;
foreach(var item in source)
{
result += item + ";";
}
}
}
}
| 24.527778 | 75 | 0.492072 | [
"MIT"
] | digb/StringConcatBenchmark | StringConcatBenchmark/Program.cs | 1,768 | C# |
namespace ServiceManager.UI.forms
{
partial class frmConnectTo
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtHost = new Telerik.WinControls.UI.RadTextBox();
this.radLabel1 = new Telerik.WinControls.UI.RadLabel();
this.bnConnect = new Telerik.WinControls.UI.RadButton();
this.txtPort = new Telerik.WinControls.UI.RadTextBox();
this.radLabel2 = new Telerik.WinControls.UI.RadLabel();
((System.ComponentModel.ISupportInitialize)(this.txtHost)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.radLabel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bnConnect)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtPort)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.radLabel2)).BeginInit();
this.SuspendLayout();
//
// txtHost
//
this.txtHost.Font = new System.Drawing.Font("Segoe UI", 10F);
this.txtHost.Location = new System.Drawing.Point(119, 33);
this.txtHost.Name = "txtHost";
this.txtHost.SelectionStart = 9;
this.txtHost.Size = new System.Drawing.Size(222, 23);
this.txtHost.TabIndex = 0;
this.txtHost.Text = "localhost";
//
// radLabel1
//
this.radLabel1.Font = new System.Drawing.Font("Segoe UI", 10F);
this.radLabel1.Location = new System.Drawing.Point(12, 34);
this.radLabel1.Name = "radLabel1";
this.radLabel1.Size = new System.Drawing.Size(101, 21);
this.radLabel1.TabIndex = 1;
this.radLabel1.Text = "IP or Hostname";
this.radLabel1.TextAlignment = System.Drawing.ContentAlignment.TopLeft;
//
// bnConnect
//
this.bnConnect.Location = new System.Drawing.Point(119, 100);
this.bnConnect.Name = "bnConnect";
this.bnConnect.Size = new System.Drawing.Size(110, 24);
this.bnConnect.TabIndex = 2;
this.bnConnect.Text = "Connect";
this.bnConnect.Click += new System.EventHandler(this.bnConnect_Click);
//
// txtPort
//
this.txtPort.Font = new System.Drawing.Font("Segoe UI", 10F);
this.txtPort.Location = new System.Drawing.Point(119, 62);
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(74, 23);
this.txtPort.TabIndex = 0;
this.txtPort.Text = "50000";
//
// radLabel2
//
this.radLabel2.Font = new System.Drawing.Font("Segoe UI", 10F);
this.radLabel2.Location = new System.Drawing.Point(81, 63);
this.radLabel2.Name = "radLabel2";
this.radLabel2.Size = new System.Drawing.Size(32, 21);
this.radLabel2.TabIndex = 1;
this.radLabel2.Text = "Port";
this.radLabel2.TextAlignment = System.Drawing.ContentAlignment.TopLeft;
//
// frmConnectTo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(379, 136);
this.Controls.Add(this.bnConnect);
this.Controls.Add(this.radLabel2);
this.Controls.Add(this.radLabel1);
this.Controls.Add(this.txtPort);
this.Controls.Add(this.txtHost);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmConnectTo";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Connect to";
((System.ComponentModel.ISupportInitialize)(this.txtHost)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.radLabel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bnConnect)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtPort)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.radLabel2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Telerik.WinControls.UI.RadTextBox txtHost;
private Telerik.WinControls.UI.RadLabel radLabel1;
private Telerik.WinControls.UI.RadButton bnConnect;
private Telerik.WinControls.UI.RadTextBox txtPort;
private Telerik.WinControls.UI.RadLabel radLabel2;
}
} | 44.84127 | 107 | 0.590973 | [
"MIT"
] | MajMcCloud/ServiceManager | ServiceManagerUI/forms/frmConnectTo.Designer.cs | 5,652 | C# |
// *******************************************************************************
// <copyright file="FilterAppliesTo.cs" company="Intuit">
// Copyright (c) 2019 Intuit
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// *******************************************************************************
namespace Intuit.TSheets.Model.Enums
{
using System.Runtime.Serialization;
/// <summary>
/// Entity types to which a custom field item filter can be related
/// </summary>
public enum FilterAppliesTo
{
/// <summary>
/// Filter applies to Jobcode entity types.
/// </summary>
[EnumMember(Value = "jobcodes")]
Jobcodes,
/// <summary>
/// Filter applies to User entity types.
/// </summary>
[EnumMember(Value = "users")]
Users,
/// <summary>
/// Filter applies to Group entity types.
/// </summary>
[EnumMember(Value = "groups")]
Groups
}
} | 32.255319 | 83 | 0.567942 | [
"Apache-2.0"
] | LaudateCorpus1/TSheets-V1-DotNET-SDK | Intuit.TSheets/Model/Enums/FilterAppliesTo.cs | 1,518 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.IO.Charts
{
public class ChartFile : JsonFile<ChartFile>
{
public int ID { get; set; }
public string Artist { get; set; }
public string Title { get; set; }
public string Album { get; set; }
public short Year { get; set; }
public string Difficulty { get; set; }
public string Creator { get; set; }
public string Tags { get; set; }
public string Genre { get; set; }
public string Source { get; set; }
public long Offset { get; set; }
public long PreviewStart { get; set; }
public long PreviewEnd { get; set; }
public int Speed { get; set; }
public float BPM { get; set; }
public string SoundFile { get; set; }
public List<ChartNote> Notes { get; set; }
/// <summary>
/// The absolute path of the chart's file.
/// </summary>
public string FilePath;
static readonly List<string> _pathFixList = new List<string>()
{
"<", ">",
"|",
"?",
'"'.ToString()
};
public ChartFile(int id, string artist, string title, string album, short year,
string creator, string tags, long offset, long previewStart,
long previewEnd, float bpm, string soundFile, string genre, List<ChartNote> notes = null)
{
ID = id;
Artist = artist;
Title = title;
Album = album;
Year = year;
Creator = creator;
Tags = tags;
Offset = offset;
PreviewStart = previewStart;
PreviewEnd = previewEnd;
BPM = bpm;
SoundFile = soundFile;
Genre = genre;
if (notes == null)
Notes = new List<ChartNote>();
else
Notes = notes;
}
public ChartFile()
{
}
public static ChartFile ConvertOsuFile(string file)
{
FileInfo fI = new FileInfo(file);
if (!fI.Exists)
return null;
OsuFile osuFile = new OsuFile(fI.Name + fI.Extension, fI.Directory.FullName, new Dictionary<string, OsuSection>());
using (StreamReader sreader = new StreamReader(fI.FullName))
{
bool readSection = true;
bool readProps = false;
string sectionName = null;
string line;
while (!sreader.EndOfStream)
{
line = sreader.ReadLine();
if (string.IsNullOrEmpty(line))
continue;
Begin:
if (readSection)
{
if (line[0].Equals('['))
{
line = line.Trim('[', ']', ' ');
sectionName = line;
Logger.Log(sectionName);
osuFile.Sections.Add(line, new OsuSection(line, new Dictionary<string, OsuProperty>()));
readSection = false;
readProps = true;
}
continue;
}
if (readProps)
{
if (line[0].Equals('['))
{
readSection = true;
readProps = false;
goto Begin;
}
OsuProperty prop;
switch (sectionName.ToLower())
{
case "difficulty":
case "events":
case "editor":
continue;
case "timingpoints":
string[] timingSplit = line.Split(',');
int.TryParse(timingSplit[0], out int offset);
osuFile.Offset = offset;
float.TryParse(timingSplit[1], out float bpm);
osuFile.BPM = bpm;
readSection = true;
readProps = false;
continue;
case "hitobjects":
string[] noteSplit = line.Split(',').Skip(2).ToArray();
if (noteSplit == null || noteSplit.Length < 3)
continue;
long[] iNoteSplit = new long[noteSplit.Length];
for (int i = 0; i < noteSplit.Length; i++)
long.TryParse(noteSplit[i], out iNoteSplit[i]);
prop = new OsuProperty("Note." + noteSplit[0], new long[] { iNoteSplit[0], iNoteSplit[1], iNoteSplit[2] });
osuFile.Sections[sectionName].Properties.Add(prop.Name, prop);
continue;
default:
break;
}
string[] propSplit = line.Split(':');
if (propSplit == null || propSplit.Length < 2)
continue;
if (float.TryParse(propSplit[1], out float fval))
{
prop = new OsuProperty(propSplit[0], fval);
osuFile.Sections[sectionName].Properties.Add(prop.Name, prop);
continue;
}
prop = new OsuProperty(propSplit[0], propSplit[1]);
osuFile.Sections[sectionName].Properties.Add(prop.Name, prop);
}
}
}
OsuSection general = osuFile.Sections["General"];
OsuSection metadata = osuFile.Sections["Metadata"];
ChartFile ch = new ChartFile
{
ID = 0,
Artist = (string)metadata.Properties["Artist"].Value,
Title = (string)metadata.Properties["Title"].Value,
Tags = (string)metadata.Properties["Tags"].Value,
Difficulty = (string)metadata.Properties["Version"].Value,
Creator = (string)metadata.Properties["Creator"].Value,
Source = (string)metadata.Properties["Source"].Value,
PreviewStart = (long)(float)general.Properties["PreviewTime"].Value,
Offset = osuFile.Offset,
SoundFile = ((string)general.Properties["AudioFilename"].Value).TrimStart(' '),
Notes = new List<ChartNote>()
};
OsuSection snote = osuFile.Sections["HitObjects"];
ChartNote cn;
long[] vals;
bool bigNote;
TimeSpan timing;
short color;
foreach (var prop in snote.Properties)
{
vals = (long[])prop.Value.Value;
timing = TimeSpan.FromMilliseconds(vals[0]);
switch (vals[2])
{
default:
case 0:
bigNote = false;
color = 1;
break;
case 2:
bigNote = false;
color = 0;
break;
case 4:
bigNote = true;
color = 1;
break;
case 6:
bigNote = true;
color = 0;
break;
case 8:
bigNote = false;
color = 0;
break;
case 12:
bigNote = true;
color = 0;
break;
}
cn = new ChartNote(timing, bigNote, color);
ch.Notes.Add(cn);
}
return ch;
}
public static string FixPath(string path)
{
string p = string.Copy(path);
foreach (string str in _pathFixList)
p = p.Replace(str, "");
return p;
}
/// <summary>
/// Takes in a path to a chart file and attempts to parse it.
/// Will throw an error if unable to be parsed.
/// </summary>
/// <param name="path"></param>
/// <param name="checkValidity"></param>
public static ChartFile Parse(string path, bool checkValidity = true)
{
ChartFile chart;
using (var file = File.OpenText(path))
{
chart = Load(path);
chart.FilePath = path;
}
AfterLoad(chart, checkValidity);
return chart;
}
/// <summary>
/// Does some sorting of the ChartFile
/// </summary>
public void Sort()
{
// sort notes by time (ms) ascending
}
/// <summary>
/// </summary>
/// <param name="chart"></param>
/// <param name="checkValidity"></param>
/// <exception cref="ArgumentException"></exception>
static void AfterLoad(ChartFile chart, bool checkValidity)
{
if (checkValidity && !chart.IsValid())
throw new ArgumentException("The chart file is invalid.");
// Try to sort the ChartFile before returning.
chart.Sort();
}
private bool IsValid()
{
return true; // maybe test if valid if necessary
}
#region Osu file
class OsuFile
{
public string Name { get; set; }
public string Path { get; set; }
public long Offset { get; set; }
public float BPM { get; set; }
public string SoundFile { get; set; }
public Dictionary<string, OsuSection> Sections { get; set; }
public OsuFile(string name, string path, Dictionary<string, OsuSection> sections)
{
Name = name;
Path = path;
Sections = sections;
}
public OsuFile()
{
}
}
class OsuSection : IEquatable<OsuSection>
{
public string Name { get; set; }
public Dictionary<string, OsuProperty> Properties { get; set; }
public OsuSection(string name, Dictionary<string, OsuProperty> properties)
{
Name = name;
Properties = properties;
}
public OsuSection()
{
}
public override bool Equals(object obj)
{
return Equals(obj as OsuSection);
}
public bool Equals(OsuSection other)
{
return other != null &&
Name == other.Name;
}
public override int GetHashCode()
{
return 539060726 + EqualityComparer<string>.Default.GetHashCode(Name);
}
public static bool operator ==(OsuSection section1, OsuSection section2)
{
return EqualityComparer<OsuSection>.Default.Equals(section1, section2);
}
public static bool operator !=(OsuSection section1, OsuSection section2)
{
return !(section1 == section2);
}
}
class OsuProperty : IEquatable<OsuProperty>
{
public string Name { get; set; }
public object Value { get; set; }
public OsuProperty(string name, object value)
{
Name = name;
Value = value;
}
public OsuProperty()
{
}
public override bool Equals(object obj)
{
return Equals(obj as OsuProperty);
}
public bool Equals(OsuProperty other)
{
return other != null &&
Name == other.Name &&
EqualityComparer<object>.Default.Equals(Value, other.Value);
}
public override int GetHashCode()
{
var hashCode = -244751520;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Value);
return hashCode;
}
public static bool operator ==(OsuProperty property1, OsuProperty property2)
{
return EqualityComparer<OsuProperty>.Default.Equals(property1, property2);
}
public static bool operator !=(OsuProperty property1, OsuProperty property2)
{
return !(property1 == property2);
}
}
#endregion
}
}
| 32.713942 | 139 | 0.440664 | [
"MIT"
] | Darginn/Drum-Smasher | Game/Assets/Scripts/IO/Charts/ChartFile.cs | 13,611 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.AI.EnemyStates
{
public interface IState
{
//Prepare the state
void Enter(Enemy parent);
void Update();
void Exit();
}
} | 17 | 39 | 0.647059 | [
"MIT"
] | baidenx7/Elebris-Adventures | Pulled Resources/Scripts/AI/EnemyStates/IState.cs | 274 | 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 InternationalCompany
{
public partial class Home
{
}
}
| 24.333333 | 81 | 0.413242 | [
"MIT"
] | pavelhristov/ASP.NETWebForms | ASP.NETMasterPages/InternationalCompany/Home.aspx.designer.cs | 440 | C# |
using NUnit.Framework;
using HashTable_RansomNote;
using System;
namespace Tests
{
public class Tests : Solution
{
[SetUp]
public void Setup()
{
}
[Test]
public void HashRansomTest1()
{
string[] magazine = "give me one grand today night".Split(' ');
string[] note = "give one grand today".Split(' ');
Assert.True(checkMagazine(magazine, note));
}
[Test]
public void HashRansomTest2()
{
string[] magazine = "two times three is not four".Split(' ');
string[] note = "two times two is four".Split(' ');
Assert.False(checkMagazine(magazine, note));
}
[Test]
public void HashRansomTest3()
{
string[] magazine = "ive got a lovely bunch of coconuts".Split(' ');
string[] note = "ive got some coconuts".Split(' ');
Assert.False(checkMagazine(magazine, note));
}
[Test]
public void HashRansomTest4()
{
string[] magazine = new string[30000];
string[] note = new string[20000];
string[] fileAsString = System.IO.File.ReadAllText(@"D:\Source\HackerRankChallenges\HackerRankChallenges\HashTable_RansomNote_Test\bin\input18.txt").Split(' ');
for (int i = 0; i < magazine.Length; i++)
{
magazine[i] = fileAsString[i + 2];
}
for (int i = 0; i < note.Length; i++)
{
note[i] = fileAsString[magazine.Length + i];
}
Assert.False(checkMagazine(magazine, note));
}
[Test]
public void HashRansomTest5()
{
string[] magazine = new string[30000];
string[] note = new string[10000];
string[] fileAsString = System.IO.File.ReadAllText(@"D:\Source\HackerRankChallenges\HackerRankChallenges\HashTable_RansomNote_Test\bin\input14.txt").Split(' ');
for (int i = 0; i < magazine.Length; i++)
{
magazine[i] = fileAsString[i + 2];
}
for (int i = 0; i < note.Length; i++)
{
note[i] = fileAsString[magazine.Length + i];
}
Assert.True(checkMagazine(magazine, note));
}
}
} | 31.864865 | 172 | 0.52078 | [
"MIT"
] | anathemus/HackerRankChallenges | HackerRankChallenges/HashTable_RansomNote_Test/UnitTest1.cs | 2,358 | C# |
namespace ForumNet.Web.ViewModels.Posts
{
public class PostsCategoryDetailsViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
} | 20.111111 | 46 | 0.629834 | [
"MIT"
] | AnthonyDisasi/ForumNet | Web/ForumNet.Web.ViewModels/Posts/PostsCategoryDetailsViewModel.cs | 183 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.Models;
namespace Microsoft.Azure.Management.RecoveryServices
{
public static partial class VaultOperationsExtensions
{
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <returns>
/// The response model for the Vm group object.
/// </returns>
public static VaultCreateResponse BeginCreating(this IVaultOperations operations, string resourceGroupName, string vaultName, VaultCreateArgs vaultCreationInput)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).BeginCreatingAsync(resourceGroupName, vaultName, vaultCreationInput);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <returns>
/// The response model for the Vm group object.
/// </returns>
public static Task<VaultCreateResponse> BeginCreatingAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, VaultCreateArgs vaultCreationInput)
{
return operations.BeginCreatingAsync(resourceGroupName, vaultName, vaultCreationInput, CancellationToken.None);
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static RecoveryServicesOperationStatusResponse BeginDeleting(this IVaultOperations operations, string resourceGroupName, string vaultName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).BeginDeletingAsync(resourceGroupName, vaultName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<RecoveryServicesOperationStatusResponse> BeginDeletingAsync(this IVaultOperations operations, string resourceGroupName, string vaultName)
{
return operations.BeginDeletingAsync(resourceGroupName, vaultName, CancellationToken.None);
}
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Optional. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static RecoveryServicesOperationStatusResponse Create(this IVaultOperations operations, string resourceGroupName, string vaultName, VaultCreateArgs vaultCreationInput)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).CreateAsync(resourceGroupName, vaultName, vaultCreationInput);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Optional. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<RecoveryServicesOperationStatusResponse> CreateAsync(this IVaultOperations operations, string resourceGroupName, string vaultName, VaultCreateArgs vaultCreationInput)
{
return operations.CreateAsync(resourceGroupName, vaultName, vaultCreationInput, CancellationToken.None);
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static RecoveryServicesOperationStatusResponse Delete(this IVaultOperations operations, string resourceGroupName, string vaultName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).DeleteAsync(resourceGroupName, vaultName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<RecoveryServicesOperationStatusResponse> DeleteAsync(this IVaultOperations operations, string resourceGroupName, string vaultName)
{
return operations.DeleteAsync(resourceGroupName, vaultName, CancellationToken.None);
}
/// <summary>
/// Get the Vault details.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for Vault.
/// </returns>
public static VaultResponse Get(this IVaultOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).GetAsync(resourceGroupName, resourceName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the Vault details.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for Vault.
/// </returns>
public static Task<VaultResponse> GetAsync(this IVaultOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(resourceGroupName, resourceName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Fetches resource storage config.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of resource group to which vault belongs
/// </param>
/// <param name='resourceName'>
/// Required. The name of the vault
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a get resource storage config response.
/// </returns>
public static GetResourceStorageConfigResponse GetResourceStorageConfig(this IVaultOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).GetResourceStorageConfigAsync(resourceGroupName, resourceName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fetches resource storage config.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of resource group to which vault belongs
/// </param>
/// <param name='resourceName'>
/// Required. The name of the vault
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The definition of a get resource storage config response.
/// </returns>
public static Task<GetResourceStorageConfigResponse> GetResourceStorageConfigAsync(this IVaultOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders)
{
return operations.GetResourceStorageConfigAsync(resourceGroupName, resourceName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of Vaults.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for Vault.
/// </returns>
public static VaultListResponse List(this IVaultOperations operations, string resourceGroupName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).ListAsync(resourceGroupName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of Vaults.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for Vault.
/// </returns>
public static Task<VaultListResponse> ListAsync(this IVaultOperations operations, string resourceGroupName, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(resourceGroupName, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Updates vault storage model type.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='updateVaultStorageTypeRequest'>
/// Required. Update Vault Storage Type Request
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse UpdateStorageType(this IVaultOperations operations, string resourceGroupName, string resourceName, UpdateVaultStorageTypeRequest updateVaultStorageTypeRequest, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IVaultOperations)s).UpdateStorageTypeAsync(resourceGroupName, resourceName, updateVaultStorageTypeRequest, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates vault storage model type.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.IVaultOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='updateVaultStorageTypeRequest'>
/// Required. Update Vault Storage Type Request
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateStorageTypeAsync(this IVaultOperations operations, string resourceGroupName, string resourceName, UpdateVaultStorageTypeRequest updateVaultStorageTypeRequest, CustomRequestHeaders customRequestHeaders)
{
return operations.UpdateStorageTypeAsync(resourceGroupName, resourceName, updateVaultStorageTypeRequest, customRequestHeaders, CancellationToken.None);
}
}
}
| 46.253493 | 258 | 0.624434 | [
"Apache-2.0"
] | CloudHeaven/Azure | src/ResourceManagement/RecoveryServices/RecoveryServicesManagement/Generated/VaultOperationsExtensions.cs | 23,173 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.rtc.Model.V20180111;
namespace Aliyun.Acs.rtc.Transform.V20180111
{
public class DescribeRtcScaleResponseUnmarshaller
{
public static DescribeRtcScaleResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeRtcScaleResponse describeRtcScaleResponse = new DescribeRtcScaleResponse();
describeRtcScaleResponse.HttpResponse = _ctx.HttpResponse;
describeRtcScaleResponse.RequestId = _ctx.StringValue("DescribeRtcScale.RequestId");
List<DescribeRtcScaleResponse.DescribeRtcScale_ScaleItem> describeRtcScaleResponse_scale = new List<DescribeRtcScaleResponse.DescribeRtcScale_ScaleItem>();
for (int i = 0; i < _ctx.Length("DescribeRtcScale.Scale.Length"); i++) {
DescribeRtcScaleResponse.DescribeRtcScale_ScaleItem scaleItem = new DescribeRtcScaleResponse.DescribeRtcScale_ScaleItem();
scaleItem.Time = _ctx.StringValue("DescribeRtcScale.Scale["+ i +"].Time");
scaleItem.ChannelCount = _ctx.LongValue("DescribeRtcScale.Scale["+ i +"].ChannelCount");
scaleItem.UserCount = _ctx.LongValue("DescribeRtcScale.Scale["+ i +"].UserCount");
scaleItem.SessionCount = _ctx.LongValue("DescribeRtcScale.Scale["+ i +"].SessionCount");
scaleItem.AudioDuration = _ctx.LongValue("DescribeRtcScale.Scale["+ i +"].AudioDuration");
scaleItem.VideoDuration = _ctx.LongValue("DescribeRtcScale.Scale["+ i +"].VideoDuration");
describeRtcScaleResponse_scale.Add(scaleItem);
}
describeRtcScaleResponse.Scale = describeRtcScaleResponse_scale;
return describeRtcScaleResponse;
}
}
}
| 45.944444 | 159 | 0.758968 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-rtc/Rtc/Transform/V20180111/DescribeRtcScaleResponseUnmarshaller.cs | 2,481 | C# |
using Microsoft.Maui.Graphics.Text;
using Markdig.Syntax;
namespace Microsoft.Maui.Graphics.Text.Renderer
{
public class ListRenderer : AttributedTextObjectRenderer<ListBlock>
{
protected override void Write(
AttributedTextRenderer renderer,
ListBlock listBlock)
{
var start = renderer.Count;
renderer.EnsureLine();
foreach (var item in listBlock)
{
var listItem = (ListItemBlock) item;
renderer.EnsureLine();
renderer.Write("• ");
renderer.WriteChildren(listItem);
}
var length = renderer.Count - start;
if (length > 0)
{
var attributes = new TextAttributes();
if (!listBlock.IsOrdered) attributes[TextAttribute.UnorderedList] = "True";
renderer.AddTextRun(start, length, attributes);
}
}
}
}
| 21.971429 | 79 | 0.703511 | [
"MIT"
] | eerhardt/Microsoft.Maui.Graphics | src/Microsoft.Maui.Graphics.Text.Markdig/Renderer/ListRenderer.cs | 771 | C# |
using Microsoft.UI.Xaml.Controls;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace MasteriesQuest.Pages;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class SettingsPage : Page
{
public SettingsPage()
{
InitializeComponent();
}
} | 26.823529 | 82 | 0.675439 | [
"Unlicense"
] | magisteriis/masteries-quest | MasteriesQuest.Desktop/Pages/SettingsPage.xaml.cs | 458 | C# |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Windows;
namespace CustomApplicationClient
{
public class CustomApplication : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MessageBox.Show(@"Hello, reusable custom application!");
}
}
} | 28.8125 | 104 | 0.67462 | [
"MIT"
] | 21pages/WPF-Samples | Application Management/CustomApplication/CustomApplicationClient/CustomApplication.cs | 461 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Elsa.Models;
using Elsa.Persistence.YesSql.Documents;
using Elsa.Persistence.YesSql.Extensions;
using Elsa.Persistence.YesSql.Indexes;
using YesSql;
namespace Elsa.Persistence.YesSql.Services
{
public class YesSqlWorkflowDefinitionStore : IWorkflowDefinitionStore
{
private readonly ISession session;
private readonly IMapper mapper;
public YesSqlWorkflowDefinitionStore(ISession session, IMapper mapper)
{
this.session = session;
this.mapper = mapper;
}
public async Task<WorkflowDefinitionVersion> SaveAsync(
WorkflowDefinitionVersion definition,
CancellationToken cancellationToken = default)
{
var document = mapper.Map<WorkflowDefinitionVersionDocument>(definition);
session.Save(document);
await session.CommitAsync();
return mapper.Map<WorkflowDefinitionVersion>(document);
}
public async Task AddAsync(WorkflowDefinitionVersion definition, CancellationToken cancellationToken = default)
{
var document = mapper.Map<WorkflowDefinitionVersionDocument>(definition);
session.Save(document);
await session.CommitAsync();
}
public async Task<WorkflowDefinitionVersion> GetByIdAsync(
string id,
VersionOptions version,
CancellationToken cancellationToken = default)
{
var query = session
.Query<WorkflowDefinitionVersionDocument, WorkflowDefinitionIndex>()
.Where(x => x.WorkflowDefinitionId == id)
.WithVersion(version);
var document = await query.FirstOrDefaultAsync();
return mapper.Map<WorkflowDefinitionVersion>(document);
}
public async Task<IEnumerable<WorkflowDefinitionVersion>> ListAsync(
VersionOptions version,
CancellationToken cancellationToken = default)
{
var query = session.Query<WorkflowDefinitionVersionDocument, WorkflowDefinitionIndex>()
.WithVersion(version);
var documents = await query.ListAsync();
return mapper.Map<IEnumerable<WorkflowDefinitionVersion>>(documents);
}
public async Task<WorkflowDefinitionVersion> UpdateAsync(
WorkflowDefinitionVersion definition,
CancellationToken cancellationToken)
{
var query = session
.Query<WorkflowDefinitionVersionDocument, WorkflowDefinitionIndex>()
.Where(x => x.WorkflowDefinitionId == definition.DefinitionId)
.WithVersion(VersionOptions.SpecificVersion(definition.Version));
var document = await query.FirstOrDefaultAsync();
document = mapper.Map(definition, document);
session.Save(document);
await session.CommitAsync();
return mapper.Map<WorkflowDefinitionVersion>(document);
}
public async Task<int> DeleteAsync(string id, CancellationToken cancellationToken = default)
{
var instanceDocuments = (await session.Query<WorkflowInstanceDocument, WorkflowInstanceIndex>()
.Where(x => x.WorkflowDefinitionId == id)
.ListAsync())
.ToList();
var definitionDocuments = (await session
.Query<WorkflowDefinitionVersionDocument, WorkflowDefinitionIndex>()
.Where(x => x.WorkflowDefinitionId == id)
.ListAsync())
.ToList();
foreach (var document in instanceDocuments)
{
session.Delete(document);
}
foreach (var document in definitionDocuments)
{
session.Delete(document);
}
await session.CommitAsync();
return definitionDocuments.Count;
}
}
} | 37.052632 | 120 | 0.61411 | [
"BSD-3-Clause"
] | jamesdoran/elsa-core | src/persistence/Elsa.Persistence.YesSql/Services/YesSqlWorkflowDefinitionStore.cs | 4,224 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MightyCalc.Calculations.Aggregate.Commands;
using MightyCalc.Node;
using MightyCalc.Node.Domain;
using MightyCalc.Reports;
namespace MightyCalc.API
{
public class AkkaApi : IApiController
{
private readonly INamedCalculatorPool _pool;
private readonly IFunctionsTotalUsageQuery _totalUsageQuery;
private readonly IFunctionsUsageQuery _usageQuery;
private readonly IKnownFunctionsQuery _knownFunctionsQuery;
public AkkaApi(INamedCalculatorPool pool,
IFunctionsTotalUsageQuery totalUsageQuery,
IFunctionsUsageQuery usageQuery,
IKnownFunctionsQuery knownFunctionsQuery)
{
_knownFunctionsQuery = knownFunctionsQuery;
_usageQuery = usageQuery;
_totalUsageQuery = totalUsageQuery;
_pool = pool;
}
public Task<double> CalculateAsync(Expression body)
{
return _pool.For("anonymous").Calculate(body.Representation,
body.Parameters.Select(p => new Calculations.Parameter(p.Name, p.Value)).ToArray());
}
public async Task<IReadOnlyCollection<NamedExpression>> FindFunctionsAsync(string name)
{
var definitions = await _knownFunctionsQuery.Execute("anonymous",name);
return definitions.Select(d => new NamedExpression()
{
Description = d.Description,
Expression = new Expression
{
Parameters = d.Parameters.Select(p => new Parameter()
{
Name = p
}).ToList(),
Representation = d.Expression
},
Name = d.Name
}).ToArray();
}
public async Task CreateFunctionAsync(NamedExpression body)
{
//API-specific restriction, not coming from business logic!
var functionDefinitions = await _knownFunctionsQuery.Execute("anonymous", body.Name);
if (functionDefinitions.Any(f => f.Name == body.Name))
throw new FunctionAlreadyExistsException();
await _pool.For("anonymous").AddFunction(body.Name,
body.Description,
body.Expression.Representation,
body.Expression.Parameters.Select(p => p.Name).ToArray());
}
internal class FunctionAlreadyExistsException : Exception
{
}
public Task ReplaceFunctionAsync(NamedExpression body)
{
return _pool.For("anonymous").AddFunction(body.Name,
body.Description,
body.Expression.Representation,
body.Expression.Parameters.Select(p => p.Name).ToArray());
}
public async Task<Report> UsageTotalStatsAsync()
{
var usage = await _totalUsageQuery.Execute();
return new Report()
{
UsageStatistics = usage.Select(u => new FunctionUsage
{
Name = u.FunctionName,
UsageCount = (int) u.InvocationsCount
}).ToList()
};
}
public async Task<PeriodReport> UserUsageStatsAsync(DateTimeOffset? @from, DateTimeOffset? to)
{
var usage = await _usageQuery.Execute("anonymous", @from, to);
return new PeriodReport()
{
UsageStatistics = usage.Select(u => new FunctionPeriodUsage
{
Name = u.FunctionName,
UsageCount = u.InvocationsCount,
PeriodStart = u.PeriodStart,
PeriodEnd = u.PeriodEnd,
Period = u.Period.ToString("g")
}).ToList()
};
}
}
} | 36.666667 | 102 | 0.571212 | [
"MIT"
] | ContextCore/MightyCalc | src/MightyCalc.API/AkkaApi.cs | 3,960 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Proto.Tests
{
public class ReceiveTimeoutTests
{
private static readonly ActorSystem System = new();
private static readonly RootContext Context = System.Root;
[Fact]
public async Task receive_timeout_received_within_expected_time()
{
var timeoutReceived = false;
var receiveTimeoutWaiter = GetExpiringTaskCompletionSource();
var props = Props.FromFunc(context =>
{
switch (context.Message)
{
case Started _:
context.SetReceiveTimeout(TimeSpan.FromMilliseconds(150));
break;
case ReceiveTimeout _:
timeoutReceived = true;
receiveTimeoutWaiter.SetResult(0);
break;
}
return Task.CompletedTask;
}
);
Context.Spawn(props);
await GetSafeAwaitableTask(receiveTimeoutWaiter);
Assert.True(timeoutReceived);
}
[Fact]
public async Task receive_timeout_not_received_within_expected_time()
{
var timeoutReceived = false;
var actorStartedWaiter = GetExpiringTaskCompletionSource();
var props = Props.FromFunc(context =>
{
switch (context.Message)
{
case Started _:
context.SetReceiveTimeout(TimeSpan.FromMilliseconds(1500));
actorStartedWaiter.SetResult(0);
break;
case ReceiveTimeout _:
timeoutReceived = true;
break;
}
return Task.CompletedTask;
}
);
Context.Spawn(props);
await GetSafeAwaitableTask(actorStartedWaiter);
Assert.False(timeoutReceived);
}
[Fact]
public async Task can_cancel_receive_timeout()
{
var timeoutReceived = false;
var endingTimeout = TimeSpan.MaxValue;
var autoExpiringWaiter = GetExpiringTaskCompletionSource(1500);
var props = Props.FromFunc(context =>
{
switch (context.Message)
{
case Started _:
context.SetReceiveTimeout(TimeSpan.FromMilliseconds(150));
context.CancelReceiveTimeout();
endingTimeout = context.ReceiveTimeout;
break;
case ReceiveTimeout _:
timeoutReceived = true;
autoExpiringWaiter.SetResult(0); // should never happen
break;
}
return Task.CompletedTask;
}
);
Context.Spawn(props);
// this task should auto cancel
await GetSafeAwaitableTask(autoExpiringWaiter);
Assert.True(autoExpiringWaiter.Task.IsCanceled);
Assert.Equal(TimeSpan.Zero, endingTimeout);
Assert.False(timeoutReceived);
}
[Fact]
public async Task can_still_set_receive_timeout_after_cancelling()
{
var timeoutReceived = false;
var receiveTimeoutWaiter = GetExpiringTaskCompletionSource();
var props = Props.FromFunc(context =>
{
switch (context.Message)
{
case Started _:
context.SetReceiveTimeout(TimeSpan.FromMilliseconds(150));
context.CancelReceiveTimeout();
context.SetReceiveTimeout(TimeSpan.FromMilliseconds(150));
break;
case ReceiveTimeout _:
timeoutReceived = true;
receiveTimeoutWaiter.SetResult(0);
break;
}
return Task.CompletedTask;
}
);
Context.Spawn(props);
await GetSafeAwaitableTask(receiveTimeoutWaiter);
Assert.True(timeoutReceived);
}
private TaskCompletionSource<int> GetExpiringTaskCompletionSource(int timeoutMs = 60000)
{
var tcs = new TaskCompletionSource<int>();
var ct = new CancellationTokenSource();
ct.Token.Register(() => tcs.TrySetCanceled());
ct.CancelAfter(timeoutMs);
return tcs;
}
private ConfiguredTaskAwaitable<Task<int>> GetSafeAwaitableTask(TaskCompletionSource<int> tcs)
{
return tcs.Task
.ContinueWith(t => t) // suppress any TaskCanceledException
.ConfigureAwait(false);
}
}
} | 34.953642 | 102 | 0.499242 | [
"Apache-2.0"
] | dhavalgajera/protoactor-dotnet | tests/Proto.Actor.Tests/ReceiveTimeoutTests.cs | 5,280 | C# |
namespace WebApi.Boilerplate.Application.Requests.Auth
{
public class RefreshTokenRequest
{
public string Token { get; set; }
public string RefreshToken { get; set; }
}
} | 24.875 | 55 | 0.663317 | [
"MIT"
] | bharathwajv/fullstackhero | src/Application/Requests/Auth/RefreshTokenRequest.cs | 201 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Bot.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Bot.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Image1 {
get {
object obj = ResourceManager.GetObject("Image1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to bakkesmod.
/// </summary>
public static string String1 {
get {
return ResourceManager.GetString("String1", resourceCulture);
}
}
}
}
| 41 | 169 | 0.590068 | [
"MIT"
] | aydensutt/RLBotCSharpExample | CSharpBot/Bot/Properties/Resources.Designer.cs | 3,405 | C# |
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using moddingSuite.Model.Ndfbin;
using moddingSuite.Model.Ndfbin.Types;
using moddingSuite.ViewModel.Base;
namespace moddingSuite.ViewModel.Ndf
{
public class AddCollectionItemViewModel : ViewModelBase
{
private readonly List<NdfType> _typeSelection = new List<NdfType>();
private NdfType _type = NdfType.Unset;
private CollectionItemValueHolder _wrapper;
public AddCollectionItemViewModel(NdfBinary mgr, Window view)
{
Manager = mgr;
View = view;
OkCommand = new ActionCommand(OkCommandExecute, () => Type != NdfType.Unset);
CancelCommand = new ActionCommand(CancelCommandExecute);
_typeSelection.AddRange(NdfTypeManager.GetTypeSelection());
}
public ICommand OkCommand { get; protected set; }
public ICommand CancelCommand { get; protected set; }
public NdfBinary Manager { get; protected set; }
protected Window View { get; set; }
public NdfType Type
{
get { return _type; }
set
{
_type = value;
GetValueForType();
OnPropertyChanged(() => Type);
}
}
public List<NdfType> TypeSelection
{
get { return _typeSelection; }
}
public CollectionItemValueHolder Wrapper
{
get { return _wrapper; }
set
{
_wrapper = value;
OnPropertyChanged(() => Wrapper);
}
}
private void GetValueForType()
{
Wrapper = new CollectionItemValueHolder(NdfTypeManager.GetValue(new byte[NdfTypeManager.SizeofType(Type)], Type, Manager), Manager);
}
private void CancelCommandExecute(object obj)
{
View.DialogResult = false;
}
private void OkCommandExecute(object obj)
{
View.DialogResult = true;
View.Close();
}
}
} | 28.213333 | 144 | 0.581758 | [
"MIT"
] | RemiGC/moddingSuite | moddingSuite/ViewModel/Ndf/AddCollectionItemViewModel.cs | 2,118 | C# |
/*
* [The "BSD license"]
* Copyright (c) 2011 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace TypeSql.Antlr.Runtime
{
using ArgumentNullException = System.ArgumentNullException;
using Exception = System.Exception;
using SerializationInfo = System.Runtime.Serialization.SerializationInfo;
using StreamingContext = System.Runtime.Serialization.StreamingContext;
[System.Serializable]
public class NoViableAltException : RecognitionException
{
private readonly string _grammarDecisionDescription;
private readonly int _decisionNumber;
private readonly int _stateNumber;
public NoViableAltException()
{
}
public NoViableAltException(string grammarDecisionDescription)
{
this._grammarDecisionDescription = grammarDecisionDescription;
}
public NoViableAltException(string message, string grammarDecisionDescription)
: base(message)
{
this._grammarDecisionDescription = grammarDecisionDescription;
}
public NoViableAltException(string message, string grammarDecisionDescription, Exception innerException)
: base(message, innerException)
{
this._grammarDecisionDescription = grammarDecisionDescription;
}
public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
: this(grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
{
}
public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
: base(input, k)
{
this._grammarDecisionDescription = grammarDecisionDescription;
this._decisionNumber = decisionNumber;
this._stateNumber = stateNumber;
}
public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
: this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
{
}
public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
: base(message, input, k)
{
this._grammarDecisionDescription = grammarDecisionDescription;
this._decisionNumber = decisionNumber;
this._stateNumber = stateNumber;
}
public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, Exception innerException)
: this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1, innerException)
{
}
public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k, Exception innerException)
: base(message, input, k, innerException)
{
this._grammarDecisionDescription = grammarDecisionDescription;
this._decisionNumber = decisionNumber;
this._stateNumber = stateNumber;
}
protected NoViableAltException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info == null)
throw new ArgumentNullException("info");
this._grammarDecisionDescription = info.GetString("GrammarDecisionDescription");
this._decisionNumber = info.GetInt32("DecisionNumber");
this._stateNumber = info.GetInt32("StateNumber");
}
public int DecisionNumber
{
get
{
return _decisionNumber;
}
}
public string GrammarDecisionDescription
{
get
{
return _grammarDecisionDescription;
}
}
public int StateNumber
{
get
{
return _stateNumber;
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("GrammarDecisionDescription", _grammarDecisionDescription);
info.AddValue("DecisionNumber", _decisionNumber);
info.AddValue("StateNumber", _stateNumber);
}
public override string ToString()
{
if ( Input is ICharStream )
{
return "NoViableAltException('" + (char)UnexpectedType + "'@[" + GrammarDecisionDescription + "])";
}
else
{
return "NoViableAltException(" + UnexpectedType + "@[" + GrammarDecisionDescription + "])";
}
}
}
}
| 40.343373 | 175 | 0.652083 | [
"MIT"
] | MJRichardson/TypeSql | TypeSql/Parsing/Antlr/Antlr3.Runtime/NoViableAltException.cs | 6,697 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CS014UdalostiOsetreni
{
public partial class UdalostiOsetreniForm : Form
{
private int pocetUdalosti = 0;
public UdalostiOsetreniForm()
{
InitializeComponent();
}
private void UdalostZaznam(string zprava)
{
udalostiListBox.Items.Insert(0, String.Format("{0:D4} {1}", pocetUdalosti++, zprava)); // pocet++->pocet = pocet + 1
}
private string KurzorSouradnice(int x, int y)
{
return String.Format("X: {0:D3}, Y: {1:D3}", x, y);
}
private void UdalostiOsetreniForm_MouseMove(object sender, MouseEventArgs e)
{
souradniceLabel.Text = KurzorSouradnice(e.X, e.Y);
UdalostZaznam(string.Format("MouseMove {0}", KurzorSouradnice(e.X, e.Y)));
}
private void UdalostiOsetreniForm_MouseClick(object sender, MouseEventArgs e)
{
UdalostZaznam("MouseClick");
}
private void UdalostiOsetreniForm_MouseDown(object sender, MouseEventArgs e)
{
UdalostZaznam("MouseDown");
}
private void UdalostiOsetreniForm_MouseEnter(object sender, EventArgs e)
{
UdalostZaznam("MouseEnter");
}
private void UdalostiOsetreniForm_MouseLeave(object sender, EventArgs e)
{
UdalostZaznam("MouseLeave");
}
}
}
| 28.559322 | 130 | 0.60178 | [
"MIT"
] | FatildaIV/CS014UdalostiOsetreni | CS014UdalostiOsetreni/Form1.cs | 1,687 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
//资源加载模块
public class ResMgr : BaseManager<ResMgr>
{
//同步加载资源
public T Load<T>(string name) where T:Object{
T res = Resources.Load<T>(name); ;
//如果对象是一个GameObject类型的,我把它实例化后,再返回出去直接使用。
if (res is GameObject)
return GameObject.Instantiate(res);
else //else情况示例:TextAsset、AudioClip
return res;
}
//异步加载资源
public void LoadAsync<T>(string name,UnityAction<T> callback) where T:Object
{
//开启异步加载的协程
MonoMgr.GetInstance().StartCoroutine(ReallyLoadAsync<T>(name,callback));
}
private IEnumerator ReallyLoadAsync<T>(string name,UnityAction<T> callback) where T:Object{
ResourceRequest r=Resources.LoadAsync<T>(name);
yield return r;
if (r.asset is GameObject)
{
//实例化一下再传给方法
callback(GameObject.Instantiate(r.asset) as T);
}
else {
//直接传给方法
callback(r.asset as T);
}
}
}
| 26.853659 | 95 | 0.610354 | [
"MIT"
] | Kamen6666/Unity-FrameWork | Assets/Scripts/ProjectBase/Res/ResMgr.cs | 1,259 | C# |
namespace quicsharp
{
/// <summary>
/// Abstract class to define a frame. The payload of a packet is filled with one or more frames.
/// Different type of frame exist.
/// </summary>
public abstract class Frame
{
// Section 12.3 Table 3
public abstract byte Type { get; }
/// <summary>
/// Abstract method to encode a specific frame to a raw byte array
/// </summary>
/// <returns>The encoded frame</returns>
public abstract byte[] Encode();
/// <summary>
/// Abstract method to decode a specific from a raw byte array
/// </summary>
/// <param name="content">The raw byte array</param>
/// <param name="begin">The bit index of the byte array where the AckFrame is located</param>
/// <returns>The number of bits read</returns>
public abstract int Decode(byte[] payload, int begin);
}
}
| 34.444444 | 101 | 0.596774 | [
"MIT"
] | quicsharp/quicsharp | lib/Frame.cs | 932 | C# |
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Stride.Core.AssemblyProcessor.Serializers;
using Stride.Core.Serialization;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
namespace Stride.Core.AssemblyProcessor
{
internal partial class UpdateEngineProcessor : ICecilSerializerProcessor
{
private MethodDefinition updatableFieldGenericCtor;
private MethodDefinition updatableListUpdateResolverGenericCtor;
private MethodDefinition updatableArrayUpdateResolverGenericCtor;
private TypeDefinition updatablePropertyGenericType;
private MethodDefinition updatablePropertyGenericCtor;
private MethodDefinition updatablePropertyObjectGenericCtor;
private MethodDefinition parameterCollectionResolverInstantiateValueAccessor;
private MethodReference updateEngineRegisterMemberMethod;
private MethodReference updateEngineRegisterMemberResolverMethod;
private MethodReference getTypeFromHandleMethod;
int prepareMethodCount = 0;
private MethodDefinition CreateUpdateMethod(AssemblyDefinition assembly)
{
// Get or create method
var updateEngineType = GetOrCreateUpdateType(assembly, true);
var mainPrepareMethod = new MethodDefinition($"UpdateMain{prepareMethodCount++}", MethodAttributes.HideBySig | MethodAttributes.Assembly | MethodAttributes.Static, assembly.MainModule.TypeSystem.Void);
updateEngineType.Methods.Add(mainPrepareMethod);
// Make sure it is called at module startup
var strideCoreModule = assembly.GetStrideCoreModule();
var moduleInitializerAttribute = strideCoreModule.GetType("Stride.Core.ModuleInitializerAttribute");
var ctorMethod = moduleInitializerAttribute.GetConstructors().Single(x => !x.IsStatic && !x.HasParameters);
mainPrepareMethod.CustomAttributes.Add(new CustomAttribute(assembly.MainModule.ImportReference(ctorMethod)));
return mainPrepareMethod;
}
private MethodReference CreateDispatcher(AssemblyDefinition assembly, MethodReference method)
{
var updateEngineType = GetOrCreateUpdateType(assembly, true);
var dispatcherMethod = new MethodDefinition($"Dispatcher_{method.Name}", MethodAttributes.HideBySig | MethodAttributes.Assembly | MethodAttributes.Static, assembly.MainModule.ImportReference(method.ReturnType));
updateEngineType.Methods.Add(dispatcherMethod);
dispatcherMethod.Parameters.Add(new ParameterDefinition("this", Mono.Cecil.ParameterAttributes.None, method.DeclaringType));
foreach (var param in method.Parameters)
{
dispatcherMethod.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, param.ParameterType));
}
var il = dispatcherMethod.Body.GetILProcessor();
il.Emit(OpCodes.Ldarg_0);
foreach (var param in dispatcherMethod.Parameters.Skip(1)) // first parameter is "this"
{
il.Emit(OpCodes.Ldarg, param);
}
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldvirtftn, method);
var callsite = new Mono.Cecil.CallSite(method.ReturnType) { HasThis = true };
foreach (var param in method.Parameters)
callsite.Parameters.Add(param);
il.Emit(OpCodes.Calli, callsite);
il.Emit(OpCodes.Ret);
return dispatcherMethod;
}
public void ProcessSerializers(CecilSerializerContext context)
{
var references = new HashSet<AssemblyDefinition>();
EnumerateReferences(references, context.Assembly);
var coreAssembly = CecilExtensions.FindCorlibAssembly(context.Assembly);
// Only process assemblies depending on Stride.Engine
if (!references.Any(x => x.Name.Name == "Stride.Engine"))
{
// Make sure Stride.Engine.Serializers can access everything internally
var internalsVisibleToAttribute = coreAssembly.MainModule.GetTypeResolved(typeof(InternalsVisibleToAttribute).FullName);
var serializationAssemblyName = "Stride.Engine.Serializers";
// Add [InteralsVisibleTo] attribute
var internalsVisibleToAttributeCtor = context.Assembly.MainModule.ImportReference(internalsVisibleToAttribute.GetConstructors().Single());
var internalsVisibleAttribute = new CustomAttribute(internalsVisibleToAttributeCtor)
{
ConstructorArguments =
{
new CustomAttributeArgument(context.Assembly.MainModule.ImportReference(context.Assembly.MainModule.TypeSystem.String), serializationAssemblyName)
}
};
context.Assembly.CustomAttributes.Add(internalsVisibleAttribute);
return;
}
var strideEngineAssembly = context.Assembly.Name.Name == "Stride.Engine"
? context.Assembly
: context.Assembly.MainModule.AssemblyResolver.Resolve(new AssemblyNameReference("Stride.Engine", null));
var strideEngineModule = strideEngineAssembly.MainModule;
// Generate IL for Stride.Core
if (context.Assembly.Name.Name == "Stride.Engine")
{
ProcessStrideEngineAssembly(context);
}
var updatableFieldGenericType = strideEngineModule.GetType("Stride.Updater.UpdatableField`1");
updatableFieldGenericCtor = updatableFieldGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic);
updatablePropertyGenericType = strideEngineModule.GetType("Stride.Updater.UpdatableProperty`1");
updatablePropertyGenericCtor = updatablePropertyGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic);
var updatablePropertyObjectGenericType = strideEngineModule.GetType("Stride.Updater.UpdatablePropertyObject`1");
updatablePropertyObjectGenericCtor = updatablePropertyObjectGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic);
var updatableListUpdateResolverGenericType = strideEngineModule.GetType("Stride.Updater.ListUpdateResolver`1");
updatableListUpdateResolverGenericCtor = updatableListUpdateResolverGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic);
var updatableArrayUpdateResolverGenericType = strideEngineModule.GetType("Stride.Updater.ArrayUpdateResolver`1");
updatableArrayUpdateResolverGenericCtor = updatableArrayUpdateResolverGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic);
var parameterCollectionResolver = strideEngineModule.GetType("Stride.Engine.Design.ParameterCollectionResolver");
parameterCollectionResolverInstantiateValueAccessor = parameterCollectionResolver.Methods.First(x => x.Name == "InstantiateValueAccessor");
var registerMemberMethod = strideEngineModule.GetType("Stride.Updater.UpdateEngine").Methods.First(x => x.Name == "RegisterMember");
updateEngineRegisterMemberMethod = context.Assembly.MainModule.ImportReference(registerMemberMethod);
var registerMemberResolverMethod = strideEngineModule.GetType("Stride.Updater.UpdateEngine") .Methods.First(x => x.Name == "RegisterMemberResolver");
//pclVisitor.VisitMethod(registerMemberResolverMethod);
updateEngineRegisterMemberResolverMethod = context.Assembly.MainModule.ImportReference(registerMemberResolverMethod);
var typeType = coreAssembly.MainModule.GetTypeResolved(typeof(Type).FullName);
getTypeFromHandleMethod = context.Assembly.MainModule.ImportReference(typeType.Methods.First(x => x.Name == "GetTypeFromHandle"));
var mainPrepareMethod = CreateUpdateMethod(context.Assembly);
// Emit serialization code for all the types we care about
var processedTypes = new HashSet<TypeDefinition>(TypeReferenceEqualityComparer.Default);
foreach (var serializableType in context.SerializableTypesProfiles.SelectMany(x => x.Value.SerializableTypes))
{
// Special case: when processing Stride.Engine assembly, we automatically add dependent assemblies types too
if (!serializableType.Value.Local && strideEngineAssembly != context.Assembly)
continue;
var typeDefinition = serializableType.Key as TypeDefinition;
if (typeDefinition == null)
continue;
// Ignore already processed types
if (!processedTypes.Add(typeDefinition))
continue;
try
{
ProcessType(context, context.Assembly.MainModule.ImportReference(typeDefinition), mainPrepareMethod);
}
catch (Exception e)
{
throw new InvalidOperationException(string.Format("Error when generating update engine code for {0}", typeDefinition), e);
}
}
// Force generic instantiations
var il = mainPrepareMethod.Body.GetILProcessor();
foreach (var serializableType in context.SerializableTypesProfiles.SelectMany(x => x.Value.SerializableTypes).ToArray())
{
// Special case: when processing Stride.Engine assembly, we automatically add dependent assemblies types too
if (!serializableType.Value.Local && strideEngineAssembly != context.Assembly)
continue;
// Try to find if original method definition was generated
var typeDefinition = serializableType.Key.Resolve();
// If using List<T>, register this type in UpdateEngine
var parentTypeDefinition = typeDefinition;
while(parentTypeDefinition != null)
{
var listInterfaceType = parentTypeDefinition.Interfaces.Select(x => x.InterfaceType).OfType<GenericInstanceType>().FirstOrDefault(x => x.ElementType.FullName == typeof(IList<>).FullName);
if (listInterfaceType != null)
{
//call Updater.UpdateEngine.RegisterMemberResolver(new Updater.ListUpdateResolver<T>());
var elementType = ResolveGenericsVisitor.Process(serializableType.Key, listInterfaceType.GenericArguments[0]);
il.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(updatableListUpdateResolverGenericCtor).MakeGeneric(context.Assembly.MainModule.ImportReference(elementType)));
il.Emit(OpCodes.Call, updateEngineRegisterMemberResolverMethod);
}
parentTypeDefinition = parentTypeDefinition.BaseType?.Resolve();
}
// Same for arrays
var arrayType = serializableType.Key as ArrayType;
if (arrayType != null)
{
//call Updater.UpdateEngine.RegisterMemberResolver(new Updater.ArrayUpdateResolver<T>());
var elementType = ResolveGenericsVisitor.Process(serializableType.Key, arrayType.ElementType);
il.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(updatableArrayUpdateResolverGenericCtor).MakeGeneric(context.Assembly.MainModule.ImportReference(elementType)));
il.Emit(OpCodes.Call, updateEngineRegisterMemberResolverMethod);
}
// Generic instantiation for AOT platforms
if (context.Platform == Core.PlatformType.iOS && serializableType.Key.Name == "ValueParameterKey`1")
{
var keyType = ((GenericInstanceType)serializableType.Key).GenericArguments[0];
il.Emit(OpCodes.Call, context.Assembly.MainModule.ImportReference(parameterCollectionResolverInstantiateValueAccessor).MakeGenericMethod(context.Assembly.MainModule.ImportReference(keyType)));
}
var genericInstanceType = serializableType.Key as GenericInstanceType;
if (genericInstanceType != null)
{
var expectedUpdateMethodName = ComputeUpdateMethodName(typeDefinition);
var updateMethod = GetOrCreateUpdateType(typeDefinition.Module.Assembly, false)?.Methods.FirstOrDefault(x => x.Name == expectedUpdateMethodName && x.HasGenericParameters && x.GenericParameters.Count == genericInstanceType.GenericParameters.Count);
// If nothing was found in main assembly, also look in Stride.Engine assembly, just in case (it might defines some shared/corlib types -- currently not the case)
if (updateMethod == null)
{
updateMethod = GetOrCreateUpdateType(strideEngineAssembly, false)?.Methods.FirstOrDefault(x => x.Name == expectedUpdateMethodName && x.HasGenericParameters && x.GenericParameters.Count == genericInstanceType.GenericParameters.Count);
}
if (updateMethod != null)
{
// Emit call to update engine setup method with generic arguments of current type
il.Emit(OpCodes.Call, context.Assembly.MainModule.ImportReference(updateMethod)
.MakeGenericMethod(genericInstanceType.GenericArguments
.Select(context.Assembly.MainModule.ImportReference)
.ToArray()));
}
}
}
il.Emit(OpCodes.Ret);
}
public void ProcessType(CecilSerializerContext context, TypeReference type, MethodDefinition updateMainMethod)
{
var typeDefinition = type.Resolve();
// No need to process enum
if (typeDefinition.IsEnum)
return;
var updateCurrentMethod = updateMainMethod;
ResolveGenericsVisitor replaceGenericsVisitor = null;
if (typeDefinition.HasGenericParameters)
{
// Make a prepare method for just this object since it might need multiple instantiation
updateCurrentMethod = new MethodDefinition(ComputeUpdateMethodName(typeDefinition), MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Static, context.Assembly.MainModule.TypeSystem.Void);
var genericsMapping = new Dictionary<TypeReference, TypeReference>();
foreach (var genericParameter in typeDefinition.GenericParameters)
{
var genericParameterCopy = new GenericParameter(genericParameter.Name, updateCurrentMethod)
{
Attributes = genericParameter.Attributes,
};
foreach (var constraint in genericParameter.Constraints)
genericParameterCopy.Constraints.Add(new GenericParameterConstraint(context.Assembly.MainModule.ImportReference(constraint.ConstraintType)));
updateCurrentMethod.GenericParameters.Add(genericParameterCopy);
genericsMapping[genericParameter] = genericParameterCopy;
}
replaceGenericsVisitor = new ResolveGenericsVisitor(genericsMapping);
updateMainMethod.DeclaringType.Methods.Add(updateCurrentMethod);
}
var il = updateCurrentMethod.Body.GetILProcessor();
var typeIsValueType = type.IsResolvedValueType();
var emptyObjectField = typeIsValueType ? null : updateMainMethod.DeclaringType.Fields.FirstOrDefault(x => x.Name == "emptyObject");
VariableDefinition emptyStruct = null;
// Note: forcing fields and properties to be processed in all cases
foreach (var serializableItem in ComplexSerializerRegistry.GetSerializableItems(type, true, ComplexTypeSerializerFlags.SerializePublicFields | ComplexTypeSerializerFlags.SerializePublicProperties | ComplexTypeSerializerFlags.Updatable))
{
if (serializableItem.MemberInfo is FieldReference fieldReference)
{
var field = fieldReference.Resolve();
// First time it is needed, let's create empty object in the class (var emptyObject = new object()) or empty local struct in the method
if (typeIsValueType)
{
if (emptyStruct == null)
{
emptyStruct = new VariableDefinition(type);
updateMainMethod.Body.Variables.Add(emptyStruct);
}
}
else
{
if (emptyObjectField == null)
{
emptyObjectField = new FieldDefinition("emptyObject", FieldAttributes.Static | FieldAttributes.Private, context.Assembly.MainModule.TypeSystem.Object);
// Create static ctor that will initialize this object
var staticConstructor = new MethodDefinition(".cctor",
MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
context.Assembly.MainModule.TypeSystem.Void);
var staticConstructorIL = staticConstructor.Body.GetILProcessor();
staticConstructorIL.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(emptyObjectField.FieldType.Resolve().GetConstructors().Single(x => !x.IsStatic && !x.HasParameters)));
staticConstructorIL.Emit(OpCodes.Stsfld, emptyObjectField);
staticConstructorIL.Emit(OpCodes.Ret);
updateMainMethod.DeclaringType.Fields.Add(emptyObjectField);
updateMainMethod.DeclaringType.Methods.Add(staticConstructor);
}
}
il.Emit(OpCodes.Ldtoken, type);
il.Emit(OpCodes.Call, getTypeFromHandleMethod);
il.Emit(OpCodes.Ldstr, field.Name);
if (typeIsValueType)
il.Emit(OpCodes.Ldloca, emptyStruct);
else
il.Emit(OpCodes.Ldsfld, emptyObjectField);
il.Emit(OpCodes.Ldflda, context.Assembly.MainModule.ImportReference(fieldReference));
il.Emit(OpCodes.Conv_I);
if (typeIsValueType)
il.Emit(OpCodes.Ldloca, emptyStruct);
else
il.Emit(OpCodes.Ldsfld, emptyObjectField);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Conv_I4);
var fieldType = context.Assembly.MainModule.ImportReference(replaceGenericsVisitor != null ? replaceGenericsVisitor.VisitDynamic(field.FieldType) : field.FieldType);
il.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(updatableFieldGenericCtor).MakeGeneric(fieldType));
il.Emit(OpCodes.Call, updateEngineRegisterMemberMethod);
}
var propertyReference = serializableItem.MemberInfo as PropertyReference;
if (propertyReference != null)
{
var property = propertyReference.Resolve();
var propertyGetMethod = context.Assembly.MainModule.ImportReference(property.GetMethod).MakeGeneric(updateCurrentMethod.GenericParameters.ToArray());
il.Emit(OpCodes.Ldtoken, type);
il.Emit(OpCodes.Call, getTypeFromHandleMethod);
il.Emit(OpCodes.Ldstr, property.Name);
// If it's a virtual or interface call, we need to create a dispatcher using ldvirtftn
if (property.GetMethod.IsVirtual)
propertyGetMethod = CreateDispatcher(context.Assembly, propertyGetMethod);
il.Emit(OpCodes.Ldftn, propertyGetMethod);
// Set whether getter method uses a VirtualDispatch (static call) or instance call
il.Emit(property.GetMethod.IsVirtual ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
// Only uses setter if it exists and it's public
if (property.SetMethod != null && property.SetMethod.IsPublic)
{
var propertySetMethod = context.Assembly.MainModule.ImportReference(property.SetMethod).MakeGeneric(updateCurrentMethod.GenericParameters.ToArray());
if (property.SetMethod.IsVirtual)
propertySetMethod = CreateDispatcher(context.Assembly, propertySetMethod);
il.Emit(OpCodes.Ldftn, propertySetMethod);
}
else
{
// 0 (native int)
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Conv_I);
}
// Set whether setter method uses a VirtualDispatch (static call) or instance call
il.Emit((property.SetMethod?.IsVirtual ?? false) ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
var propertyType = context.Assembly.MainModule.ImportReference(replaceGenericsVisitor != null ? replaceGenericsVisitor.VisitDynamic(property.PropertyType) : property.PropertyType);
var updatablePropertyInflatedCtor = GetOrCreateUpdatablePropertyCtor(context.Assembly, propertyType);
il.Emit(OpCodes.Newobj, updatablePropertyInflatedCtor);
il.Emit(OpCodes.Call, updateEngineRegisterMemberMethod);
}
}
if (updateCurrentMethod != updateMainMethod)
{
// If we have a local method, close it
il.Emit(OpCodes.Ret);
// Also call it from main method if it was a closed generic instantiation
if (type is GenericInstanceType)
{
il = updateMainMethod.Body.GetILProcessor();
il.Emit(OpCodes.Call, updateCurrentMethod.MakeGeneric(((GenericInstanceType)type).GenericArguments.Select(context.Assembly.MainModule.ImportReference).ToArray()));
}
}
}
private static string ComputeUpdateMethodName(TypeDefinition typeDefinition)
{
var typeName = ComputeTypeName(typeDefinition);
return string.Format("UpdateGeneric_{0}", typeName);
}
private static string ComputeTypeName(TypeDefinition typeDefinition)
{
var typeName = typeDefinition.FullName.Replace(".", "_");
var typeNameGenericPart = typeName.IndexOf("`");
if (typeNameGenericPart != -1)
typeName = typeName.Substring(0, typeNameGenericPart);
return typeName;
}
private static TypeDefinition GetOrCreateUpdateType(AssemblyDefinition assembly, bool createIfNotExists)
{
// Get or create module static constructor
var updateEngineType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == "UpdateEngineAutoGenerated");
if (updateEngineType == null && createIfNotExists)
{
updateEngineType = new TypeDefinition(string.Empty, "UpdateEngineAutoGenerated", TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass);
updateEngineType.BaseType = assembly.MainModule.TypeSystem.Object;
assembly.MainModule.Types.Add(updateEngineType);
}
return updateEngineType;
}
public MethodReference GetOrCreateUpdatablePropertyCtor(AssemblyDefinition assembly, TypeReference propertyType)
{
// Use different type depending on if type is a struct or not
var updatablePropertyGenericType =
(propertyType.IsResolvedValueType() && (!propertyType.IsGenericInstance ||
((GenericInstanceType) propertyType).ElementType.FullName !=
typeof(Nullable<>).FullName))
? updatablePropertyGenericCtor
: updatablePropertyObjectGenericCtor;
return assembly.MainModule.ImportReference(updatablePropertyGenericType).MakeGeneric(propertyType);
}
private static void EnumerateReferences(HashSet<AssemblyDefinition> assemblies, AssemblyDefinition assembly)
{
// Already processed?
if (!assemblies.Add(assembly))
return;
// Let's recurse over referenced assemblies
foreach (var referencedAssemblyName in assembly.MainModule.AssemblyReferences.ToArray())
{
// Avoid processing system assemblies
// TODO: Scan what is actually in framework folders
if (referencedAssemblyName.Name == "mscorlib" || referencedAssemblyName.Name.StartsWith("System")
|| referencedAssemblyName.FullName.Contains("PublicKeyToken=31bf3856ad364e35")) // Signed with Microsoft public key (likely part of system libraries)
continue;
try
{
var referencedAssembly = assembly.MainModule.AssemblyResolver.Resolve(referencedAssemblyName);
EnumerateReferences(assemblies, referencedAssembly);
}
catch (AssemblyResolutionException)
{
}
}
}
}
};
| 55.610766 | 267 | 0.637267 | [
"MIT"
] | Aggror/Stride | sources/core/Stride.Core.AssemblyProcessor/UpdateEngineProcessor.cs | 26,860 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TopBarTurnCountGUI : MonoBehaviour
{
[SerializeField] TextIconGUI Display;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Display.Value = ((GameModeBase.Instance.CurrentTurn == 0 ? GameModeBase.Instance.CurrentTurn : GameModeBase.Instance.CurrentTurn / 2 ) + 1).ToString();
}
}
| 23.619048 | 159 | 0.685484 | [
"MIT"
] | geldoronie/the-azure-lux-game-jam-2021 | Assets/Scripts/GUI/TopBarTurnCountGUI.cs | 496 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualMachineScaleSetVMsOperations operations.
/// </summary>
internal partial class VirtualMachineScaleSetVMsOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineScaleSetVMsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineScaleSetVMsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualMachineScaleSetVMsOperations(ComputeManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ComputeManagementClient
/// </summary>
public ComputeManagementClient Client { get; private set; }
/// <summary>
/// Reimages (upgrade the operating system) a specific virtual machine in a VM
/// scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginReimageWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, tempDisk, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Allows you to re-image all the disks ( including data disks ) in the a VM
/// scale set instance. This operation is only supported for managed disks.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> ReimageAllWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginReimageAllWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deallocates a specific virtual machine in a VM scale set. Shuts down the
/// virtual machine and releases the compute resources it uses. You are not
/// billed for the compute resources of this virtual machine once it is
/// deallocated.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a virtual machine of a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set where the extension should be create or
/// updated.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Scale Sets VM operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualMachineScaleSetVM>> UpdateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, VirtualMachineScaleSetVM parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualMachineScaleSetVM> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='forceDeletion'>
/// Optional parameter to force delete a virtual machine from a VM scale set.
/// (Feature in Preview)
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? forceDeletion = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, forceDeletion, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualMachineScaleSetVM>> GetWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, InstanceViewTypes? expand = default(InstanceViewTypes?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("expand", expand);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(expand, Client.SerializationSettings).Trim('"'))));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualMachineScaleSetVM>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineScaleSetVM>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the status of a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualMachineScaleSetVMInstanceView>> GetInstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInstanceView", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualMachineScaleSetVMInstanceView>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineScaleSetVMInstanceView>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of all virtual machines in a VM scale sets.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// The list parameters. Allowed values are 'instanceView',
/// 'instanceView/statuses'.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, ODataQuery<VirtualMachineScaleSetVM> odataQuery = default(ODataQuery<VirtualMachineScaleSetVM>), string select = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualMachineScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualMachineScaleSetName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualMachineScaleSetName", virtualMachineScaleSetName);
tracingParameters.Add("select", select);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualMachineScaleSetName}", System.Uri.EscapeDataString(virtualMachineScaleSetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<VirtualMachineScaleSetVM>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Power off (stop) a virtual machine in a VM scale set. Note that resources
/// are still attached and you are getting charged for the resources. Instead,
/// use deallocate to release resources and avoid charges.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, skipShutdown, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Restarts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> RestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginRestartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStartWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Shuts down the virtual machine in the virtual machine scale set, moves it
/// to a new node, and powers it back on.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> RedeployWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginRedeployWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to retrieve SAS URIs of boot diagnostic logs for a virtual
/// machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='sasUriExpirationTimeInMinutes'>
/// Expiration duration in minutes for the SAS URIs with a value between 1 to
/// 1440 minutes. <br><br>NOTE: If not specified, SAS URIs will be
/// generated with a default expiration duration of 120 minutes.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RetrieveBootDiagnosticsDataResult>> RetrieveBootDiagnosticsDataWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, int? sasUriExpirationTimeInMinutes = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("sasUriExpirationTimeInMinutes", sasUriExpirationTimeInMinutes);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RetrieveBootDiagnosticsData", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/retrieveBootDiagnosticsData").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (sasUriExpirationTimeInMinutes != null)
{
_queryParameters.Add(string.Format("sasUriExpirationTimeInMinutes={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(sasUriExpirationTimeInMinutes, Client.SerializationSettings).Trim('"'))));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RetrieveBootDiagnosticsDataResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RetrieveBootDiagnosticsDataResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Performs maintenance on a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> PerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginPerformMaintenanceWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to simulate the eviction of spot virtual machine in a VM
/// scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> SimulateEvictionWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "SimulateEviction", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/simulateEviction").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Run command on a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RunCommandResult>> RunCommandWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<RunCommandResult> _response = await BeginRunCommandWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, instanceId, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reimages (upgrade the operating system) a specific virtual machine in a VM
/// scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
VirtualMachineScaleSetVMReimageParameters vmScaleSetVMReimageInput = default(VirtualMachineScaleSetVMReimageParameters);
if (tempDisk != null)
{
vmScaleSetVMReimageInput = new VirtualMachineScaleSetVMReimageParameters();
vmScaleSetVMReimageInput.TempDisk = tempDisk;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vmScaleSetVMReimageInput", vmScaleSetVMReimageInput);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginReimage", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(vmScaleSetVMReimageInput != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(vmScaleSetVMReimageInput, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Allows you to re-image all the disks ( including data disks ) in the a VM
/// scale set instance. This operation is only supported for managed disks.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginReimageAllWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginReimageAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deallocates a specific virtual machine in a VM scale set. Shuts down the
/// virtual machine and releases the compute resources it uses. You are not
/// billed for the compute resources of this virtual machine once it is
/// deallocated.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDeallocate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a virtual machine of a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set where the extension should be create or
/// updated.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine Scale Sets VM operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualMachineScaleSetVM>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, VirtualMachineScaleSetVM parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualMachineScaleSetVM>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineScaleSetVM>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineScaleSetVM>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='forceDeletion'>
/// Optional parameter to force delete a virtual machine from a VM scale set.
/// (Feature in Preview)
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? forceDeletion = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("forceDeletion", forceDeletion);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (forceDeletion != null)
{
_queryParameters.Add(string.Format("forceDeletion={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(forceDeletion, Client.SerializationSettings).Trim('"'))));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Power off (stop) a virtual machine in a VM scale set. Note that resources
/// are still attached and you are getting charged for the resources. Instead,
/// use deallocate to release resources and avoid charges.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("skipShutdown", skipShutdown);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPowerOff", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (skipShutdown != null)
{
_queryParameters.Add(string.Format("skipShutdown={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(skipShutdown, Client.SerializationSettings).Trim('"'))));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Restarts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRestart", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Starts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStart", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Shuts down the virtual machine in the virtual machine scale set, moves it
/// to a new node, and powers it back on.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginRedeployWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRedeploy", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/redeploy").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Performs maintenance on a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginPerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPerformMaintenance", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/performMaintenance").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Run command on a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RunCommandResult>> BeginRunCommandWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vmScaleSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vmScaleSetName");
}
if (instanceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "instanceId");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vmScaleSetName", vmScaleSetName);
tracingParameters.Add("instanceId", instanceId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRunCommand", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/runCommand").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vmScaleSetName}", System.Uri.EscapeDataString(vmScaleSetName));
_url = _url.Replace("{instanceId}", System.Uri.EscapeDataString(instanceId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RunCommandResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RunCommandResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of all virtual machines in a VM scale sets.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<VirtualMachineScaleSetVM>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 48.188445 | 420 | 0.575915 | [
"MIT"
] | AlonsoMondal/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/VirtualMachineScaleSetVMsOperations.cs | 178,490 | C# |
namespace ShogiCore.Book {
partial class BookEditControl {
/// <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 コンポーネント デザイナで生成されたコード
/// <summary>
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
/// </summary>
private void InitializeComponent() {
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.treeView1 = new System.Windows.Forms.TreeView();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.blunderViewControl1 = new ShogiCore.Drawing.BlunderViewControl();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.treeView1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.numericUpDown1);
this.splitContainer1.Panel2.Controls.Add(this.label2);
this.splitContainer1.Panel2.Controls.Add(this.label1);
this.splitContainer1.Panel2.Controls.Add(this.blunderViewControl1);
this.splitContainer1.Size = new System.Drawing.Size(848, 556);
this.splitContainer1.SplitterDistance = 251;
this.splitContainer1.TabIndex = 0;
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.FullRowSelect = true;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(251, 556);
this.treeView1.TabIndex = 0;
this.treeView1.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand);
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(96, 496);
this.numericUpDown1.Maximum = new decimal(new int[] {
32767,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(120, 19);
this.numericUpDown1.TabIndex = 2;
this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(239, 504);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(163, 12);
this.label2.TabIndex = 1;
this.label2.Text = "(0 ~ 32767。0の手は指さない。)";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(40, 504);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 12);
this.label1.TabIndex = 1;
this.label1.Text = "評価値";
//
// blunderViewControl1
//
this.blunderViewControl1.BackColor = System.Drawing.Color.Transparent;
this.blunderViewControl1.Location = new System.Drawing.Point(8, 8);
this.blunderViewControl1.Name = "blunderViewControl1";
this.blunderViewControl1.Size = new System.Drawing.Size(578, 460);
this.blunderViewControl1.TabIndex = 0;
//
// BookEditControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.splitContainer1);
this.Name = "BookEditControl";
this.Size = new System.Drawing.Size(848, 556);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView treeView1;
private ShogiCore.Drawing.BlunderViewControl blunderViewControl1;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
}
}
| 44.654412 | 124 | 0.599868 | [
"MIT"
] | ak110/Blunder.BookEditor | Blunder.BookEditor/Book/BookEditControl.Designer.cs | 6,363 | C# |
namespace YoulessNet {
using System.Runtime.Serialization;
/// <summary>
/// Represents the current status of the Youless energy meter
/// </summary>
[DataContract]
public class YoulessStatus {
/// <summary>
/// Gets the total amount of energy used (in <c>kWh</c>)
/// </summary>
[IgnoreDataMember]
public double TotalCounter { get; set; }
/// <summary>
/// Gets the current power usage (in <c>W</c>)
/// </summary>
[DataMember(Name = "pwr")]
public int CurrentUsage { get; set; }
/// <summary>
/// Gets the luminosity of the reflection (in case of analog meters)
/// </summary>
[DataMember(Name = "lvl")]
public int? MovingAverageLevel { get; set; }
/// <summary>
/// Gets the difference in percents of the <see cref="MovingAverageLevel"/>
/// </summary>
[IgnoreDataMember]
public int? ReflectionDeviation { get; set; }
/// <summary>
/// Gets the time in seconds until the next online status update
/// </summary>
[IgnoreDataMember]
public int NextOnlineStatusUpdate { get; set; }
/// <summary>
/// Gets the connection status of the youless
/// </summary>
[IgnoreDataMember]
public YoulessConnectionStatus ConnectionStatus { get; set; }
}
} | 32 | 83 | 0.557639 | [
"MIT"
] | Sebazzz/Youless.NET | src/YoulessNet/YoulessStatus.cs | 1,442 | C# |
using System;
public class Task02_5
{
private static void Main()
{
Console.WriteLine("Task 2.5. Employee");
Employee employee = new Employee();
Console.Write("Enter your first name: ");
employee.FirstName = Console.ReadLine();
Console.Write("Enter your patronymic: ");
employee.Patronymic = Console.ReadLine();
Console.Write("Enter your last name: ");
employee.LastName = Console.ReadLine();
Console.Write("Enter your date of birth: ");
DateTime dateOfBirth;
if (!DateTime.TryParse(Console.ReadLine(), out dateOfBirth))
{
Console.WriteLine("Incorrect value");
return;
}
Console.WriteLine("Enter your appointment: ");
employee.Appointment = Console.ReadLine();
Console.Write("Enter your working experience (in years): ");
int experience;
if (!int.TryParse(Console.ReadLine(), out experience))
{
Console.WriteLine("Incorrect value");
return;
}
try
{
employee.DateOfBirth = dateOfBirth;
employee.Experience = experience;
Console.WriteLine($"Your age is {employee.Age} years. You have been working as a {employee.Appointment} for {experience} years.");
}
catch (ArgumentException exc)
{
Console.WriteLine(exc.Message);
}
}
} | 28.92 | 142 | 0.583679 | [
"MIT"
] | Andrei-Kekov/XT-2018Q4 | Epam.Task02/Epam.Task02.05_Employee/Demo.cs | 1,448 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataMigration.V20180315Preview.Outputs
{
/// <summary>
/// Input for the task that validates connection to SQL Server and also validates source server requirements
/// </summary>
[OutputType]
public sealed class ConnectToSourceSqlServerTaskInputResponse
{
/// <summary>
/// Permission group for validations
/// </summary>
public readonly string? CheckPermissionsGroup;
/// <summary>
/// Connection information for Source SQL Server
/// </summary>
public readonly Outputs.SqlConnectionInfoResponse SourceConnectionInfo;
[OutputConstructor]
private ConnectToSourceSqlServerTaskInputResponse(
string? checkPermissionsGroup,
Outputs.SqlConnectionInfoResponse sourceConnectionInfo)
{
CheckPermissionsGroup = checkPermissionsGroup;
SourceConnectionInfo = sourceConnectionInfo;
}
}
}
| 32.820513 | 112 | 0.692969 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataMigration/V20180315Preview/Outputs/ConnectToSourceSqlServerTaskInputResponse.cs | 1,280 | C# |
namespace Microsoft.Marketplace.SaaS.SDK.Services.Models
{
/// <summary>
/// Enumerator witrh new status.
/// </summary>
public enum SubscriptionStatusEnumExtension
{
/// <summary>
/// The pending fulfillment start
/// </summary>
PendingFulfillmentStart,
/// <summary>
/// The subscribed
/// </summary>
Subscribed,
/// <summary>
/// The unsubscribed
/// </summary>
Unsubscribed,
/// <summary>
/// The not started
/// </summary>
NotStarted,
/// <summary>
/// Pending Activation
/// </summary>
PendingActivation,
/// <summary>
/// The pending unsubscribe
/// </summary>
PendingUnsubscribe,
/// <summary>
/// The activation failed
/// </summary>
ActivationFailed,
/// <summary>
/// The unsubscribe failed
/// </summary>
UnsubscribeFailed,
/// <summary>
/// The Suspend
/// </summary>
Suspend,
}
}
| 20.685185 | 57 | 0.482543 | [
"MIT"
] | Azure/Commercial-Marketplace-SaaS-Accelerator | src/SaaS.SDK.Services/Models/SubscriptionStatusEnumExtension.cs | 1,119 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Octopus.Cli.Commands.Deployment;
using Octopus.Cli.Diagnostics;
using Octopus.Cli.Infrastructure;
using Octopus.Cli.Repositories;
using Octopus.Cli.Util;
using Octopus.Client;
using Octopus.Client.Exceptions;
using Octopus.Client.Model;
using Serilog;
using Serilog.Events;
namespace Octopus.Cli.Commands.Releases
{
[Command("create-release", Description = "Creates (and, optionally, deploys) a release.")]
public class CreateReleaseCommand : DeploymentCommandBase, ISupportFormattedOutput
{
private readonly IReleasePlanBuilder releasePlanBuilder;
ReleaseResource release;
ProjectResource project;
ReleasePlan plan;
string versionNumber;
public CreateReleaseCommand(IOctopusAsyncRepositoryFactory repositoryFactory, IOctopusFileSystem fileSystem, IPackageVersionResolver versionResolver, IReleasePlanBuilder releasePlanBuilder, IOctopusClientFactory clientFactory, ICommandOutputProvider commandOutputProvider)
: base(repositoryFactory, fileSystem, clientFactory, commandOutputProvider)
{
this.releasePlanBuilder = releasePlanBuilder;
var options = Options.For("Release creation");
options.Add<string>("project=", "Name or ID of the project", v => ProjectNameOrId = v);
options.Add<string>("defaultPackageVersion=|packageVersion=", "Default version number of all packages to use for this release. Override per-package using --package.", versionResolver.Default);
options.Add<string>("version=|releaseNumber=", "[Optional] Release number to use for the new release.", v => VersionNumber = v);
options.Add<string>("channel=", "[Optional] Name or ID of the channel to use for the new release. Omit this argument to automatically select the best channel.", v => ChannelNameOrId = v);
options.Add<string>("package=", "[Optional] Version number to use for a package in the release. Format: StepName:Version or PackageID:Version or StepName:PackageName:Version. StepName, PackageID, and PackageName can be replaced with an asterisk. An asterisk will be assumed for StepName, PackageID, or PackageName if they are omitted.", v => versionResolver.Add(v));
options.Add<string>("packagesFolder=", "[Optional] A folder containing NuGet packages from which we should get versions.", v => {v.CheckForIllegalPathCharacters("packagesFolder"); versionResolver.AddFolder(v);});
options.Add<string>("releaseNotes=", "[Optional] Release Notes for the new release. Styling with Markdown is supported.", v => ReleaseNotes = v);
options.Add<string>("releaseNoteFile=|releaseNotesFile=", "[Optional] Path to a file that contains Release Notes for the new release. Supports Markdown files.", ReadReleaseNotesFromFile);
options.Add<bool>("ignoreExisting", "[Optional, Flag] Don't create this release if there is already one with the same version number.", v => IgnoreIfAlreadyExists = true);
options.Add<bool>("ignoreChannelRules", "[Optional, Flag] Create the release ignoring any version rules specified by the channel.", v => IgnoreChannelRules = true);
options.Add<string>("packagePrerelease=", "[Optional] Pre-release for latest version of all packages to use for this release.", v => VersionPreReleaseTag = v);
options.Add<bool>("whatIf", "[Optional, Flag] Perform a dry run but don't actually create/deploy release.", v => WhatIf = true);
options = Options.For("Deployment");
options.Add<string>("deployTo=", "[Optional] Name or ID of the environment to automatically deploy to, e.g., 'Production' or 'Environments-1'; specify this argument multiple times to deploy to multiple environments.", v => DeployToEnvironmentNamesOrIds.Add(v));
}
public string ChannelNameOrId { get; set; }
public string VersionNumber { get; set; }
public string ReleaseNotes { get; set; }
public bool IgnoreIfAlreadyExists { get; set; }
public bool IgnoreChannelRules { get; set; }
public string VersionPreReleaseTag { get; set; }
public bool WhatIf { get; set; }
protected override async Task ValidateParameters()
{
if (!string.IsNullOrWhiteSpace(ChannelNameOrId) && !await Repository.SupportsChannels().ConfigureAwait(false))
throw new CommandException("Your Octopus Server does not support channels, which was introduced in Octopus 3.2. Please upgrade your Octopus Server, or remove the --channel argument.");
await base.ValidateParameters();
}
public async Task Request()
{
var serverSupportsChannels = await ServerSupportsChannels();
commandOutputProvider.Debug(serverSupportsChannels ? "This Octopus Server supports channels" : "This Octopus Server does not support channels");
project = await Repository.Projects.FindByNameOrIdOrFail(ProjectNameOrId).ConfigureAwait(false);
plan = await BuildReleasePlan(project).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(VersionNumber))
{
versionNumber = VersionNumber;
commandOutputProvider.Debug("Using version number provided on command-line: {Version:l}", versionNumber);
}
else if (!string.IsNullOrWhiteSpace(plan.ReleaseTemplate.NextVersionIncrement))
{
versionNumber = plan.ReleaseTemplate.NextVersionIncrement;
commandOutputProvider.Debug("Using version number from release template: {Version:l}", versionNumber);
}
else if (!string.IsNullOrWhiteSpace(plan.ReleaseTemplate.VersioningPackageStepName))
{
versionNumber = plan.GetActionVersionNumber(plan.ReleaseTemplate.VersioningPackageStepName, plan.ReleaseTemplate.VersioningPackageReferenceName);
commandOutputProvider.Debug("Using version number from package step: {Version:l}", versionNumber);
}
else
{
throw new CommandException(
"A version number was not specified and could not be automatically selected.");
}
commandOutputProvider.Write(
plan.IsViableReleasePlan() ? LogEventLevel.Information : LogEventLevel.Warning,
"Release plan for {Project:l} {Version:l}" + System.Environment.NewLine + "{Plan:l}",
project.Name, versionNumber, plan.FormatAsTable()
);
if (plan.HasUnresolvedSteps())
{
throw new CommandException(
"Package versions could not be resolved for one or more of the package packageSteps in this release. See the errors above for details. Either ensure the latest version of the package can be automatically resolved, or set the version to use specifically by using the --package argument.");
}
if (plan.ChannelHasAnyEnabledSteps() == false)
{
if (serverSupportsChannels)
{
throw new CommandException($"Channel {plan.Channel.Name} has no available steps");
}
else
{
throw new CommandException($"Plan has no available steps");
}
}
if (plan.HasStepsViolatingChannelVersionRules())
{
if (IgnoreChannelRules)
{
commandOutputProvider.Warning("At least one step violates the package version rules for the Channel '{Channel:l}'. Forcing the release to be created ignoring these rules...", plan.Channel.Name);
}
else
{
throw new CommandException(
$"At least one step violates the package version rules for the Channel '{plan.Channel.Name}'. Either correct the package versions for this release, let Octopus select the best channel by omitting the --channel argument, select a different channel using --channel=MyChannel argument, or ignore these version rules altogether by using the --ignoreChannelRules argument.");
}
}
if (IgnoreIfAlreadyExists)
{
commandOutputProvider.Debug("Checking for existing release for {Project:l} {Version:l} because you specified --ignoreExisting...", project.Name, versionNumber);
try
{
var found = await Repository.Projects.GetReleaseByVersion(project, versionNumber)
.ConfigureAwait(false);
if (found != null)
{
commandOutputProvider.Information("A release of {Project:l} with the number {Version:l} already exists, and you specified --ignoreExisting, so we won't even attempt to create the release.", project.Name, versionNumber);
return;
}
}
catch (OctopusResourceNotFoundException)
{
// Expected
commandOutputProvider.Debug("No release exists - the coast is clear!");
}
}
if (WhatIf)
{
// We were just doing a dry run - bail out here
if (DeployToEnvironmentNamesOrIds.Any())
commandOutputProvider.Information("[WhatIf] This release would have been created using the release plan and deployed to {Environments:l}", DeployToEnvironmentNamesOrIds.CommaSeperate());
else
commandOutputProvider.Information("[WhatIf] This release would have been created using the release plan");
}
else
{
// Actually create the release!
commandOutputProvider.Debug("Creating release...");
// if no release notes were provided on the command line, but the project has a template, then use the template
if (string.IsNullOrWhiteSpace(ReleaseNotes) && !string.IsNullOrWhiteSpace(project.ReleaseNotesTemplate))
{
ReleaseNotes = project.ReleaseNotesTemplate;
}
release = await Repository.Releases.Create(new ReleaseResource(versionNumber, project.Id, plan.Channel?.Id)
{
ReleaseNotes = ReleaseNotes,
SelectedPackages = plan.GetSelections()
}, ignoreChannelRules: IgnoreChannelRules)
.ConfigureAwait(false);
commandOutputProvider.Information("Release {Version:l} created successfully!", release.Version);
commandOutputProvider.ServiceMessage("setParameter", new { name = "octo.releaseNumber", value = release.Version });
commandOutputProvider.TfsServiceMessage(ServerBaseUrl, project, release);
await DeployRelease(project, release).ConfigureAwait(false);
}
}
private async Task<ReleasePlan> BuildReleasePlan(ProjectResource project)
{
if (!string.IsNullOrWhiteSpace(ChannelNameOrId))
{
commandOutputProvider.Information("Building release plan for channel '{Channel:l}'...", ChannelNameOrId);
var matchingChannel = await Repository.Channels.FindByNameOrIdOrFail(project, ChannelNameOrId).ConfigureAwait(false);
return await releasePlanBuilder.Build(Repository, project, matchingChannel, VersionPreReleaseTag).ConfigureAwait(false);
}
// All Octopus 3.2+ servers should have the Channels hypermedia link, we should use the channel information
// to select the most appropriate channel, or provide enough information to proceed from here
if (await ServerSupportsChannels().ConfigureAwait(false))
{
commandOutputProvider.Debug("Automatically selecting the best channel for this release...");
return await AutoSelectBestReleasePlanOrThrow(project).ConfigureAwait(false);
}
// Compatibility: this has to cater for Octopus before Channels existed
commandOutputProvider.Information("Building release plan without a channel for Octopus Server without channels support...");
return await releasePlanBuilder.Build(Repository, project, null, VersionPreReleaseTag).ConfigureAwait(false);
}
private Task<bool> ServerSupportsChannels()
{
return Repository.HasLink("Channels");
}
async Task<ReleasePlan> AutoSelectBestReleasePlanOrThrow(ProjectResource project)
{
// Build a release plan for each channel to determine which channel is the best match for the provided options
var channels = await Repository.Projects.GetChannels(project).ConfigureAwait(false);
var candidateChannels = await channels.GetAllPages(Repository).ConfigureAwait(false);
var releasePlans = new List<ReleasePlan>();
foreach (var channel in candidateChannels)
{
commandOutputProvider.Information("Building a release plan for Channel '{Channel:l}'...", channel.Name);
var plan = await releasePlanBuilder.Build(Repository, project, channel, VersionPreReleaseTag).ConfigureAwait(false);
releasePlans.Add(plan);
if (plan.ChannelHasAnyEnabledSteps() == false)
{
commandOutputProvider.Warning($"Channel {channel.Name} does not contain any packageSteps");
}
}
var viablePlans = releasePlans.Where(p => p.IsViableReleasePlan()).ToArray();
if (viablePlans.Length <= 0)
{
throw new CommandException(
"There are no viable release plans in any channels using the provided arguments. The following release plans were considered:" +
System.Environment.NewLine +
$"{releasePlans.Select(p => p.FormatAsTable()).NewlineSeperate()}");
}
if (viablePlans.Length == 1)
{
var selectedPlan = viablePlans.Single();
commandOutputProvider.Information("Selected the release plan for Channel '{Channel:l}' - it is a perfect match", selectedPlan.Channel.Name);
return selectedPlan;
}
if (viablePlans.Length > 1 && viablePlans.Any(p => p.Channel.IsDefault))
{
var selectedPlan = viablePlans.First(p => p.Channel.IsDefault);
commandOutputProvider.Information("Selected the release plan for Channel '{Channel:l}' - there were multiple matching Channels ({AllChannels:l}) so we selected the default channel.", selectedPlan.Channel.Name, viablePlans.Select(p => p.Channel.Name).CommaSeperate());
return selectedPlan;
}
throw new CommandException(
$"There are {viablePlans.Length} viable release plans using the provided arguments so we cannot auto-select one. The viable release plans are:" +
System.Environment.NewLine +
$"{viablePlans.Select(p => p.FormatAsTable()).NewlineSeperate()}" +
System.Environment.NewLine +
"The unviable release plans are:" +
System.Environment.NewLine +
$"{releasePlans.Except(viablePlans).Select(p => p.FormatAsTable()).NewlineSeperate()}");
}
void ReadReleaseNotesFromFile(string value)
{
try
{
ReleaseNotes = File.ReadAllText(value);
}
catch (IOException ex)
{
throw new CommandException(ex.Message);
}
}
public void PrintDefaultOutput()
{
}
public void PrintJsonOutput()
{
commandOutputProvider.Json(new
{
ReleaseId = release.Id,
release.Assembled,
release.Version,
Project = new { project.Id, project.Name },
Channel = plan.Channel == null ? null : new { plan.Channel.Id, plan.Channel.Name },
Steps = plan.PackageSteps.Select((x, i) => new
{
Id = i,
x.ActionName,
x.Version,
x.VersionSource,
VersionRule = x.ChannelVersionRuleTestResult?.ToSummaryString()
})
});
}
}
}
| 55.75 | 394 | 0.629455 | [
"Apache-2.0"
] | praveenk2527/octops-cli | source/Octopus.Cli/Commands/Releases/CreateReleaseCommand.cs | 16,950 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Web.Controllers
{
public class HomeController : Controller
{
public ActionResult AJMillwork()
{
return View();
}
public ActionResult Services()
{
return View();
}
public ActionResult Portfolio()
{
return View();
}
public ActionResult Designer()
{
return View();
}
public ActionResult DesignerFurniture()
{
return View();
}
public ActionResult DesignerStair()
{
return View();
}
// [HttpGet]
public ActionResult Contact()
{
return View();
}
// public ActionResult ContactSubmited()
// {
// var result = new FilePathResult("~/Views/Home/AJMillwork.html", "text/html");
// return result;
// }
}
} | 17.79661 | 91 | 0.49619 | [
"MIT"
] | tosca/AJ-millwork | Web/Web/Controllers/HomeController.cs | 1,052 | C# |
using System.Collections.Generic;
namespace ABPNetCore.Authentication.External
{
public interface IExternalAuthConfiguration
{
List<ExternalLoginProviderInfo> Providers { get; }
}
}
| 20.4 | 58 | 0.745098 | [
"MIT"
] | phamquanghien/ZeroProject | aspnet-core/src/ABPNetCore.Web.Core/Authentication/External/IExternalAuthConfiguration.cs | 206 | C# |
//-----------------------------------------------------------------------
// <copyright file="ClusterSingletonManagerSettings.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Configuration;
namespace Akka.Cluster.Tools.Singleton
{
/// <summary>
/// The settings used for the <see cref="ClusterSingletonManager"/>
/// </summary>
[Serializable]
public sealed class ClusterSingletonManagerSettings : INoSerializationVerificationNeeded
{
/// <summary>
/// Creates a new <see cref="ClusterSingletonManagerSettings"/> instance.
/// </summary>
/// <param name="system">The <see cref="ActorSystem"/> to which this singleton manager belongs.</param>
/// <exception cref="ConfigurationException">Thrown if no "akka.cluster.singleton" section is defined.</exception>
/// <returns>The requested settings.</returns>
public static ClusterSingletonManagerSettings Create(ActorSystem system)
{
system.Settings.InjectTopLevelFallback(ClusterSingletonManager.DefaultConfig());
var config = system.Settings.Config.GetConfig("akka.cluster.singleton");
if (config == null)
throw new ConfigurationException(
$"Cannot initialize {typeof(ClusterSingletonManagerSettings)}: akka.cluster.singleton configuration node was not provided");
return Create(config).WithRemovalMargin(Cluster.Get(system).DowningProvider.DownRemovalMargin);
}
/// <summary>
/// Creates a new <see cref="ClusterSingletonManagerSettings"/> instance.
/// </summary>
/// <param name="config">The HOCON configuration used to create the settings.</param>
/// <returns>The requested settings.</returns>
public static ClusterSingletonManagerSettings Create(Config config)
{
return new ClusterSingletonManagerSettings(
singletonName: config.GetString("singleton-name"),
role: RoleOption(config.GetString("role")),
removalMargin: TimeSpan.Zero, // defaults to ClusterSettings.DownRemovalMargin
handOverRetryInterval: config.GetTimeSpan("hand-over-retry-interval"));
}
private static string RoleOption(string role)
{
if (string.IsNullOrEmpty(role))
return null;
return role;
}
/// <summary>
/// The actor name of the child singleton actor.
/// </summary>
public string SingletonName { get; }
/// <summary>
/// Singleton among the nodes tagged with specified role.
/// </summary>
public string Role { get; }
/// <summary>
/// Margin until the singleton instance that belonged to a downed/removed partition is created in surviving partition.
/// </summary>
public TimeSpan RemovalMargin { get; }
/// <summary>
/// When a node is becoming oldest it sends hand-over request to previous oldest, that might be leaving the cluster.
/// </summary>
public TimeSpan HandOverRetryInterval { get; }
/// <summary>
/// Creates a new instance of the <see cref="ClusterSingletonManagerSettings"/>.
/// </summary>
/// <param name="singletonName">The actor name of the child singleton actor.</param>
/// <param name="role">
/// Singleton among the nodes tagged with specified role. If the role is not specified
/// it's a singleton among all nodes in the cluster.
/// </param>
/// <param name="removalMargin">
/// Margin until the singleton instance that belonged to a downed/removed partition is
/// created in surviving partition. The purpose of this margin is that in case of
/// a network partition the singleton actors in the non-surviving partitions must
/// be stopped before corresponding actors are started somewhere else.
/// This is especially important for persistent actors.
/// </param>
/// <param name="handOverRetryInterval">
/// When a node is becoming oldest it sends hand-over
/// request to previous oldest, that might be leaving the cluster. This is
/// retried with this interval until the previous oldest confirms that the hand
/// over has started or the previous oldest member is removed from the cluster
/// (+ <paramref name="removalMargin"/>).
/// </param>
/// <exception cref="ArgumentException">TBD</exception>
public ClusterSingletonManagerSettings(string singletonName, string role, TimeSpan removalMargin, TimeSpan handOverRetryInterval)
{
if (string.IsNullOrWhiteSpace(singletonName))
throw new ArgumentNullException(nameof(singletonName));
if (removalMargin < TimeSpan.Zero)
throw new ArgumentException("ClusterSingletonManagerSettings.RemovalMargin must be positive", nameof(removalMargin));
if (handOverRetryInterval <= TimeSpan.Zero)
throw new ArgumentException("ClusterSingletonManagerSettings.HandOverRetryInterval must be positive", nameof(handOverRetryInterval));
SingletonName = singletonName;
Role = role;
RemovalMargin = removalMargin;
HandOverRetryInterval = handOverRetryInterval;
}
/// <summary>
/// Create a singleton manager with specified singleton name.
/// </summary>
/// <param name="singletonName">TBD</param>
/// <returns>TBD</returns>
public ClusterSingletonManagerSettings WithSingletonName(string singletonName)
{
return Copy(singletonName: singletonName);
}
/// <summary>
/// Create a singleton manager with specified singleton role.
/// </summary>
/// <param name="role">TBD</param>
/// <returns>TBD</returns>
public ClusterSingletonManagerSettings WithRole(string role)
{
return Copy(role: RoleOption(role));
}
/// <summary>
/// Create a singleton manager with specified singleton removal margin.
/// </summary>
/// <param name="removalMargin">TBD</param>
/// <returns>TBD</returns>
public ClusterSingletonManagerSettings WithRemovalMargin(TimeSpan removalMargin)
{
return Copy(removalMargin: removalMargin);
}
/// <summary>
/// Create a singleton manager with specified singleton removal margin hand-over retry interval.
/// </summary>
/// <param name="handOverRetryInterval">TBD</param>
/// <returns>TBD</returns>
public ClusterSingletonManagerSettings WithHandOverRetryInterval(TimeSpan handOverRetryInterval)
{
return Copy(handOverRetryInterval: handOverRetryInterval);
}
private ClusterSingletonManagerSettings Copy(string singletonName = null, string role = null, TimeSpan? removalMargin = null,
TimeSpan? handOverRetryInterval = null)
{
return new ClusterSingletonManagerSettings(
singletonName: singletonName ?? SingletonName,
role: role ?? Role,
removalMargin: removalMargin ?? RemovalMargin,
handOverRetryInterval: handOverRetryInterval ?? HandOverRetryInterval);
}
}
}
| 46.047619 | 149 | 0.629783 | [
"Apache-2.0"
] | IgorFedchenko/akka.net | src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManagerSettings.cs | 7,738 | C# |
/*
*
* User: Philippe Elsass
* Date: 18/03/2006
* Time: 19:03
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using ASCompletion.Completion;
using ASCompletion.Context;
namespace ASCompletion.Model
{
#region Token class
class Token
{
public int Position;
public int Line;
public string Text;
public Token()
{
}
public Token(Token copy)
{
Text = copy.Text;
Line = copy.Line;
Position = copy.Position;
}
override public string ToString()
{
return Text;
}
}
#endregion
#region TypeDefinitionKind enum
/// <summary>
/// Contributor: i.o.
/// </summary>
public enum TypeDefinitionKind : uint
{
Null = 0,
Simple = 1,
TypedArray = 2,
TypedCallback = 3,
TypedObject = 4
}
//
#endregion
#region TypeCommentUtils class
/// <summary>
/// Contributor: i.o.
/// </summary>
public class TypeCommentUtils
{
//---------------------
// FIELDS
//---------------------
public static string ObjectType = "Object"; // will differ in haxe
private static Random random = new Random(123456);
//---------------------
// PUBLIC METHODS
//---------------------
/// <summary>
/// Type-comment parsing into model (source and destination)
/// </summary>
public static TypeDefinitionKind Parse(string comment, MemberModel model)
{
return Parse(comment, model, false);
}
public static TypeDefinitionKind Parse(string comment, MemberModel model, bool detectKindOnly)
{
if (model != null && comment != null && comment != "")
{
switch (model.Type)
{
case "Array":
return ParseTypedArray(comment, model, detectKindOnly);
case "Function":
return ParseTypedCallback(comment, model, detectKindOnly);
}
if (model.Type == ObjectType)
return ParseTypedObject(comment, model, detectKindOnly);
}
return TypeDefinitionKind.Null;
}
/// <summary>
/// Typed object parsing
/// </summary>
public static TypeDefinitionKind ParseTypedObject(string comment, MemberModel model)
{
return ParseTypedObject(comment, model, false);
}
public static TypeDefinitionKind ParseTypedObject(string comment, MemberModel model, bool detectKindOnly)
{
if (model != null && comment != null && comment != "")
{
Match m = ASFileParserRegexes.ValidObjectType.Match(comment);
if (m.Success)
{
if (!detectKindOnly)
model.Type = TypeCommentUtils.ObjectType + "@" + m.Groups["type"].Value;
return TypeDefinitionKind.TypedObject;
}
}
return TypeDefinitionKind.Null;
}
/// <summary>
/// Typed array parsing
/// </summary>
public static TypeDefinitionKind ParseTypedArray(string comment, MemberModel model)
{
return ParseTypedArray(comment, model, false);
}
public static TypeDefinitionKind ParseTypedArray(string comment, MemberModel model, bool detectKindOnly)
{
if (model != null && comment != null && comment != "")
{
Match m = ASFileParserRegexes.ValidTypeName.Match(comment);
if (m.Success)
{
if (!detectKindOnly)
model.Type = "Array@" + m.Groups["type"].Value;
return TypeDefinitionKind.TypedArray;
}
}
return TypeDefinitionKind.Null;
}
/// <summary>
/// Typed callbck parsing
/// </summary>
public static TypeDefinitionKind ParseTypedCallback(string comment, MemberModel model)
{
return ParseTypedCallback(comment, model, false);
}
public static TypeDefinitionKind ParseTypedCallback(string comment, MemberModel model, bool detectKindOnly)
{
if (model != null && comment != null && comment != ""
&& (model.Flags & FlagType.Function) == 0)
{
MemberModel fnModel = extractTypedCallbackModel(comment);
if (fnModel != null)
{
if (!detectKindOnly)
{
model.Type = fnModel.Type;
model.Flags |= FlagType.Function;
model.Parameters = fnModel.Parameters;
if (model.Access == 0)
{
if (model.Namespace == "internal")
{
if ((model.Access & Visibility.Public) == 0)
model.Access = Visibility.Internal;
model.Namespace = "";
}
else model.Access = Visibility.Public;
}
}
return TypeDefinitionKind.TypedCallback;
}
}
return TypeDefinitionKind.Null;
}
//---------------------
// PRIVATE METHODS
//---------------------
/// <summary>
/// String randomer
/// </summary>
private static string getRandomStringRepl()
{
random.NextDouble();
return "StringRepl" + random.Next(0xFFFFFFF).ToString();
}
/// <summary>
/// TypedCallback model extracting
/// </summary>
private static MemberModel extractTypedCallbackModel(string comment)
{
if (comment == null || comment.Length == 0)
return null;
int idxBraceOp = comment.IndexOf("(");
int idxBraceCl = comment.IndexOf(")");
if (idxBraceOp != 0 || idxBraceCl < 1)
return null;
// replace strings by temp replacements
MatchCollection qStrMatches = ASFileParserRegexes.QuotedString.Matches(comment);
Dictionary<String, String> qStrRepls = new Dictionary<string, string>();
int i = qStrMatches.Count;
while (i-- > 0)
{
String strRepl = getRandomStringRepl();
qStrRepls.Add(strRepl, qStrMatches[i].Value);
comment = comment.Substring(0, qStrMatches[i].Index) + strRepl + comment.Substring(qStrMatches[i].Index + qStrMatches[i].Length);
}
// refreshing
idxBraceOp = comment.IndexOf("(");
idxBraceCl = comment.IndexOf(")");
if (idxBraceOp != 0 || comment.LastIndexOf("(") != idxBraceOp
|| idxBraceCl < 0 || comment.LastIndexOf(")") != idxBraceCl)
return null;
MemberModel fm = new MemberModel("unknown", "*", FlagType.Function, Visibility.Default);
fm.Parameters = new List<MemberModel>();
// return type
Match m = ASFileParserRegexes.FunctionType.Match(comment.Substring(idxBraceCl));
if (m.Success)
fm.Type = m.Groups["fType"].Value;
// parameters
String pBody = comment.Substring(idxBraceOp, 1 + idxBraceCl - idxBraceOp);
MatchCollection pMatches = ASFileParserRegexes.Parameter.Matches(pBody);
int l = pMatches.Count;
for (i = 0; i < l; i++)
{
string pName = pMatches[i].Groups["pName"].Value;
if (pName != null && pName.Length > 0)
{
foreach (KeyValuePair<String,String> replEntry in qStrRepls)
{
if (pName.IndexOf(replEntry.Key) > -1)
{
pName = "[COLOR=#F00][I]InvalidName[/I][/COLOR]";
break;
}
}
}
string pType = pMatches[i].Groups["pType"].Value;
if (pType != null && pType.Length > 0)
{
foreach (KeyValuePair<String,String> replEntry in qStrRepls)
{
if (pType.IndexOf(replEntry.Key) > -1)
{
pType = "[COLOR=#F00][I]InvalidType[/I][/COLOR]";
break;
}
}
}
string pVal = pMatches[i].Groups["pVal"].Value;
if (pVal != null && pVal.Length > 0)
{
if (qStrRepls.ContainsKey(pVal))
{
pVal = qStrRepls[pVal];
}
else
{
foreach (KeyValuePair<String,String> replEntry in qStrRepls)
{
if (pVal.IndexOf(replEntry.Key) > -1)
{
pVal = "[COLOR=#F00][I]InvalidValue[/I][/COLOR]";
break;
}
}
}
}
else
{
pVal = null;
}
MemberModel pModel = new MemberModel();
pModel.Name = pName;
pModel.Type = pType;
pModel.Value = pVal;
pModel.Flags = FlagType.ParameterVar;
pModel.Access = Visibility.Default;
fm.Parameters.Add(pModel);
}
return fm;
}
}
//
#endregion
#region ASFileParserRegexes class
//
public class ASFileParserRegexes
{
public static readonly Regex Spaces = new Regex("\\s+", RegexOptions.Compiled);
public static readonly Regex RegionStart = new Regex(@"^{[ ]?region[:\\s]*(?<name>[^\r\n]*)", RegexOptions.Compiled);
public static readonly Regex RegionEnd = new Regex(@"^}[ ]?endregion", RegexOptions.Compiled);
public static readonly Regex QuotedString = new Regex("(\"(\\\\.|[^\"\\\\])*\")|('(\\\\.|[^'\\\\])*')", RegexOptions.Compiled);
public static readonly Regex FunctionType = new Regex(@"\)\s*\:\s*(?<fType>[\w\$\.\<\>\@]+)", RegexOptions.Compiled);
public static readonly Regex ValidTypeName = new Regex("^(\\s*of\\s*)?(?<type>[\\w.\\$]*)$", RegexOptions.Compiled);
public static readonly Regex ValidObjectType = new Regex("^(?<type>[\\w.,\\$]*)$", RegexOptions.Compiled);
public static readonly Regex Import = new Regex("^[\\s]*import[\\s]+(?<package>[\\w.]+)",
ASFileParserRegexOptions.MultilineComment);
public static readonly Regex Parameter = new Regex(@"[\(,]\s*((?<pName>(\.\.\.)?[\w\$]+)\s*(\:\s*(?<pType>[\w\$\*\.\<\>\@]+))?(\s*\=\s*(?<pVal>[^\,\)]+))?)",
RegexOptions.Compiled);
public static readonly Regex BalancedBraces = new Regex("{[^{}]*(((?<Open>{)[^{}]*)+((?<Close-Open>})[^{}]*)+)*(?(Open)(?!))}",
ASFileParserRegexOptions.SinglelineComment);
private const string typeChars = @"[\w\$][\w\d\$]*";
private const string typeClsf = @"(\s*(?<Classifier>" + typeChars + @"(\." + typeChars + ")*" + @"(\:\:?" + typeChars + ")?" + @")\s*)";
private const string typeComment = @"(\s*\/\*(?<Comment>.*)\*\/\s*)";
public static readonly Regex TypeDefinition = new Regex(@"^((" + typeClsf + typeComment + ")|(" + typeComment + typeClsf + ")|(" + typeClsf + "))$",
RegexOptions.Compiled);
}
//
#endregion
#region ASFileParserRegexOptions class
//
public class ASFileParserRegexOptions
{
public const RegexOptions MultilineComment = RegexOptions.Compiled | RegexOptions.Multiline;
public const RegexOptions SinglelineComment = RegexOptions.Compiled | RegexOptions.Singleline;
}
//
#endregion
#region ASFileParserUtils class
//
public class ASFileParserUtils
{
/// <summary>
/// Contributor: i.o.
/// Description: Extracts from plain string a type classifier and type comment
/// Example:
/// typeDefinition: "Array/*String*/" or "Array[spaces]/*String*/" or "/*String*/Array"
/// typeClassifier: "Array"
/// typeComment: "String"
/// </summary>
public static bool ParseTypeDefinition(string typeDefinition, out string typeClassifier, out string typeComment)
{
typeClassifier = null;
typeComment = null;
if (String.IsNullOrEmpty(typeDefinition))
return false;
Match m = ASFileParserRegexes.TypeDefinition.Match(typeDefinition);
if (!m.Success)
return false;
typeClassifier = m.Groups["Classifier"].Value;
if (m.Groups["Comment"].Success)
typeComment = m.Groups["Comment"].Value;
return true;
}
public static TypeDefinitionKind ParseTypeDefinitionInto(string typeDefinition, MemberModel model)
{
return ParseTypeDefinitionInto(typeDefinition, model, true, true);
}
public static TypeDefinitionKind ParseTypeDefinitionInto(string typeDefinition, MemberModel model, bool parseCommon, bool parseGeneric)
{
if (String.IsNullOrEmpty(typeDefinition))
return TypeDefinitionKind.Null;
if (typeDefinition.IndexOf("/*") < 0 || typeDefinition.IndexOf("*/") < 0)
{
if (!parseCommon)
return TypeDefinitionKind.Null;
model.Type = typeDefinition.Replace(":", ".");
if (model.Type.IndexOf('$') > 0) model.Type = model.Type.Replace("$", ".<") + ">";
return TypeDefinitionKind.Simple;
}
if (!parseGeneric)
return TypeDefinitionKind.Null;
string typeClassifier;
string typeComment;
if (!ASFileParserUtils.ParseTypeDefinition(typeDefinition, out typeClassifier, out typeComment))
return TypeDefinitionKind.Null;
model.Type = typeClassifier;
return TypeCommentUtils.Parse(typeComment, model);
}
}
//
#endregion
/// <summary>
/// Old & clumsy AS2/AS3/haxe file parser - beware!
/// </summary>
public class ASFileParser
{
#region public methods
static private PathModel cachedPath;
static private DateTime cacheLastWriteTime;
static public void ParseCacheFile(PathModel inPath, string file, IASContext inContext)
{
lock (typeof(ASFileParser))
{
cachedPath = inPath;
ParseFile(inContext.CreateFileModel(file));
cachedPath = null;
}
}
static public FileModel ParseFile(FileModel fileModel)
{
string src = "";
// parse file
if (fileModel.FileName.Length > 0)
{
if (File.Exists(fileModel.FileName))
{
src = PluginCore.Helpers.FileHelper.ReadFile(fileModel.FileName);
ASFileParser parser = new ASFileParser();
fileModel.LastWriteTime = File.GetLastWriteTime(fileModel.FileName);
if (cachedPath != null)
cacheLastWriteTime = fileModel.LastWriteTime;
parser.ParseSrc(fileModel, src);
}
// the file is not available (for the moment?)
else if (Path.GetExtension(fileModel.FileName).Length > 0)
{
fileModel.OutOfDate = true;
}
}
// this is a package
else
{
// ignore
}
return fileModel;
}
#endregion
#region parser context
const int COMMENTS_BUFFER = 4096;
const int TOKEN_BUFFER = 1024;
const int VALUE_BUFFER = 1024;
// parser context
private FileModel model;
private int version;
private bool haXe;
private bool tryPackage;
private bool hasPackageSection;
private FlagType context;
private FlagType modifiers;
private FlagType curModifiers;
//private int modifiersPos;
private int line;
private int modifiersLine;
private bool foundColon;
private bool foundConstant;
private bool inParams;
private bool inEnum;
private bool inTypedef;
private bool inAbstract;
private bool inGeneric;
private bool inValue;
private bool hadValue;
private bool inConst;
private bool inType;
private bool inAnonType;
private int flattenNextBlock;
private FlagType foundKeyword;
private Token valueKeyword;
private MemberModel valueMember;
private Token curToken;
private Token prevToken;
private MemberModel curMember;
private MemberModel curMethod;
private Visibility curAccess;
private string curNamespace;
private ClassModel curClass;
private string lastComment;
private string curComment;
private bool isBlockComment;
private ContextFeatures features;
private List<ASMetaData> carriedMetaData;
#endregion
#region tokenizer
public bool ScriptMode;
public ContextFeatures Features
{
get { return features; }
}
public ASFileParser()
{
features = new ContextFeatures();
}
/// <summary>
/// Rebuild a file model with the source provided
/// </summary>
/// <param name="fileModel">Model</param>
/// <param name="ba">Source</param>
///
public void ParseSrc(FileModel fileModel, string ba)
{
ParseSrc(fileModel, ba, true);
}
public void ParseSrc(FileModel fileModel, string ba, bool allowBaReExtract)
{
//TraceManager.Add("Parsing " + Path.GetFileName(fileModel.FileName));
model = fileModel;
model.OutOfDate = false;
model.CachedModel = false;
if (model.Context != null) features = model.Context.Features;
if (features != null && features.hasModules)
model.Module = Path.GetFileNameWithoutExtension(model.FileName);
// pre-filtering
if (allowBaReExtract && model.HasFiltering && model.Context != null)
ba = model.Context.FilterSource(fileModel.FileName, ba);
model.InlinedIn = null;
model.InlinedRanges = null;
// language features
model.Imports.Clear();
model.Classes.Clear();
model.Members.Clear();
model.Namespaces.Clear();
model.Regions.Clear();
model.PrivateSectionIndex = 0;
model.Package = "";
model.MetaDatas = null;
// state
int len = ba.Length;
if (len < 0)
return;
int i = 0;
line = 0;
// when parsing cache file including multiple files
resetParser:
char c1;
char c2;
int matching = 0;
bool isInString = false;
int inString = 0;
int braceCount = 0;
bool inCode = true;
// comments
char[] commentBuffer = new char[COMMENTS_BUFFER];
int commentLength = 0;
lastComment = null;
curComment = null;
// tokenisation
tryPackage = true;
hasPackageSection = false;
haXe = model.haXe;
TypeCommentUtils.ObjectType = haXe ? "Dynamic" : "Object";
version = (haXe) ? 4 : 1;
curToken = new Token();
prevToken = new Token();
int tokPos = 0;
int tokLine = 0;
curMethod = null;
curMember = null;
valueKeyword = null;
valueMember = null;
curModifiers = 0;
curNamespace = "internal";
curAccess = 0;
char[] buffer = new char[TOKEN_BUFFER];
int length = 0;
char[] valueBuffer = new char[VALUE_BUFFER];
int valueLength = 0;
int paramBraceCount = 0;
int paramTempCount = 0;
int paramParCount = 0;
int paramSqCount = 0;
bool hadWS = true;
bool hadDot = false;
inParams = false;
inEnum = false;
inTypedef = false;
inAbstract = false;
inValue = false;
hadValue = false;
inConst = false;
inType = false;
inGeneric = false;
inAnonType = false;
bool addChar = false;
int evalToken = 0;
//bool evalKeyword = true;
context = 0;
modifiers = 0;
foundColon = false;
bool handleDirectives = features.hasDirectives || cachedPath != null;
bool inlineDirective = false;
while (i < len)
{
c1 = ba[i++];
isInString = (inString > 0);
/* MATCH COMMENTS / STRING LITERALS */
switch (matching)
{
// look for comment block/line and preprocessor commands
case 0:
if (!isInString)
{
// new comment
if (c1 == '/' && i < len)
{
c2 = ba[i];
if (c2 == '/')
{
// Check if this this is a /// comment
if (i + 1 < len && ba[i + 1] == '/')
{
// This is a /// comment
matching = 4;
isBlockComment = true;
i++;
}
else
{
// This is a regular comment
matching = 1;
isBlockComment = false;
}
inCode = false;
i++;
continue;
}
else if (c2 == '*')
{
isBlockComment = (i + 1 < len && ba[i + 1] == '*');
matching = 2;
inCode = false;
i++;
while (i < len - 1)
{
c2 = ba[i];
if (c2 == '*' && ba[i + 1] != '/') i++;
else break;
}
continue;
}
}
// don't look for comments in strings
else if (c1 == '"')
{
isInString = true;
inString = 1;
}
else if (c1 == '\'')
{
isInString = true;
inString = 2;
}
// preprocessor statements
else if (c1 == '#' && handleDirectives && i < len)
{
int ls = i - 2;
inlineDirective = false;
while (ls > 0)
{
c2 = ba[ls--];
if (c2 == 10 || c2 == 13) break;
else if (c2 > 32) { inlineDirective = true; break; }
}
c2 = ba[i];
if (i < 2 || ba[i - 2] < 33 && c2 >= 'a' && c2 <= 'z')
{
matching = 3;
inCode = false;
continue;
}
}
}
// end of string
else if (isInString)
{
if (c1 == '\\') { i++; continue; }
else if (c1 == 10 || c1 == 13) inString = 0;
else if ((inString == 1) && (c1 == '"')) inString = 0;
else if ((inString == 2) && (c1 == '\'')) inString = 0;
// extract "include" declarations
if (inString == 0 && length == 7 && context == 0)
{
string token = new string(buffer, 0, length);
if (token == "include")
{
string inc = ba.Substring(tokPos, i - tokPos);
if (model.MetaDatas == null) model.MetaDatas = new List<ASMetaData>();
ASMetaData meta = new ASMetaData("Include");
meta.ParseParams(inc);
model.MetaDatas.Add(meta);
}
}
}
break;
// skip commented line
case 1:
if (c1 == 10 || c1 == 13)
{
// ignore single comments
commentLength = 0;
inCode = true;
matching = 0;
}
break;
// skip commented block
case 2:
if (c1 == '*')
{
bool end = false;
while (i < len)
{
c2 = ba[i];
if (c2 == '\\') { i++; continue; }
if (c2 == '/')
{
end = true;
break;
}
else if (c2 == '*') i++;
else break;
}
if (end)
{
lastComment = (commentLength > 0) ? new string(commentBuffer, 0, commentLength) : null;
// TODO parse for TODO statements?
commentLength = 0;
inCode = true;
matching = 0;
i++;
continue;
}
}
break;
// directive/preprocessor statement
case 3:
if (c1 == 10 || c1 == 13 || (inlineDirective && c1 <= 32))
{
if (commentLength > 0)
{
string directive = new string(commentBuffer, 0, commentLength);
if (directive.StartsWith("if"))
{
inCode = true;
}
else if (directive.StartsWith("else"))
{
inCode = true;
}
else if (directive.StartsWith("end"))
{
inCode = true; // directive end
matching = 0;
}
else inCode = true;
// FD cache custom directive
if (cachedPath != null && directive.StartsWith("file-cache "))
{
// parsing done!
FinalizeModel();
// next model
string realFile = directive.Substring(11);
FileModel newModel = model.Context != null ? model.Context.CreateFileModel(realFile) : new FileModel(realFile);
newModel.LastWriteTime = cacheLastWriteTime;
newModel.CachedModel = true;
if (features != null && features.hasModules)
newModel.Module = Path.GetFileNameWithoutExtension(realFile);
haXe = newModel.haXe;
if (!cachedPath.HasFile(realFile) && File.Exists(realFile))
{
newModel.OutOfDate = (File.GetLastWriteTime(realFile) > cacheLastWriteTime);
cachedPath.AddFile(newModel);
}
model = newModel;
goto resetParser; // loop
}
}
else inCode = true;
commentLength = 0;
matching = 0;
}
else if (c1 == '#') // peek for #end
{
if (i + 3 < len && ba[i] == 'e' && ba[i + 1] == 'n' && ba[i + 2] == 'd' && ba[i + 3] <= 32)
{
matching = 0;
inCode = true;
commentLength = 0;
i += 3;
continue;
}
}
break;
// We are inside a /// comment
case 4:
{
bool end = false;
bool skipAhead = false;
// See if we just ended a line
if (2 <= i && (ba[i - 2] == 10 || ba[i - 2] == 13))
{
// Check ahead to the next line, see if it has a /// comment on it too.
// If it does, we want to continue the comment with that line. If it
// doesn't, then this comment is finished and we will set end to true.
for (int j = i + 1; j < len; ++j)
{
// Skip whitespace
char twoBack = ba[j - 2];
if (' ' != twoBack && '\t' != twoBack)
{
if ('/' == twoBack && '/' == ba[j - 1] && '/' == ba[j])
{
// There is a comment ahead. Move up to it so we can gather the
// rest of the comment
i = j + 1;
skipAhead = true;
break;
}
else
{
// Not a comment! We're done!
end = true;
break;
}
}
}
}
if (end)
{
// The comment is over and we want to write it out
lastComment = (commentLength > 0) ? new string(commentBuffer, 0, commentLength).Trim() : null;
commentLength = 0;
inCode = true;
matching = 0;
// Back up i so we can start gathering comments from right after the line break
--i;
continue;
}
if (skipAhead)
{
// We just hit another /// and are skipping up to right after it.
continue;
}
break;
}
}
/* LINE/COLUMN NUMBER */
if (c1 == 10 || c1 == 13)
{
if (cachedPath == null) line++; // cache breaks line count
if (c1 == 13 && i < len && ba[i] == 10) i++;
}
/* SKIP CONTENT */
if (!inCode)
{
// store comments
if (matching == 2 || (matching == 3 && handleDirectives) || matching == 4)
{
if (commentLength < COMMENTS_BUFFER) commentBuffer[commentLength++] = c1;
}
else if (matching == 1 && (c1 == '{' || c1 == '}'))
{
commentBuffer[commentLength++] = c1;
while (i < len)
{
c2 = ba[i];
if (commentLength < COMMENTS_BUFFER) commentBuffer[commentLength++] = c2;
if (c2 == 10 || c2 == 13)
break;
i++;
}
string comment = new String(commentBuffer, 0, commentLength);
// region start
Match matchStart = ASFileParserRegexes.RegionStart.Match(comment);
if (matchStart.Success)
{
string regionName = matchStart.Groups["name"].Value.Trim();
MemberModel region = new MemberModel(regionName, String.Empty, FlagType.Declaration, Visibility.Default);
region.LineFrom = line;
model.Regions.Add(region);
}
else
{
// region end
Match matchEnd = ASFileParserRegexes.RegionEnd.Match(comment);
if (matchEnd.Success && model.Regions.Count > 0)
{
MemberModel region = model.Regions[model.Regions.Count - 1];
if (region.LineTo == 0)
{
region.LineTo = line;
}
}
}
}
continue;
}
else if (isInString)
{
// store parameter default value
if (inValue && valueLength < VALUE_BUFFER)
valueBuffer[valueLength++] = c1;
continue;
}
if (braceCount > 0 && !inValue)
{
if (c1 == '/')
{
LookupRegex(ref ba, ref i);
}
else if (c1 == '}')
{
lastComment = null;
braceCount--;
if (braceCount == 0 && curMethod != null)
{
curMethod.LineTo = line;
curMethod = null;
}
}
else if (c1 == '{') braceCount++;
// escape next char
else if (c1 == '\\') i++;
continue;
}
/* PARSE DECLARATION VALUES/TYPES */
if (inValue)
{
bool stopParser = false;
bool valueError = false;
if (inType && !inAnonType && !inGeneric && !Char.IsLetterOrDigit(c1) && ".{}-><".IndexOf(c1) < 0)
{
inType = false;
inValue = false;
hadValue = false;
inGeneric = false;
valueLength = 0;
length = 0;
context = 0;
}
else if (c1 == '{')
{
if (!inType || valueLength == 0 || valueBuffer[valueLength - 1] == '<' || paramBraceCount > 0)
{
paramBraceCount++;
stopParser = true;
}
}
else if (c1 == '}')
{
if (paramBraceCount > 0) { paramBraceCount--; stopParser = true; }
else valueError = true;
}
else if (c1 == '(')
{
paramParCount++;
stopParser = true;
}
else if (c1 == ')')
{
if (paramParCount > 0) { paramParCount--; stopParser = true; }
else valueError = true;
}
else if (c1 == '[') paramSqCount++;
else if (c1 == ']')
{
if (paramSqCount > 0) { paramSqCount--; stopParser = true; }
else valueError = true;
}
else if (c1 == '<')
{
if (i > 1 && ba[i - 2] == '<') paramTempCount = 0; // a << b
else
{
if (inType) inGeneric = true;
paramTempCount++;
}
}
else if (c1 == '>')
{
if (ba[i - 2] == '-') { /*haxe method signatures*/ }
else if (paramTempCount > 0)
{
paramTempCount--;
stopParser = true;
}
else valueError = true;
}
else if (c1 == '/')
{
int i0 = i;
if (LookupRegex(ref ba, ref i) && valueLength < VALUE_BUFFER - 3)
{
valueBuffer[valueLength++] = '/';
for (; i0 < i; i0++)
if (valueLength < VALUE_BUFFER - 2) valueBuffer[valueLength++] = ba[i0];
valueBuffer[valueLength++] = '/';
continue;
}
}
else if (inValue && (inParams || inType || inConst)
&& c1 == '/' && valueLength == 0) // lookup native regex
{
int itemp = i;
valueBuffer[valueLength++] = '/';
while (valueLength < VALUE_BUFFER && i < len)
{
c1 = ba[i++];
if (c1 == '\n' || c1 == '\r')
{
valueLength = 0;
i = itemp;
break;
}
valueBuffer[valueLength++] = c1;
if (c1 == '\\' && i < len)
{
c1 = ba[i++];
valueBuffer[valueLength++] = c1;
}
else if (c1 == '/') break;
}
}
else if ((c1 == ':' || c1 == ',') && paramBraceCount > 0) stopParser = true;
// end of value
if ((valueError || (!stopParser && paramBraceCount == 0 && paramParCount == 0 && paramSqCount == 0 && paramTempCount == 0))
&& (c1 == ',' || c1 == ';' || c1 == '}' || c1 == '\r' || c1 == '\n' || (inParams && c1 == ')') || inType))
{
if (!inType && (!inValue || c1 != ','))
{
length = 0;
context = 0;
}
inValue = false;
inGeneric = false;
hadValue = true;
}
// in params, store the default value
else if ((inParams || inType || inConst) && valueLength < VALUE_BUFFER)
{
if (c1 <= 32)
{
if (valueLength > 0 && valueBuffer[valueLength - 1] != ' ')
valueBuffer[valueLength++] = ' ';
}
else valueBuffer[valueLength++] = c1;
}
// detect keywords
if (!Char.IsLetterOrDigit(c1))
{
// escape next char
if (c1 == '\\' && i < len)
{
c1 = ba[i++];
if (valueLength < VALUE_BUFFER) valueBuffer[valueLength++] = c1;
continue;
}
if (stopParser || paramBraceCount > 0 || paramSqCount > 0) continue;
else if (valueError && c1 == ')') inValue = false;
else if (inType && inGeneric && (c1 == '<' || c1 == '.')) continue;
else if (inAnonType) continue;
hadWS = true;
}
}
// store type / parameter value
if (hadValue) //!inValue && valueLength > 0)
{
string param = valueLength > 0 ? new string(valueBuffer, 0, valueLength) : "";
// get text before the last keyword found
if (valueKeyword != null)
{
int p = param.LastIndexOf(valueKeyword.Text);
if (p > 0) param = param.Substring(0, p).TrimEnd();
}
if (curMember == null)
{
if (inType)
{
prevToken.Text = curToken.Text;
prevToken.Line = curToken.Line;
prevToken.Position = curToken.Position;
curToken.Text = param;
curToken.Line = tokLine;
curToken.Position = tokPos;
EvalToken(true, true/*false*/, i - 1 - valueLength);
evalToken = 0;
}
}
else if (inType)
{
foundColon = false;
if (haXe)
{
if (param.EndsWith("}") || param.Contains(">"))
{
param = ASFileParserRegexes.Spaces.Replace(param, "");
param = param.Replace(",", ", ");
param = param.Replace("->", " -> ");
}
}
curMember.Type = param;
length = 0;
}
// AS3 const or method parameter's default value
else if (version > 2 && (curMember.Flags & FlagType.Variable) > 0)
{
if (inParams || inConst) curMember.Value = param;
curMember.LineTo = line;
if (c1 == '\r' || c1 == '\n') curMember.LineTo--;
if (inConst && c1 != ',')
{
context = 0;
inConst = false;
}
}
//
hadValue = false;
valueLength = 0;
valueMember = null;
if (!inParams && !(inConst && context != 0) && c1 != '{') continue;
else length = 0;
}
/* TOKENIZATION */
// whitespace
if (c1 <= 32)
{
hadWS = true;
continue;
}
// a dot can be in an identifier
if (c1 == '.')
{
if (length > 0 || (inParams && version == 3))
{
hadWS = false;
hadDot = true;
addChar = true;
if (!inValue && context == FlagType.Variable && !foundColon)
{
bool keepContext = inParams && (length == 0 || buffer[0] == '.');
if (!keepContext) context = 0;
}
}
else continue;
}
else
{
// function types
if (c1 == '-' && context != 0 && length > 0 && features.hasGenerics && i < len && ba[i] == '>')
{
buffer[length++] = '-';
buffer[length++] = '>';
i++;
hadDot = true;
continue;
}
// should we evaluate the token?
if (hadWS && !hadDot && !inGeneric && length > 0)
{
evalToken = 1;
}
hadWS = false;
hadDot = false;
bool shortcut = true;
// valid char for keyword
if (c1 >= 'a' && c1 <= 'z')
{
addChar = true;
}
else
{
// valid chars for identifiers
if (c1 >= 'A' && c1 <= 'Z')
{
addChar = true;
}
else if (c1 == '$' || c1 == '_')
{
addChar = true;
}
else if (length > 0)
{
if (c1 >= '0' && c1 <= '9')
{
addChar = true;
}
else if (c1 == '*' && context == FlagType.Import)
{
addChar = true;
}
// AS3/haXe generics
else if (c1 == '<' && features.hasGenerics)
{
if (!inValue && i > 2 && length > 1 && i < len - 3
&& Char.IsLetterOrDigit(ba[i - 3]) && (Char.IsLetter(ba[i]) || (haXe && ba[i] == '{'))
&& (Char.IsLetter(buffer[0]) || buffer[0] == '_'))
{
if (curMember == null)
{
evalToken = 0;
if (inGeneric) paramTempCount++;
else
{
paramTempCount = 1;
inGeneric = true;
}
addChar = true;
}
else
{
evalToken = 0;
inGeneric = true;
inValue = true;
hadValue = false;
inType = true;
inAnonType = false;
valueLength = 0;
for (int j = 0; j < length; j++)
valueBuffer[valueLength++] = buffer[j];
valueBuffer[valueLength++] = c1;
length = 0;
paramBraceCount = 0;
paramParCount = 0;
paramSqCount = 0;
paramTempCount = 1;
continue;
}
}
}
else if (inGeneric && (c1 == ',' || c1 == '.' || c1 == '-' || c1 == '>' || c1 == ':' || c1 == '(' || c1 == ')'))
{
hadWS = false;
hadDot = false;
evalToken = 0;
if (!inValue)
{
addChar = true;
if (c1 == '>' && inGeneric)
{
if (paramTempCount > 0) paramTempCount--;
if (paramTempCount == 0 && paramBraceCount == 0
&& paramSqCount == 0 && paramParCount == 0) inGeneric = false;
}
}
}
else
{
evalToken = 2;
shortcut = false;
}
}
// star is valid in import statements
else if (c1 == '*' && version >= 3)
{
addChar = true;
}
// conditional haXe parameter
else if (c1 == '?' && haXe && inParams && length == 0)
{
addChar = true;
}
else shortcut = false;
}
// eval this word
if (evalToken > 0)
{
prevToken.Text = curToken.Text;
prevToken.Line = curToken.Line;
prevToken.Position = curToken.Position;
curToken.Text = new string(buffer, 0, length);
curToken.Line = tokLine;
curToken.Position = tokPos;
EvalToken(!inValue, (c1 != '=' && c1 != ','), i - 1 - length);
length = 0;
evalToken = 0;
}
if (!shortcut)
// start of block
if (c1 == '{')
{
if (context == FlagType.Package || context == FlagType.Class) // parse package/class block
{
context = 0;
}
else if (context == FlagType.Enum) // parse enum block
{
if (curClass != null && (curClass.Flags & FlagType.Enum) > 0)
inEnum = true;
else
{
context = 0;
curModifiers = 0;
braceCount++; // ignore block
}
}
else if (context == FlagType.TypeDef) // parse typedef block
{
if (curClass != null && (curClass.Flags & FlagType.TypeDef) > 0)
{
inTypedef = true;
if (i < len && ba[i] == '>')
{
buffer[0] = 'e'; buffer[1] = 'x'; buffer[2] = 't'; buffer[3] = 'e'; buffer[4] = 'n'; buffer[5] = 'd'; buffer[6] = 's';
length = 7;
context = FlagType.Class;
}
}
else
{
context = 0;
curModifiers = 0;
braceCount++; // ignore block
}
}
else if (context == FlagType.Abstract) // parse abstract block
{
if (curClass != null && (curClass.Flags & FlagType.Abstract) > 0)
inAbstract = true;
else
{
context = 0;
curModifiers = 0;
braceCount++; // ignore block
}
}
else if (foundColon && haXe && length == 0) // copy haXe anonymous type
{
inValue = true;
hadValue = false;
inType = true;
inAnonType = true;
valueLength = 0;
valueBuffer[valueLength++] = c1;
paramBraceCount = 1;
paramParCount = 0;
paramSqCount = 0;
paramTempCount = 0;
continue;
}
else if (foundConstant) // start config block
{
flattenNextBlock++;
foundConstant = false;
context = 0;
}
else if (ScriptMode) // not in a class, parse if/for/while/do blocks
{
context = 0;
}
else braceCount++; // ignore block
}
// end of block
else if (c1 == '}')
{
curComment = null;
foundColon = false;
foundConstant = false;
if (flattenNextBlock > 0) // content of this block was parsed
{
flattenNextBlock--;
}
// outside of a method, the '}' ends the current class
else if (curClass != null)
{
if (curClass != null) curClass.LineTo = line;
curClass = null;
inEnum = false;
inTypedef = false;
inAbstract = false;
}
else
{
if (hasPackageSection && model.PrivateSectionIndex == 0) model.PrivateSectionIndex = line + 1;
}
}
// member type declaration
else if (c1 == ':' && !inValue && !inGeneric)
{
foundColon = curMember != null && curMember.Type == null;
// recognize compiler config block
if (!foundColon && braceCount == 0
&& i < len - 2 && ba[i] == ':' && Char.IsLetter(ba[i + 1]))
foundConstant = true;
}
// next variable declaration
else if (c1 == ',')
{
if ((context == FlagType.Variable || context == FlagType.TypeDef) && curMember != null)
{
curAccess = curMember.Access;
foundKeyword = FlagType.Variable;
foundColon = false;
lastComment = null;
}
else if (context == FlagType.Class && prevToken.Text == "implements")
{
curToken.Text = "implements";
foundKeyword = FlagType.Implements;
}
}
else if (c1 == '(')
{
if (!inValue && context == FlagType.Variable && curToken.Text != "catch" && (!haXe || curToken.Text != "for"))
if (haXe && curMember != null && valueLength == 0) // haXe properties
{
curMember.Flags -= FlagType.Variable;
curMember.Flags |= FlagType.Getter | FlagType.Setter;
context = FlagType.Function;
}
else context = 0;
// beginning of method parameters
if (context == FlagType.Function)
{
context = FlagType.Variable;
inParams = true;
inGeneric = false;
if (valueMember != null && curMember == null)
{
valueLength = 0;
//valueMember.Flags -= FlagType.Variable; ???
valueMember.Flags = FlagType.Function;
curMethod = curMember = valueMember;
valueMember = null;
}
else if (curMember == null)
{
context = FlagType.Function;
if ((curModifiers & FlagType.Getter) > 0)
{
curModifiers -= FlagType.Getter;
EvalToken(true, false, i);
curMethod = curMember;
context = FlagType.Variable;
}
else if ((curModifiers & FlagType.Setter) > 0)
{
curModifiers -= FlagType.Setter;
EvalToken(true, false, i);
curMethod = curMember;
context = FlagType.Variable;
}
else
{
inParams = false;
context = 0;
}
}
else
{
curMethod = curMember;
}
}
// an Enum value with parameters
else if (inEnum && curToken != null)
{
context = FlagType.Variable;
inParams = true;
curMethod = curMember ?? new MemberModel();
curMethod.Name = curToken.Text;
curMethod.Flags = curModifiers | FlagType.Function | FlagType.Static;
curMethod.Parameters = new List<MemberModel>();
//
if (curClass != null && curMember == null) curClass.Members.Add(curMethod);
}
// a TypeDef method with parameters
else if (inTypedef && curToken != null)
{
context = FlagType.Variable;
inParams = true;
curMethod = curMember ?? new MemberModel();
curMethod.Name = curToken.Text;
curMethod.Flags = curModifiers | FlagType.Function;
curMethod.Parameters = new List<MemberModel>();
//
if (curClass != null && curMember == null) curClass.Members.Add(curMethod);
}
// an Abstract "opaque type"
else if (context == FlagType.Abstract && prevToken.Text == "abstract")
{
foundKeyword = FlagType.Class;
curModifiers = FlagType.Extends;
}
else if (curMember == null && curToken.Text != "catch" && (!haXe || curToken.Text != "for"))
{
context = 0;
inGeneric = false;
}
}
// end of statement
else if (c1 == ';')
{
context = (inEnum) ? FlagType.Enum : 0;
inGeneric = false;
modifiers = 0;
inParams = false;
curMember = null;
}
// end of method parameters
else if (c1 == ')' && inParams)
{
context = 0;
if (inEnum) context = FlagType.Enum;
else if (inTypedef) context = FlagType.TypeDef;
modifiers = 0;
inParams = false;
curMember = curMethod;
}
// skip value of a declared variable
else if (c1 == '=')
{
if (context == FlagType.Variable || (context == FlagType.Enum && inEnum))
{
if (!inValue && curMember != null)
{
inValue = true;
hadValue = false;
inConst = (curMember.Flags & FlagType.Constant) > 0;
inType = false;
inGeneric = false;
paramBraceCount = 0;
paramParCount = 0;
paramSqCount = 0;
paramTempCount = 0;
valueLength = 0;
valueMember = curMember;
}
}
}
// metadata
else if (!inValue && c1 == '[')
{
if (version == 3)
{
var meta = LookupMeta(ref ba, ref i);
if (meta != null)
{
carriedMetaData = carriedMetaData ?? new List<ASMetaData>();
carriedMetaData.Add(meta);
}
}
else if (features.hasCArrays && curMember != null && curMember.Type != null)
{
if (ba[i] == ']') curMember.Type = features.CArrayTemplate + "@" + curMember.Type;
}
}
// haXe signatures: T -> T -> T
else if (haXe && c1 == '-' && curMember != null)
{
if (ba[i] == '>' && curMember.Type != null)
{
curMember.Type += " ->";
foundColon = true;
}
}
// escape next char
else if (c1 == '\\') { i++; continue; }
// literal regex
else if (c1 == '/' && version == 3)
{
if (LookupRegex(ref ba, ref i))
continue;
}
}
// put in buffer
if (addChar)
{
if (length < TOKEN_BUFFER) buffer[length++] = c1;
if (length == 1)
{
tokPos = i - 1;
tokLine = line;
}
addChar = false;
}
}
// parsing done!
FinalizeModel();
// post-filtering
if (cachedPath == null && model.HasFiltering && model.Context != null)
model.Context.FilterSource(model);
// Debug.WriteLine("out model: " + model.GenerateIntrinsic(false));
}
private bool LookupRegex(ref string ba, ref int i)
{
int len = ba.Length;
int i0 = i - 2;
char c;
// regex in valid context
while (i0 > 0)
{
c = ba[i0--];
if ("=(,[{;".IndexOf(c) >= 0) break; // ok
if (" \t".IndexOf(c) >= 0) continue;
return false; // anything else isn't expected before a regex
}
i0 = i;
while (i0 < len)
{
c = ba[i0++];
if (c == '\\') { i0++; continue; } // escape next
if (c == '/') break; // end of regex
if ("\r\n".IndexOf(c) >= 0) return false;
}
i = i0; // ok, skip this regex
return true;
}
private ASMetaData LookupMeta(ref string ba, ref int i)
{
int len = ba.Length;
int i0 = i;
int line0 = line;
int inString = 0;
int parCount = 0;
bool isComplex = false;
while (i < len)
{
char c = ba[i];
if (c == 10 || c == 13)
{
if (cachedPath == null) line++; // cache breaks line count
if (c == 13 && i < len && ba[i + 1] == 10) i++;
}
if (inString == 0)
{
if (c == '"') inString = 1;
else if (c == '\'') inString = 2;
else if ("{;[".IndexOf(c) >= 0)
{
i = i0;
line = line0;
return null;
}
else if (c == '(') parCount++;
else if (c == ')')
{
parCount--;
if (parCount < 0) return null;
isComplex = true;
}
else if (c == ']') break;
}
else if (inString == 1 && c == '"') inString = 0;
else if (inString == 2 && c == '\'') inString = 0;
else if (inString > 0 && (c == 10 || c == 13)) inString = 0;
i++;
}
string meta = ba.Substring(i0, i - i0);
ASMetaData md = new ASMetaData(isComplex ? meta.Substring(0, meta.IndexOf('(')) : meta);
md.LineFrom = line0;
md.LineTo = line;
if (isComplex)
{
meta = meta.Substring(meta.IndexOf('(') + 1);
md.ParseParams(meta.Substring(0, meta.Length - 1));
if (lastComment != null && isBlockComment && (md.Name == "Event" || md.Name == "Style"))
{
md.Comments = lastComment;
lastComment = null;
}
else lastComment = null;
}
return md;
}
private void FinalizeModel()
{
model.Version = version;
model.HasPackage = hasPackageSection || haXe;
model.FullPackage = model.Module == "" ? model.Package
: (model.Package == "" ? model.Module : model.Package + '.' + model.Module);
if (model.FileName.Length == 0 || model.FileName.EndsWith("_cache")) return;
if (model.PrivateSectionIndex == 0) model.PrivateSectionIndex = line;
if (version == 2)
{
string testPackage = Path.Combine(Path.GetDirectoryName(model.FileName), model.GetPublicClass().Name);
if (Directory.Exists(testPackage)) model.TryAsPackage = true;
}
}
#endregion
#region lexer
/// <summary>
/// Eval a token depending on the parser context
/// </summary>
/// <param name="evalContext">The token could be an identifier</param>
/// <param name="evalKeyword">The token could be a keyword</param>
/// <param name="position">Parser position</param>
/// <returns>A keyword was found</returns>
private bool EvalToken(bool evalContext, bool evalKeyword, int position)
{
bool hadContext = (context != 0);
bool hadKeyword = (foundKeyword != 0);
foundKeyword = 0;
/* KEYWORD EVALUATION */
string token = curToken.Text;
int dotIndex = token.LastIndexOf('.');
if (evalKeyword && (token.Length > 2))
{
if (dotIndex > 0) token = token.Substring(dotIndex + 1);
// members
if (token == "var" || (token == "catch" && !haXe))
{
foundKeyword = FlagType.Variable;
}
else if (token == "function")
{
foundKeyword = FlagType.Function;
}
else if (features.hasConsts && token == "const")
{
foundKeyword = FlagType.Variable;
modifiers |= FlagType.Constant;
}
else if (features.hasNamespaces && token == "namespace")
{
if (context == 0 && prevToken.Text != "use")
foundKeyword = FlagType.Namespace;
}
else if (features.hasDelegates && token == "delegate")
{
foundKeyword = FlagType.Function;
modifiers |= FlagType.Delegate;
}
// class declaration
else if (tryPackage && token == "package")
{
foundKeyword = FlagType.Package;
if (version < 3)
{
version = 3;
hasPackageSection = true;
//model.Namespaces.Add("AS3", Visibility.Public);
//model.Namespaces.Add("ES", Visibility.Public);
}
}
else if (token == "class")
{
foundKeyword = FlagType.Class;
modifiers |= FlagType.Class;
if (version == 1)
{
version = 2;
hasPackageSection = true;
}
}
else if (token == "interface")
{
foundKeyword = FlagType.Class;
modifiers |= FlagType.Class | FlagType.Interface;
if (version == 1)
{
version = 2;
hasPackageSection = true;
}
}
else if (features.hasTypeDefs && token == "typedef")
{
foundKeyword = FlagType.TypeDef;
modifiers |= FlagType.TypeDef;
}
else if (features.hasTypeDefs && token == "abstract")
{
foundKeyword = FlagType.Abstract;
modifiers |= FlagType.Abstract;
}
else if (features.hasStructs && token == "struct")
{
foundKeyword = FlagType.Struct;
modifiers |= FlagType.Class | FlagType.Struct;
}
else if (features.hasEnums && token == "enum")
{
foundKeyword = FlagType.Enum;
modifiers |= FlagType.Enum;
}
// head declarations
else if (token == features.importKey || (haXe && token == features.importKeyAlt))
{
foundKeyword = FlagType.Import;
}
// modifiers
else
{
if (context == FlagType.Class || context == FlagType.TypeDef)
{
if (token == "extends")
{
foundKeyword = FlagType.Class;
curModifiers = FlagType.Extends;
return true;
}
else if (token == "implements")
{
foundKeyword = FlagType.Class;
curModifiers = FlagType.Implements;
return true;
}
}
else if (context == FlagType.Abstract)
{
if (features.hasTypeDefs && token == "from")
{
foundKeyword = FlagType.Class;
curModifiers = FlagType.Extends;
return true;
}
}
// properties
else if (context == FlagType.Function)
{
if (token == "get")
{
foundKeyword = FlagType.Function;
curModifiers |= FlagType.Getter;
return true;
}
else if (token == "set")
{
foundKeyword = FlagType.Function;
curModifiers |= FlagType.Setter;
return true;
}
}
FlagType foundModifier = 0;
// access modifiers
if (token == "public")
{
foundModifier = FlagType.Access;
curAccess = Visibility.Public;
}
else if (token == "private")
{
foundModifier = FlagType.Access;
curAccess = Visibility.Private;
}
else if (token == features.protectedKey)
{
foundModifier = FlagType.Access;
curAccess = Visibility.Protected;
}
else if (token == features.internalKey)
{
foundModifier = FlagType.Access;
curAccess = Visibility.Internal;
}
else if (version == 3 && !hadContext) // TODO Handle namespaces properly
{
if (token == "AS3")
{
foundModifier = FlagType.Access;
curAccess = Visibility.Public;
curNamespace = token;
}
else if (token == "flash_proxy")
{
foundModifier = FlagType.Access;
curAccess = Visibility.Public;
curNamespace = token;
}
}
// other modifiers
if (foundModifier == 0)
{
if (token == "static")
{
foundModifier = FlagType.Static;
}
else if (version <= 3 && token == "intrinsic")
{
foundModifier = FlagType.Intrinsic;
}
else if (token == "override")
{
foundModifier = FlagType.Override;
}
else if (version == 3 && token == "native")
{
foundModifier = FlagType.Intrinsic | FlagType.Native;
}
else if (version == 4 && token == "extern")
{
foundModifier = FlagType.Intrinsic | FlagType.Extern;
}
else if (token == "final")
{
foundModifier = FlagType.Final;
}
else if (token == "dynamic")
{
foundModifier = FlagType.Dynamic;
}
// namespace modifier
else if (features.hasNamespaces && model.Namespaces.Count > 0)
foreach (KeyValuePair<string, Visibility> ns in model.Namespaces)
if (token == ns.Key)
{
curAccess = ns.Value;
curNamespace = token;
foundModifier = FlagType.Namespace;
}
}
// a declaration modifier was recognized
if (foundModifier != 0)
{
if (inParams && inValue) valueKeyword = new Token(curToken);
inParams = false;
inEnum = false;
inTypedef = false;
inAbstract = false;
inValue = false;
hadValue = false;
inConst = false;
inType = false;
inGeneric = false;
valueMember = null;
foundColon = false;
if (curNamespace == "internal") curNamespace = "";
if (context != 0)
{
modifiers = 0;
context = 0;
}
if (modifiers == 0)
{
modifiersLine = curToken.Line;
//modifiersPos = curToken.Position;
}
modifiers |= foundModifier;
return true;
}
}
}
// a declaration keyword was recognized
if (foundKeyword != 0)
{
if (dotIndex > 0)
{
// an unexpected keyword was found, ignore previous context
curToken.Text = token;
curToken.Line = line;
// TODO Should the parser note this error?
}
if (inParams && inValue) valueKeyword = new Token(curToken);
inParams = false;
inEnum = false;
inTypedef = false;
inAbstract = false;
inGeneric = false;
inValue = false;
hadValue = false;
inConst = false;
if (token != "function") valueMember = null;
foundColon = false;
foundConstant = false;
context = foundKeyword;
curModifiers = modifiers;
if (!isBlockComment) lastComment = null;
curComment = lastComment;
if (foundKeyword != FlagType.Import)
lastComment = null;
modifiers = 0;
curMember = null;
return true;
}
else
{
// when not in a class, parse if/for/while blocks
if (ScriptMode)
{
if (token == "catch" || (haXe && token == "for"))
{
curModifiers = 0;
foundKeyword = FlagType.Variable;
context = FlagType.Variable;
return false;
}
}
if (inValue && valueMember != null) valueMember = null;
if (!evalContext) return false;
if (dotIndex > 0) token = curToken.Text;
// some heuristic around Enums & Typedefs
if (inEnum && !inValue)
{
curModifiers = 0;
curAccess = Visibility.Public;
}
if (inTypedef && !inValue && curModifiers != FlagType.Extends)
{
curModifiers = 0;
curAccess = Visibility.Public;
}
else if (!inTypedef && curModifiers == FlagType.TypeDef && curClass != null && token != "extends")
{
curClass.ExtendsType = token;
curModifiers = 0;
context = 0;
curComment = null;
curClass = null;
curNamespace = "internal";
curAccess = 0;
modifiers = 0;
modifiersLine = 0;
return true;
}
}
/* EVAL DECLARATION */
if (foundColon && curMember != null)
{
foundColon = false;
if (haXe && curMember.Type != null) curMember.Type += " " + curToken.Text;
else curMember.Type = curToken.Text;
curMember.LineTo = curToken.Line;
// Typed Arrays
if (TypeCommentUtils.Parse(lastComment, curMember) != TypeDefinitionKind.Null)
lastComment = null;
}
else if (hadContext && (hadKeyword || inParams || inEnum || inTypedef))
{
MemberModel member;
switch (context)
{
case FlagType.Package:
if (prevToken.Text == "package")
{
model.Package = token;
model.Comments = curComment;
}
break;
case FlagType.Namespace:
if (prevToken.Text == "namespace")
{
if (!model.Namespaces.ContainsKey(token))
{
model.Namespaces.Add(token, curAccess);
// namespace is treated as a variable
member = new MemberModel();
member.Comments = curComment;
member.Name = token;
member.Type = "Namespace";
member.Flags = FlagType.Dynamic | FlagType.Variable | FlagType.Namespace;
member.Access = (curAccess == 0) ? features.varModifierDefault : curAccess;
member.Namespace = curNamespace;
member.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
member.LineTo = curToken.Line;
if (curClass != null) curClass.Members.Add(member);
else
{
member.InFile = model;
member.IsPackageLevel = true;
model.Members.Add(member);
}
}
}
break;
case FlagType.Import:
if (prevToken.Text == features.importKey)
{
member = new MemberModel();
member.Name = LastStringToken(token, ".");
member.Type = token;
member.LineFrom = prevToken.Line;
member.LineTo = curToken.Line;
member.Flags = (token.EndsWith("*")) ? FlagType.Package : FlagType.Class;
if (flattenNextBlock > 0) // this declaration is inside a config block
member.Flags |= FlagType.Constant;
model.Imports.Add(member);
}
else if (prevToken.Text == features.importKeyAlt)
{
member = new MemberModel();
member.Name = LastStringToken(token, ".");
member.Type = token;
member.LineFrom = prevToken.Line;
member.LineTo = curToken.Line;
member.Flags = FlagType.Class | FlagType.Using;
model.Imports.Add(member);
}
break;
case FlagType.Class:
case FlagType.Struct:
if (curModifiers == FlagType.Extends)
{
if (curClass != null)
{
// typed Array & Proxy
if ((token == "Array" || token == "Proxy" || token == "flash.utils.Proxy")
&& lastComment != null && ASFileParserRegexes.ValidTypeName.IsMatch(lastComment))
{
Match m = ASFileParserRegexes.ValidTypeName.Match(lastComment);
if (m.Success)
{
token += "<" + m.Groups["type"].Value + ">";
lastComment = null;
}
}
curClass.ExtendsType = token;
if (inTypedef) context = FlagType.TypeDef;
}
}
else if (curModifiers == FlagType.Implements)
{
if (curClass != null)
{
if (curClass.Implements == null) curClass.Implements = new List<string>();
curClass.Implements.Add(token);
}
}
else if ((context == FlagType.Class && (prevToken.Text == "class" || prevToken.Text == "interface"))
|| (context == FlagType.Struct && prevToken.Text == "struct"))
{
if (curClass != null)
{
curClass.LineTo = (modifiersLine != 0) ? modifiersLine - 1 : curToken.Line - 1;
}
// check classname
int p = token.LastIndexOf('.');
if (p > 0)
{
if (version < 3)
{
model.Package = token.Substring(0, p);
token = token.Substring(p + 1);
}
else
{
//TODO Error: AS3 & haXe classes are qualified by their package declaration
}
}
if (model.PrivateSectionIndex != 0 && curToken.Line > model.PrivateSectionIndex)
curAccess = Visibility.Private;
curClass = new ClassModel();
curClass.InFile = model;
curClass.Comments = curComment;
var qtype = QualifiedName(model, token);
curClass.Type = qtype.Type;
curClass.Template = qtype.Template;
curClass.Name = qtype.Name;
curClass.Constructor = (haXe) ? "new" : token;
curClass.Flags = curModifiers;
curClass.Access = (curAccess == 0) ? features.classModifierDefault : curAccess;
curClass.Namespace = curNamespace;
curClass.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
curClass.LineTo = curToken.Line;
AddClass(model, curClass);
}
else
{
context = 0;
modifiers = 0;
}
if (carriedMetaData != null)
{
if (model.MetaDatas == null)
model.MetaDatas = carriedMetaData;
else
foreach (var meta in carriedMetaData) model.MetaDatas.Add(meta);
carriedMetaData = null;
}
break;
case FlagType.Enum:
if (inEnum && curClass != null && prevToken.Text != "enum")
{
member = new MemberModel();
member.Comments = curComment;
member.Name = token;
member.Flags = curModifiers | FlagType.Variable | FlagType.Enum | FlagType.Static;
member.Access = Visibility.Public;
member.Namespace = curNamespace;
member.LineFrom = member.LineTo = curToken.Line;
curClass.Members.Add(member);
//
curMember = member;
}
else
{
if (curClass != null)
{
curClass.LineTo = (modifiersLine != 0) ? modifiersLine - 1 : curToken.Line - 1;
}
curClass = new ClassModel();
curClass.InFile = model;
curClass.Comments = curComment;
var qtype = QualifiedName(model, token);
curClass.Type = qtype.Type;
curClass.Template = qtype.Template;
curClass.Name = qtype.Name;
curClass.Flags = curModifiers;
curClass.Access = (curAccess == 0) ? features.enumModifierDefault : curAccess;
curClass.Namespace = curNamespace;
curClass.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
curClass.LineTo = curToken.Line;
AddClass(model, curClass);
}
break;
case FlagType.TypeDef:
if (curModifiers == FlagType.Extends) // cached syntax
{
if (curClass != null)
{
curClass.ExtendsType = token;
}
}
else if (inTypedef && curClass != null && prevToken.Text != "typedef")
{
member = new MemberModel();
member.Comments = curComment;
member.Name = token;
member.Flags = curModifiers | FlagType.Variable | FlagType.Dynamic;
member.Access = Visibility.Public;
member.Namespace = curNamespace;
member.LineFrom = member.LineTo = curToken.Line;
curClass.Members.Add(member);
//
curMember = member;
}
else
{
if (curClass != null)
{
curClass.LineTo = (modifiersLine != 0) ? modifiersLine - 1 : curToken.Line - 1;
}
curClass = new ClassModel();
curClass.InFile = model;
curClass.Comments = curComment;
var qtype = QualifiedName(model, token);
curClass.Type = qtype.Type;
curClass.Template = qtype.Template;
curClass.Name = qtype.Name;
curClass.Flags = FlagType.Class | FlagType.TypeDef;
curClass.Access = (curAccess == 0) ? features.typedefModifierDefault : curAccess;
curClass.Namespace = curNamespace;
curClass.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
curClass.LineTo = curToken.Line;
AddClass(model, curClass);
}
break;
case FlagType.Abstract:
if (inAbstract && curClass != null && prevToken.Text != "abstract")
{
member = new MemberModel();
member.Comments = curComment;
member.Name = token;
member.Flags = curModifiers | FlagType.Variable | FlagType.Dynamic;
member.Access = Visibility.Public;
member.Namespace = curNamespace;
member.LineFrom = member.LineTo = curToken.Line;
curClass.Members.Add(member);
//
curMember = member;
}
else if (!inAbstract && curClass != null && (curClass.Flags & FlagType.Abstract) > 0)
{
if (prevToken.Text == "to") { /* can be casted to X */ }
else curClass.ExtendsType = curToken.Text;
}
else
{
if (curClass != null)
{
curClass.LineTo = (modifiersLine != 0) ? modifiersLine - 1 : curToken.Line - 1;
}
curClass = new ClassModel();
curClass.InFile = model;
curClass.Comments = curComment;
var qtype = QualifiedName(model, token);
curClass.Type = qtype.Type;
curClass.Template = qtype.Template;
curClass.Name = qtype.Name;
curClass.Flags = FlagType.Class | FlagType.Abstract;
curClass.Access = (curAccess == 0) ? features.typedefModifierDefault : curAccess;
curClass.Namespace = curNamespace;
curClass.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
curClass.LineTo = curToken.Line;
AddClass(model, curClass);
}
break;
case FlagType.Variable:
// haXe signatures: T -> T
if (haXe && curMember != null && curMember.Type != null
&& curMember.Type.EndsWith("->"))
{
curMember.Type += " " + token;
return false;
}
else
{
member = new MemberModel();
member.Comments = curComment;
member.Name = token;
if ((curModifiers & FlagType.Static) == 0) curModifiers |= FlagType.Dynamic;
member.Flags = curModifiers | FlagType.Variable;
member.Access = (curAccess == 0) ? features.varModifierDefault : curAccess;
member.Namespace = curNamespace;
member.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
member.LineTo = curToken.Line;
//
// method parameter
if (inParams && curMethod != null)
{
member.Flags = FlagType.Variable | FlagType.ParameterVar;
if (inEnum) member.Flags |= FlagType.Enum;
if (curMethod.Parameters == null) curMethod.Parameters = new List<MemberModel>();
member.Access = 0;
if (member.Name.Length > 0)
curMethod.Parameters.Add(member);
}
// class member
else if (curClass != null)
{
FlagType forcePublic = FlagType.Interface;
if (haXe) forcePublic |= FlagType.Intrinsic | FlagType.TypeDef;
if ((curClass.Flags & forcePublic) > 0)
member.Access = Visibility.Public;
curClass.Members.Add(member);
curClass.LineTo = member.LineTo;
}
// package member
else
{
member.InFile = model;
member.IsPackageLevel = true;
model.Members.Add(member);
}
//
curMember = member;
if (carriedMetaData != null)
{
if (member.MetaDatas == null)
member.MetaDatas = carriedMetaData;
else
foreach (var meta in carriedMetaData) member.MetaDatas.Add(meta);
carriedMetaData = null;
}
}
break;
case FlagType.Function:
member = new MemberModel();
member.Comments = curComment;
int t = token.IndexOf('<');
if (t > 0)
{
member.Template = token.Substring(t);
token = token.Substring(0, t);
}
member.Name = token;
if ((curModifiers & FlagType.Static) == 0) curModifiers |= FlagType.Dynamic;
if ((curModifiers & (FlagType.Getter | FlagType.Setter)) == 0)
curModifiers |= FlagType.Function;
member.Flags = curModifiers;
member.Access = (curAccess == 0) ? features.methodModifierDefault : curAccess;
member.Namespace = curNamespace;
member.LineFrom = (modifiersLine != 0) ? modifiersLine : curToken.Line;
member.LineTo = curToken.Line;
//
if (curClass != null)
{
if (token == curClass.Constructor)
{
if (haXe) // constructor is: new()
{
member.Name = curClass.Name;
curClass.Constructor = curClass.Name;
}
member.Flags |= FlagType.Constructor;
if ((member.Flags & FlagType.Dynamic) > 0) member.Flags -= FlagType.Dynamic;
if (curAccess == 0) curAccess = Visibility.Public;
}
FlagType forcePublic = FlagType.Interface;
if (haXe) forcePublic |= FlagType.Intrinsic | FlagType.TypeDef;
if (curAccess == 0 && (curClass.Flags & forcePublic) > 0)
member.Access = Visibility.Public;
curClass.Members.Add(member);
curClass.LineTo = member.LineTo;
}
// package-level function
else
{
member.InFile = model;
member.IsPackageLevel = true;
model.Members.Add(member);
}
//
curMember = member;
if (carriedMetaData != null)
{
if (member.MetaDatas == null)
member.MetaDatas = carriedMetaData;
else
foreach (var meta in carriedMetaData) member.MetaDatas.Add(meta);
carriedMetaData = null;
}
break;
}
if (context != FlagType.Function && !inParams) curMethod = null;
curComment = null;
curNamespace = "internal";
curAccess = 0;
modifiers = 0;
modifiersLine = 0;
inGeneric = false;
tryPackage = false;
}
return false;
}
private void AddClass(FileModel model, ClassModel curClass)
{
// avoid empty duplicates due to Haxe directives
foreach(ClassModel aClass in model.Classes)
if (aClass.Name == curClass.Name)
{
if (aClass.Members.Count == 0)
{
model.Classes.Remove(aClass);
break;
}
else return;
}
model.Classes.Add(curClass);
}
#endregion
#region tool methods
public QType QualifiedName(FileModel InFile, string Name)
{
var qt = new QType();
var type = Name;
if (InFile.Package == "") type = Name;
else if (InFile.Module == "" || InFile.Module == Name) type = InFile.Package + "." + Name;
else type = InFile.Package + "." + InFile.Module + "." + Name;
qt.Type = type;
int p = Name.IndexOf('<');
if (p > 0)
{
qt.Template = Name.Substring(p);
if (Name[p - 1] == '.') p--;
qt.Name = Name.Substring(0, p);
}
else qt.Name = Name;
return qt;
}
private String LastStringToken(string token, string separator)
{
int p = token.LastIndexOf(separator);
return (p >= 0) ? token.Substring(p + 1) : token;
}
#endregion
}
public class QType
{
public string Name;
public string Type;
public string Template;
}
}
| 42.822897 | 165 | 0.354801 | [
"MIT"
] | SlavaRa/flashdevelop-macros | External/Plugins/ASCompletion/Model/ASFileParser.cs | 111,468 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsReptRequest.
/// </summary>
public partial interface IWorkbookFunctionsReptRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
WorkbookFunctionsReptRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>TheWorkbookFunctionResult</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsReptRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsReptRequest Select(string value);
}
}
| 36.388889 | 153 | 0.584733 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsReptRequest.cs | 1,965 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PettyCashApp
{
public partial class MainPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
check_multiple_login();
}
}
public void check_multiple_login()
{
if (Session["is_login"] == null)
{
Response.Redirect("~/Login.aspx");
}
else
{
if (Session["is_login"].ToString() == "t")
{
if (Session["role"].ToString() == "User")
{
Response.Redirect("~/user/dash.aspx");
}
else if (Session["role"].ToString() == "HR")
{
Response.Redirect("~/hr/dash.aspx");
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
}
}
} | 26.304348 | 64 | 0.405785 | [
"MIT"
] | agailevictor/pettycashapp | PettyCash/PettyCashApp/MainPage.aspx.cs | 1,212 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageManager
{
static MessageManager mInstance;
public static MessageManager Instatnce
{
get
{
return mInstance ?? (mInstance = new MessageManager());
}
}
Dictionary<string, Action<object[]>> mMessageDict = new Dictionary<string, Action<object[]>>(32);
Dictionary<string, object[]> mDispatchCacheDict = new Dictionary<string, object[]>(16);
private MessageManager() { }
public void Subscribe(string message, Action<object[]> action)
{
Action<object[]> value = null;
if (mMessageDict.TryGetValue(message, out value))
{
value += action;
mMessageDict[message] = value;
}
else
{
mMessageDict.Add(message, action);
}
}
public void Unsubscribe(string message)
{
mMessageDict.Remove(message);
}
public void Dispatch(string message, object[] args = null, bool addToCache = false)
{
if (addToCache)
{
mDispatchCacheDict[message] = args;
}
else
{
Action<object[]> value = null;
if (mMessageDict.TryGetValue(message, out value))
{
value.Invoke(args);
}
}
}
public void ProcessDispatchCache(string message)
{
object[] value = null;
if (mDispatchCacheDict.TryGetValue(message, out value))
{
Dispatch(message, value);
mDispatchCacheDict.Remove(message);
}
}
}
| 23.671429 | 101 | 0.572722 | [
"MIT"
] | Ryan4G/unity3d-action-gametech | Assets/Scripts/ActionGame/ActionGameCommon/MessageManager.cs | 1,659 | C# |
namespace QuantumLogic.WebApi.DataModels.Dtos.Shared.Error
{
public class ValidationFailureDto : FailureDto
{
public string Severity { get; set; }
public string PropertyName { get; set; }
#region Ctors
protected ValidationFailureDto()
: base()
{ }
public ValidationFailureDto(string propertyName, string severity, string message)
: base(message)
{
PropertyName = propertyName;
Severity = severity;
}
#endregion
}
}
| 23 | 89 | 0.586957 | [
"CC0-1.0"
] | elrondsoft/vipdrv | src/api/QuantumLogic/DataModels/Dtos/Shared/Error/ValidationFailureDto.cs | 554 | C# |
using System;
namespace Editor_Mono.Cecil
{
[Flags]
public enum AssemblyAttributes : uint
{
PublicKey = 1u,
SideBySideCompatible = 0u,
Retargetable = 256u,
WindowsRuntime = 512u,
DisableJITCompileOptimizer = 16384u,
EnableJITCompileTracking = 32768u
}
}
| 18 | 38 | 0.748148 | [
"BSD-2-Clause"
] | ErQing/cshotfix | CSHotFix_ILRuntimeSimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil/AssemblyAttributes.cs | 270 | C# |
using System;
using System.Collections.Generic;
using RestSharp;
using IO.Swagger.Client;
using IO.Swagger.Model;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IRSASignaturesApi
{
/// <summary>
/// Decrypt RSA signature The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. You use rsa_signatures to generate the required digital signature and token for a Payment Pages 2.0 form, and then you use the decrypt REST service to decrypt the signature to validate the signature and key. This REST service should be used only when you implement Payment Pages 2.0.
/// </summary>
/// <param name="request"></param>
/// <returns>POSTDecryptResponseType</returns>
POSTDecryptResponseType POSTDecryptResponse (POSTDecryptionType request);
/// <summary>
/// Generate RSA signature The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. The POST rsa_signatures call generates and returns the required digital signature and token for a Payment Pages 2.0 form. You need to pass the generated signature to your client for it to access Payment Pages 2.0. This REST service should be used only when you implement Payment Pages 2.0.
/// </summary>
/// <param name="request"></param>
/// <returns>POSTRSASignatureResponseType</returns>
POSTRSASignatureResponseType POSTRSASignature (POSTRSASignatureType request);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class RSASignaturesApi : IRSASignaturesApi
{
/// <summary>
/// Initializes a new instance of the <see cref="RSASignaturesApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public RSASignaturesApi(ApiClient apiClient = null)
{
if (apiClient == null) // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
else
this.ApiClient = apiClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="RSASignaturesApi"/> class.
/// </summary>
/// <returns></returns>
public RSASignaturesApi(String basePath)
{
this.ApiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <param name="basePath">The base path</param>
/// <value>The base path</value>
public void SetBasePath(String basePath)
{
this.ApiClient.BasePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <param name="basePath">The base path</param>
/// <value>The base path</value>
public String GetBasePath(String basePath)
{
return this.ApiClient.BasePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>An instance of the ApiClient</value>
public ApiClient ApiClient {get; set;}
/// <summary>
/// Decrypt RSA signature The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. You use rsa_signatures to generate the required digital signature and token for a Payment Pages 2.0 form, and then you use the decrypt REST service to decrypt the signature to validate the signature and key. This REST service should be used only when you implement Payment Pages 2.0.
/// </summary>
/// <param name="request"></param>
/// <returns>POSTDecryptResponseType</returns>
public POSTDecryptResponseType POSTDecryptResponse (POSTDecryptionType request)
{
// verify the required parameter 'request' is set
if (request == null) throw new ApiException(400, "Missing required parameter 'request' when calling POSTDecryptResponse");
var path = "/rsa-signatures/decrypt";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
postBody = ApiClient.Serialize(request); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400)
throw new ApiException ((int)response.StatusCode, "Error calling POSTDecryptResponse: " + response.Content, response.Content);
else if (((int)response.StatusCode) == 0)
throw new ApiException ((int)response.StatusCode, "Error calling POSTDecryptResponse: " + response.ErrorMessage, response.ErrorMessage);
return (POSTDecryptResponseType) ApiClient.Deserialize(response.Content, typeof(POSTDecryptResponseType), response.Headers);
}
/// <summary>
/// Generate RSA signature The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. The POST rsa_signatures call generates and returns the required digital signature and token for a Payment Pages 2.0 form. You need to pass the generated signature to your client for it to access Payment Pages 2.0. This REST service should be used only when you implement Payment Pages 2.0.
/// </summary>
/// <param name="request"></param>
/// <returns>POSTRSASignatureResponseType</returns>
public POSTRSASignatureResponseType POSTRSASignature (POSTRSASignatureType request)
{
// verify the required parameter 'request' is set
if (request == null) throw new ApiException(400, "Missing required parameter 'request' when calling POSTRSASignature");
var path = "/rsa-signatures";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
postBody = ApiClient.Serialize(request); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400)
throw new ApiException ((int)response.StatusCode, "Error calling POSTRSASignature: " + response.Content, response.Content);
else if (((int)response.StatusCode) == 0)
throw new ApiException ((int)response.StatusCode, "Error calling POSTRSASignature: " + response.ErrorMessage, response.ErrorMessage);
return (POSTRSASignatureResponseType) ApiClient.Deserialize(response.Content, typeof(POSTRSASignatureResponseType), response.Headers);
}
}
}
| 52.477707 | 463 | 0.633451 | [
"Apache-2.0"
] | curtisHildebrant/quickstart-dotnet | src/main/CsharpDotNet2/IO/Swagger/Api/RSASignaturesApi.cs | 8,239 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Otus.Teaching.Pcf.Administration.WebHost.Models;
using Otus.Teaching.Pcf.Administration.Core.Abstractions.Repositories;
using Otus.Teaching.Pcf.Administration.Core.Domain.Administration;
namespace Otus.Teaching.Pcf.Administration.WebHost.Controllers
{
/// <summary>
/// Роли сотрудников
/// </summary>
[ApiController]
[Route("api/v1/[controller]")]
public class RolesController
{
private readonly IRepository<Role> _rolesRepository;
public RolesController(IRepository<Role> rolesRepository)
{
_rolesRepository = rolesRepository;
}
/// <summary>
/// Получить все доступные роли сотрудников
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IEnumerable<RoleItemResponse>> GetRolesAsync()
{
var roles = await _rolesRepository.GetAllAsync();
var rolesModelList = roles.Select(x =>
new RoleItemResponse()
{
Id = x.Id,
Name = x.Name,
Description = x.Description
}).ToList();
return rolesModelList;
}
}
} | 29.644444 | 72 | 0.607946 | [
"MIT"
] | a-kozhanov/otus-csharp-asp.net-core-developer | otus.teaching.promocodefactory.homework.messagebroker/Otus.Teaching.Pcf.Administration/Otus.Teaching.Pcf.Administration.WebHost/Controllers/RolesController.cs | 1,386 | C# |
// <auto-generated> - Template:MvvmLightModelObject, Version:1.1, Id:c644a31c-7ebc-4383-bc7f-0ea7c5bf6ed4
using GalaSoft.MvvmLight;
namespace CGH.QuikRide.Xam.ModelObj.QR
{
public partial class VehicleFeatureType : ObservableObject
{
public VehicleFeatureType()
{
VehicleFeatureTypeTranslations = new System.Collections.Generic.List<VehicleFeatureTypeTranslation>(); // Reverse Navigation
VehicleTypeVehicleFeatureTypes = new System.Collections.Generic.List<VehicleTypeVehicleFeatureType>(); // Reverse Navigation
VehicleVehicleFeatureTypes = new System.Collections.Generic.List<VehicleVehicleFeatureType>(); // Reverse Navigation
InitializePartial();
}
private string _code;
private string _createdBy;
private System.DateTime _createdUtcDate;
private int _dataVersion;
private bool _isDeleted;
private string _modifiedBy;
private System.DateTime _modifiedUtcDate;
private int _vehicleFeatureTypeId;
public string Code
{
get { return _code; }
set
{
Set<string>(() => Code, ref _code, value);
RunCustomLogicSetCode(value);
}
}
public string CreatedBy
{
get { return _createdBy; }
set
{
Set<string>(() => CreatedBy, ref _createdBy, value);
RunCustomLogicSetCreatedBy(value);
}
}
public System.DateTime CreatedUtcDate
{
get { return _createdUtcDate; }
set
{
Set<System.DateTime>(() => CreatedUtcDate, ref _createdUtcDate, value);
RunCustomLogicSetCreatedUtcDate(value);
}
}
public int DataVersion
{
get { return _dataVersion; }
set
{
Set<int>(() => DataVersion, ref _dataVersion, value);
RunCustomLogicSetDataVersion(value);
}
}
public bool IsDeleted
{
get { return _isDeleted; }
set
{
Set<bool>(() => IsDeleted, ref _isDeleted, value);
RunCustomLogicSetIsDeleted(value);
}
}
public string ModifiedBy
{
get { return _modifiedBy; }
set
{
Set<string>(() => ModifiedBy, ref _modifiedBy, value);
RunCustomLogicSetModifiedBy(value);
}
}
public System.DateTime ModifiedUtcDate
{
get { return _modifiedUtcDate; }
set
{
Set<System.DateTime>(() => ModifiedUtcDate, ref _modifiedUtcDate, value);
RunCustomLogicSetModifiedUtcDate(value);
}
}
public int VehicleFeatureTypeId
{
get { return _vehicleFeatureTypeId; }
set
{
Set<int>(() => VehicleFeatureTypeId, ref _vehicleFeatureTypeId, value);
RunCustomLogicSetVehicleFeatureTypeId(value);
}
}
public virtual System.Collections.Generic.IList<VehicleFeatureTypeTranslation> VehicleFeatureTypeTranslations { get; set; } // Many to many mapping
public virtual System.Collections.Generic.IList<VehicleTypeVehicleFeatureType> VehicleTypeVehicleFeatureTypes { get; set; } // Many to many mapping
public virtual System.Collections.Generic.IList<VehicleVehicleFeatureType> VehicleVehicleFeatureTypes { get; set; } // Many to many mapping
partial void InitializePartial();
#region RunCustomLogicSet
partial void RunCustomLogicSetCode(string value);
partial void RunCustomLogicSetCreatedBy(string value);
partial void RunCustomLogicSetCreatedUtcDate(System.DateTime value);
partial void RunCustomLogicSetDataVersion(int value);
partial void RunCustomLogicSetIsDeleted(bool value);
partial void RunCustomLogicSetModifiedBy(string value);
partial void RunCustomLogicSetModifiedUtcDate(System.DateTime value);
partial void RunCustomLogicSetVehicleFeatureTypeId(int value);
#endregion RunCustomLogicSet
}
}
| 27.27907 | 149 | 0.740551 | [
"MIT"
] | MSCTek/QuikRide | src/CGH.QuikRide.Xam/QuikRide/CGH_ModelObj/VehicleFeatureType.cs | 3,519 | C# |
using System.Text.Json.Serialization;
namespace Boxi.Core.DTOs
{
public record EntityAddedDto
{
public EntityAddedDto(int id)
{
Id = id;
}
[JsonPropertyName("id")]
public int Id { get; init; }
}
} | 18.066667 | 38 | 0.531365 | [
"Apache-2.0"
] | Tappau/Boxi | Boxi/Boxi.Core/DTOs/EntityAddedDto.cs | 273 | 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.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.PdbUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class EditAndContinueStateMachineTests : EditAndContinueTestBase
{
[Fact]
public void AddIteratorMethod()
{
var source0 =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object> F()
{
yield return 0;
}
static void M()
{
}
}";
var source1 =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object> F()
{
yield return 0;
}
static IEnumerable<int> G()
{
yield return 1;
}
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib(Parse(source1, "a.cs"), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.G"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(20, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(21, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(22, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(23, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(24, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(25, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(26, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(27, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(28, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(29, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(26, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(5, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(6, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(3, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(4, TableIndex.Property, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(6, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(8, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(9, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(10, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(23, TableIndex.TypeRef),
Handle(24, TableIndex.TypeRef),
Handle(25, TableIndex.TypeRef),
Handle(26, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(4, TableIndex.Field),
Handle(5, TableIndex.Field),
Handle(6, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(16, TableIndex.MethodDef),
Handle(17, TableIndex.MethodDef),
Handle(18, TableIndex.MethodDef),
Handle(19, TableIndex.MethodDef),
Handle(20, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(6, TableIndex.InterfaceImpl),
Handle(7, TableIndex.InterfaceImpl),
Handle(8, TableIndex.InterfaceImpl),
Handle(9, TableIndex.InterfaceImpl),
Handle(10, TableIndex.InterfaceImpl),
Handle(17, TableIndex.MemberRef),
Handle(18, TableIndex.MemberRef),
Handle(19, TableIndex.MemberRef),
Handle(20, TableIndex.MemberRef),
Handle(21, TableIndex.MemberRef),
Handle(22, TableIndex.MemberRef),
Handle(23, TableIndex.MemberRef),
Handle(24, TableIndex.MemberRef),
Handle(25, TableIndex.MemberRef),
Handle(26, TableIndex.MemberRef),
Handle(27, TableIndex.MemberRef),
Handle(28, TableIndex.MemberRef),
Handle(29, TableIndex.MemberRef),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(5, TableIndex.StandAloneSig),
Handle(6, TableIndex.StandAloneSig),
Handle(2, TableIndex.PropertyMap),
Handle(3, TableIndex.Property),
Handle(4, TableIndex.Property),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics),
Handle(8, TableIndex.MethodImpl),
Handle(9, TableIndex.MethodImpl),
Handle(10, TableIndex.MethodImpl),
Handle(11, TableIndex.MethodImpl),
Handle(12, TableIndex.MethodImpl),
Handle(13, TableIndex.MethodImpl),
Handle(14, TableIndex.MethodImpl),
Handle(3, TableIndex.TypeSpec),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass));
}
string actualPdb1 = PdbToXmlConverter.DeltaPdbToXml(diff1.PdbDelta, Enumerable.Range(1, 100).Select(rid => 0x06000000U | (uint)rid));
// TODO (tomat): bug in SymWriter.
// The PDB is missing debug info for G method. The info is written to the PDB but the native SymWriter
// seems to ignore it. If another method is added to the class all information is written.
// This happens regardless of whether we emit just the delta or full PDB.
string expectedPdb1 = @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""3f5162f8-07c6-11d3-9053-00c04fa302a1"" languageVendor=""994b45c4-e6e9-11d2-903f-00c04fa302a1"" documentType=""5a869d0b-6611-11d3-bd2a-0000f80849bd"" checkSumAlgorithmId=""ff1816ec-aa5e-4d10-87f7-6f4963833460"" checkSum=""6E, 19, 36, 2B, 9A, 28, AB, E3, A2, DA, EB, 51, C1, 37, 1, 10, B0, 4F, CA, 84, "" />
</files>
<methods>
<method token=""0x600000f"">
<customDebugInfo version=""4"" count=""1"">
<using version=""4"" kind=""UsingInfo"" size=""12"" namespaceCount=""1"">
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencepoints total=""5"">
<entry il_offset=""0x0"" hidden=""true"" start_row=""16707566"" start_column=""0"" end_row=""16707566"" end_column=""0"" file_ref=""1"" />
<entry il_offset=""0x21"" start_row=""9"" start_column=""5"" end_row=""9"" end_column=""6"" file_ref=""1"" />
<entry il_offset=""0x22"" start_row=""10"" start_column=""9"" end_row=""10"" end_column=""24"" file_ref=""1"" />
<entry il_offset=""0x34"" hidden=""true"" start_row=""16707566"" start_column=""0"" end_row=""16707566"" end_column=""0"" file_ref=""1"" />
<entry il_offset=""0x3b"" start_row=""11"" start_column=""5"" end_row=""11"" end_column=""6"" file_ref=""1"" />
</sequencepoints>
<locals>
<local name=""CS$524$0000"" il_index=""0"" il_start=""0x0"" il_end=""0x3f"" attributes=""0"" />
</locals>
<scope startOffset=""0x0"" endOffset=""0x3f"">
<namespace name=""System.Collections.Generic"" />
<local name=""CS$524$0000"" il_index=""0"" il_start=""0x0"" il_end=""0x3f"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>";
AssertXmlEqual(expectedPdb1, actualPdb1);
}
[Fact]
public void AddAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Add state machine type and its members:
// - Method '.ctor'
// - Method 'MoveNext'
// - Method 'SetStateMachine'
// - Field '<>1__state'
// - Field '<>t__builder'
// - Field '<>u__$awaiter0'
// Add method F()
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodToIteratorMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void MethodToAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void IteratorMethodToMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void AsyncMethodToMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void UpdateIterator_NoVariables()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 1;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 3 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't an iterator)
// - Finally method
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (int V_0, //CS$524$0000
bool V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_001a
IL_0014: br.s IL_0034
IL_0016: ldc.i4.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ret
IL_001a: ldarg.0
IL_001b: ldc.i4.m1
IL_001c: stfld ""int C.<F>d__0.<>1__state""
IL_0021: nop
IL_0022: ldarg.0
IL_0023: ldc.i4.2
IL_0024: stfld ""int C.<F>d__0.<>2__current""
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int C.<F>d__0.<>1__state""
IL_0030: ldc.i4.1
IL_0031: stloc.1
IL_0032: br.s IL_0018
IL_0034: ldarg.0
IL_0035: ldc.i4.m1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.0
IL_003c: stloc.1
IL_003d: br.s IL_0018
}
");
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (int V_0, //CS$524$0000
bool V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_001a
IL_0014: br.s IL_0034
IL_0016: ldc.i4.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ret
IL_001a: ldarg.0
IL_001b: ldc.i4.m1
IL_001c: stfld ""int C.<F>d__0.<>1__state""
IL_0021: nop
IL_0022: ldarg.0
IL_0023: ldc.i4.1
IL_0024: stfld ""int C.<F>d__0.<>2__current""
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int C.<F>d__0.<>1__state""
IL_0030: ldc.i4.1
IL_0031: stloc.1
IL_0032: br.s IL_0018
IL_0034: ldarg.0
IL_0035: ldc.i4.m1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.0
IL_003c: stloc.1
IL_003d: br.s IL_0018
}");
}
}
}
[Fact]
public void UpdateAsync_NoVariables()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
return 2;
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(new SemanticEdit(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 2 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't async)
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 171 (0xab)
.maxstack 3
.locals init (int V_0, //CS$524$0000
int V_1, //CS$523$0001
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__1 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0049
IL_000e: nop
IL_000f: ldc.i4.s 10
IL_0011: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0016: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001b: stloc.2
IL_001c: ldloca.s V_2
IL_001e: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0023: brtrue.s IL_0065
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: dup
IL_0028: stloc.0
IL_0029: stfld ""int C.<F>d__1.<>1__state""
IL_002e: ldarg.0
IL_002f: ldloc.2
IL_0030: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_0035: ldarg.0
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_003d: ldloca.s V_2
IL_003f: ldloca.s V_3
IL_0041: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
IL_0046: nop
IL_0047: leave.s IL_00aa
IL_0049: ldarg.0
IL_004a: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_004f: stloc.2
IL_0050: ldarg.0
IL_0051: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_0056: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005c: ldarg.0
IL_005d: ldc.i4.m1
IL_005e: dup
IL_005f: stloc.0
IL_0060: stfld ""int C.<F>d__1.<>1__state""
IL_0065: ldloca.s V_2
IL_0067: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006c: pop
IL_006d: ldloca.s V_2
IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0075: ldc.i4.s 20
IL_0077: stloc.1
IL_0078: leave.s IL_0095
}
catch System.Exception
{
IL_007a: stloc.s V_4
IL_007c: nop
IL_007d: ldarg.0
IL_007e: ldc.i4.s -2
IL_0080: stfld ""int C.<F>d__1.<>1__state""
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_008b: ldloc.s V_4
IL_008d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0092: nop
IL_0093: leave.s IL_00aa
}
IL_0095: ldarg.0
IL_0096: ldc.i4.s -2
IL_0098: stfld ""int C.<F>d__1.<>1__state""
IL_009d: ldarg.0
IL_009e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00a3: ldloc.1
IL_00a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00a9: nop
IL_00aa: ret
}
");
v0.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 169 (0xa9)
.maxstack 3
.locals init (int V_0, //CS$524$0000
int V_1, //CS$523$0001
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__1 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0048
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001a: stloc.2
IL_001b: ldloca.s V_2
IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0022: brtrue.s IL_0064
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.0
IL_0028: stfld ""int C.<F>d__1.<>1__state""
IL_002d: ldarg.0
IL_002e: ldloc.2
IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_0034: ldarg.0
IL_0035: stloc.3
IL_0036: ldarg.0
IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_003c: ldloca.s V_2
IL_003e: ldloca.s V_3
IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
IL_0045: nop
IL_0046: leave.s IL_00a8
IL_0048: ldarg.0
IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_004e: stloc.2
IL_004f: ldarg.0
IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__$awaiter0""
IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005b: ldarg.0
IL_005c: ldc.i4.m1
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int C.<F>d__1.<>1__state""
IL_0064: ldloca.s V_2
IL_0066: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006b: pop
IL_006c: ldloca.s V_2
IL_006e: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0074: ldc.i4.2
IL_0075: stloc.1
IL_0076: leave.s IL_0093
}
catch System.Exception
{
IL_0078: stloc.s V_4
IL_007a: nop
IL_007b: ldarg.0
IL_007c: ldc.i4.s -2
IL_007e: stfld ""int C.<F>d__1.<>1__state""
IL_0083: ldarg.0
IL_0084: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_0089: ldloc.s V_4
IL_008b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0090: nop
IL_0091: leave.s IL_00a8
}
IL_0093: ldarg.0
IL_0094: ldc.i4.s -2
IL_0096: stfld ""int C.<F>d__1.<>1__state""
IL_009b: ldarg.0
IL_009c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00a1: ldloc.1
IL_00a2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00a7: nop
IL_00a8: ret
}
");
}
}
}
}
}
| 47.45158 | 350 | 0.61087 | [
"Apache-2.0"
] | sperling/cskarp | Src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueStateMachineTests.cs | 46,552 | C# |
using Umbraco.Cms.Infrastructure.Persistence;
namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_8_15_0
{
public class UpdateCmsPropertyGroupIdSeed : MigrationBase
{
public UpdateCmsPropertyGroupIdSeed(IMigrationContext context) : base(context)
{
}
protected override void Migrate()
{
// NOOP - was sql ce only
}
}
}
| 23.411765 | 86 | 0.660804 | [
"MIT"
] | Lantzify/Umbraco-CMS | src/Umbraco.Infrastructure/Migrations/Upgrade/V_8_15_0/UpdateCmsPropertyGroupIdSeed.cs | 398 | C# |
using GameSpec.Formats.Unknown;
using System.Threading.Tasks;
namespace GameSpec.Rsi.Transforms
{
/// <summary>
/// UnknownTransform
/// </summary>
public static class UnknownTransform
{
internal static bool CanTransformFileObject(PakFile left, PakFile right, object source) => Cry.Transforms.UnknownTransform.CanTransformFileObject(left, right, source);
internal static Task<IUnknownFileModel> TransformFileObjectAsync(PakFile left, PakFile right, object source) => Cry.Transforms.UnknownTransform.TransformFileObjectAsync(left, right, source);
}
} | 43.142857 | 199 | 0.741722 | [
"MIT"
] | bclnet/GameSpec | Rsi/GameSpec.Rsi/Transforms/UnknownTransform.cs | 606 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DiceBot.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DiceBot.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.375 | 174 | 0.598592 | [
"MIT"
] | kennetanti/DiceBot | DiceBot/Properties/Resources.Designer.cs | 2,842 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionPage.cs.tt
namespace Microsoft.Graph
{
using System;
/// <summary>
/// The type GraphServiceConnectionsCollectionPage.
/// </summary>
public partial class GraphServiceConnectionsCollectionPage : CollectionPage<ExternalConnection>, IGraphServiceConnectionsCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IGraphServiceConnectionsCollectionRequest"/> instance.
/// </summary>
public IGraphServiceConnectionsCollectionRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new GraphServiceConnectionsCollectionRequest(
nextPageLinkString,
client,
null);
}
}
}
}
| 38.025641 | 153 | 0.583277 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/GraphServiceConnectionsCollectionPage.cs | 1,483 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text; // StringBuilder
namespace System.Data.Odbc
{
public sealed class OdbcDataReader : DbDataReader
{
private OdbcCommand? _command;
private int _recordAffected = -1;
private FieldNameLookup? _fieldNameLookup;
private DbCache? _dataCache;
private enum HasRowsStatus
{
DontKnow = 0,
HasRows = 1,
HasNoRows = 2,
}
private HasRowsStatus _hasRows = HasRowsStatus.DontKnow;
private bool _isClosed;
private bool _isRead;
private bool _isValidResult;
private bool _noMoreResults;
private bool _noMoreRows;
private bool _skipReadOnce;
private int _hiddenColumns; // number of hidden columns
private readonly CommandBehavior _commandBehavior;
// track current row and column, will be set on the first Fetch call
private int _row = -1;
private int _column = -1;
// used to track position in field for sucessive reads in case of Sequential Access
private long _sequentialBytesRead;
private static int s_objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
// the statement handle here is just a copy of the statement handle owned by the command
// the DataReader must not free the statement handle. this is done by the command
//
private MetaData[]? _metadata;
private DataTable? _schemaTable; // MDAC 68336
private readonly string _cmdText; // get a copy in case the command text on the command is changed ...
private CMDWrapper? _cmdWrapper;
internal OdbcDataReader(OdbcCommand command, CMDWrapper cmdWrapper, CommandBehavior commandbehavior)
{
Debug.Assert(command != null, "Command null on OdbcDataReader ctor");
_command = command;
_commandBehavior = commandbehavior;
_cmdText = command.CommandText; // get a copy in case the command text on the command is changed ...
_cmdWrapper = cmdWrapper;
}
private CNativeBuffer Buffer
{
get
{
CNativeBuffer? value = _cmdWrapper!._dataReaderBuf;
if (null == value)
{
Debug.Fail("object is disposed");
throw new ObjectDisposedException(GetType().Name);
}
return value;
}
}
private OdbcConnection? Connection
{
get
{
if (null != _cmdWrapper)
{
return _cmdWrapper.Connection;
}
else
{
return null;
}
}
}
internal OdbcCommand? Command
{
get
{
return _command;
}
set
{
_command = value;
}
}
private OdbcStatementHandle StatementHandle
{
get
{
return _cmdWrapper!.StatementHandle!;
}
}
private OdbcStatementHandle KeyInfoStatementHandle
{
get { return _cmdWrapper!.KeyInfoStatement!; }
}
internal bool IsBehavior(CommandBehavior behavior)
{
return IsCommandBehavior(behavior);
}
internal bool IsCancelingCommand
{
get
{
if (_command != null)
{
return _command.Canceling;
}
return false;
}
}
internal bool IsNonCancelingCommand
{
get
{
if (_command != null)
{
return !_command.Canceling;
}
return false;
}
}
public override int Depth
{
get
{
if (IsClosed)
{ // MDAC 63669
throw ADP.DataReaderClosed("Depth");
}
return 0;
}
}
public override int FieldCount
{
get
{
if (IsClosed)
{ // MDAC 63669
throw ADP.DataReaderClosed("FieldCount");
}
if (_noMoreResults)
{ // MDAC 93325
return 0;
}
if (null == _dataCache)
{
short cColsAffected;
ODBC32.RetCode retcode = this.FieldCountNoThrow(out cColsAffected);
if (retcode != ODBC32.RetCode.SUCCESS)
{
Connection!.HandleError(StatementHandle, retcode);
}
}
return ((null != _dataCache) ? _dataCache._count : 0);
}
}
// HasRows
//
// Use to detect wheter there are one ore more rows in the result without going through Read
// May be called at any time
// Basically it calls Read and sets a flag so that the actual Read call will be skipped once
//
public override bool HasRows
{
get
{
if (IsClosed)
{
throw ADP.DataReaderClosed("HasRows");
}
if (_hasRows == HasRowsStatus.DontKnow)
{
Read(); //
_skipReadOnce = true; // need to skip Read once because we just did it
}
return (_hasRows == HasRowsStatus.HasRows);
}
}
internal ODBC32.RetCode FieldCountNoThrow(out short cColsAffected)
{
if (IsCancelingCommand)
{
cColsAffected = 0;
return ODBC32.RetCode.ERROR;
}
ODBC32.RetCode retcode = StatementHandle.NumberOfResultColumns(out cColsAffected);
if (retcode == ODBC32.RetCode.SUCCESS)
{
_hiddenColumns = 0;
if (IsCommandBehavior(CommandBehavior.KeyInfo))
{
// we need to search for the first hidden column
//
if (!Connection!.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns)
{
for (int i = 0; i < cColsAffected; i++)
{
SQLLEN isHidden = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_HIDDEN, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE);
if (isHidden.ToInt64() == 1)
{
_hiddenColumns = (int)cColsAffected - i;
cColsAffected = (short)i;
break;
}
}
}
}
_dataCache = new DbCache(this, cColsAffected);
}
else
{
cColsAffected = 0;
}
return retcode;
}
public override bool IsClosed
{
get
{
return _isClosed;
}
}
private SQLLEN GetRowCount()
{
if (!IsClosed)
{
SQLLEN cRowsAffected;
ODBC32.RetCode retcode = StatementHandle.RowCount(out cRowsAffected);
if (ODBC32.RetCode.SUCCESS == retcode || ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)
{
return cRowsAffected;
}
}
return -1;
}
internal int CalculateRecordsAffected(int cRowsAffected)
{
if (0 <= cRowsAffected)
{
if (-1 == _recordAffected)
{
_recordAffected = cRowsAffected;
}
else
{
_recordAffected += cRowsAffected;
}
}
return _recordAffected;
}
public override int RecordsAffected
{
get
{
return _recordAffected;
}
}
public override object this[int i]
{
get
{
return GetValue(i);
}
}
public override object this[string value]
{
get
{
return GetValue(GetOrdinal(value));
}
}
public override void Close()
{
Close(false);
}
private void Close(bool disposing)
{
Exception? error = null;
CMDWrapper? wrapper = _cmdWrapper;
if (null != wrapper && wrapper.StatementHandle != null)
{
// disposing
// true to release both managed and unmanaged resources; false to release only unmanaged resources.
//
if (IsNonCancelingCommand)
{
//Read any remaining results off the wire
// some batch statements may not be executed until SQLMoreResults is called.
// We want the user to be able to do ExecuteNonQuery or ExecuteReader
// and close without having iterate to get params or batch.
//
NextResult(disposing, !disposing); // false,true or true,false
if (null != _command)
{
if (_command.HasParameters)
{
// Output Parameters are not guareenteed to be returned until all the data
// from any restssets are read, so we do this after the above NextResult call(s)
_command.Parameters.GetOutputValues(_cmdWrapper!);
}
wrapper.FreeStatementHandle(ODBC32.STMT.CLOSE);
_command.CloseFromDataReader();
}
}
wrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE);
}
// if the command is still around we call CloseFromDataReader,
// otherwise we need to dismiss the statement handle ourselves
//
if (null != _command)
{
_command.CloseFromDataReader();
if (IsCommandBehavior(CommandBehavior.CloseConnection))
{
Debug.Assert(null != Connection, "null cmd connection");
_command.Parameters.RebindCollection = true;
Connection.Close();
}
}
else if (null != wrapper)
{
wrapper.Dispose();
}
_command = null;
_isClosed = true;
_dataCache = null;
_metadata = null;
_schemaTable = null;
_isRead = false;
_hasRows = HasRowsStatus.DontKnow;
_isValidResult = false;
_noMoreResults = true;
_noMoreRows = true;
_fieldNameLookup = null;
SetCurrentRowColumnInfo(-1, 0);
if ((null != error) && !disposing)
{
throw error;
}
_cmdWrapper = null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Close(true);
}
// not delegating to base class because we know it only calls Close
//base.Dispose(disposing)
}
public override string GetDataTypeName(int i)
{
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
if (info._typename == null)
{
info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!;
}
return info._typename;
}
throw ADP.DataReaderNoData();
}
public override IEnumerator GetEnumerator()
{
return new DbEnumerator((IDataReader)this, IsCommandBehavior(CommandBehavior.CloseConnection));
}
public override Type GetFieldType(int i)
{
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
if (info._type == null)
{
info._type = GetSqlType(i)._type;
}
return info._type;
}
throw ADP.DataReaderNoData();
}
public override string GetName(int i)
{
if (null != _dataCache)
{
DbSchemaInfo info = _dataCache.GetSchema(i);
if (info._name == null)
{
info._name = GetColAttributeStr(i, ODBC32.SQL_DESC.NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.THROW);
if (null == info._name)
{ // MDAC 66681
info._name = "";
}
}
return info._name;
}
throw ADP.DataReaderNoData();
}
public override int GetOrdinal(string value)
{
if (null == _fieldNameLookup)
{
if (null == _dataCache)
{
throw ADP.DataReaderNoData();
}
_fieldNameLookup = new FieldNameLookup(this, -1);
}
return _fieldNameLookup.GetOrdinal(value); // MDAC 71470
}
private int IndexOf(string value)
{
if (null == _fieldNameLookup)
{
if (null == _dataCache)
{
throw ADP.DataReaderNoData();
}
_fieldNameLookup = new FieldNameLookup(this, -1);
}
return _fieldNameLookup.IndexOf(value);
}
private bool IsCommandBehavior(CommandBehavior condition)
{
return (condition == (condition & _commandBehavior));
}
internal object GetValue(int i, TypeMap typemap)
{
switch (typemap._sql_type)
{
case ODBC32.SQL_TYPE.CHAR:
case ODBC32.SQL_TYPE.VARCHAR:
case ODBC32.SQL_TYPE.LONGVARCHAR:
case ODBC32.SQL_TYPE.WCHAR:
case ODBC32.SQL_TYPE.WVARCHAR:
case ODBC32.SQL_TYPE.WLONGVARCHAR:
return internalGetString(i);
case ODBC32.SQL_TYPE.DECIMAL:
case ODBC32.SQL_TYPE.NUMERIC:
return internalGetDecimal(i);
case ODBC32.SQL_TYPE.SMALLINT:
return internalGetInt16(i);
case ODBC32.SQL_TYPE.INTEGER:
return internalGetInt32(i);
case ODBC32.SQL_TYPE.REAL:
return internalGetFloat(i);
case ODBC32.SQL_TYPE.FLOAT:
case ODBC32.SQL_TYPE.DOUBLE:
return internalGetDouble(i);
case ODBC32.SQL_TYPE.BIT:
return internalGetBoolean(i);
case ODBC32.SQL_TYPE.TINYINT:
return internalGetByte(i);
case ODBC32.SQL_TYPE.BIGINT:
return internalGetInt64(i);
case ODBC32.SQL_TYPE.BINARY:
case ODBC32.SQL_TYPE.VARBINARY:
case ODBC32.SQL_TYPE.LONGVARBINARY:
return internalGetBytes(i);
case ODBC32.SQL_TYPE.TYPE_DATE:
return internalGetDate(i);
case ODBC32.SQL_TYPE.TYPE_TIME:
return internalGetTime(i);
// case ODBC32.SQL_TYPE.TIMESTAMP:
case ODBC32.SQL_TYPE.TYPE_TIMESTAMP:
return internalGetDateTime(i);
case ODBC32.SQL_TYPE.GUID:
return internalGetGuid(i);
case ODBC32.SQL_TYPE.SS_VARIANT:
//Note: SQL Variant is not an ODBC defined type.
//Instead of just binding it as a byte[], which is not very useful,
//we will actually code this specific for SQL Server.
//To obtain the sub-type, we need to first load the context (obtaining the length
//will work), and then query for a speicial SQLServer specific attribute.
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
int dummy;
bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out dummy);
// if the value is DBNull, QueryFieldInfo will cache it
if (isNotDbNull)
{
//Delegate (for the sub type)
ODBC32.SQL_TYPE subtype = (ODBC32.SQL_TYPE)(int)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.VARIANT_SQL_TYPE, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.THROW);
return GetValue(i, TypeMap.FromSqlType(subtype));
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
default:
//Unknown types are bound strictly as binary
return internalGetBytes(i);
}
}
public override object GetValue(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
_dataCache[i] = GetValue(i, GetSqlType(i));
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override int GetValues(object[] values)
{
if (_isRead)
{
int nValues = Math.Min(values.Length, FieldCount);
for (int i = 0; i < nValues; ++i)
{
values[i] = GetValue(i);
}
return nValues;
}
throw ADP.DataReaderNoData();
}
private TypeMap GetSqlType(int i)
{
//Note: Types are always returned (advertised) from ODBC as SQL_TYPEs, and
//are always bound by the user as SQL_C types.
TypeMap typeMap;
DbSchemaInfo info = _dataCache!.GetSchema(i);
if (!info._dbtype.HasValue)
{
info._dbtype = unchecked((ODBC32.SQL_TYPE)(int)GetColAttribute(i, ODBC32.SQL_DESC.CONCISE_TYPE, ODBC32.SQL_COLUMN.TYPE, ODBC32.HANDLER.THROW));
typeMap = TypeMap.FromSqlType(info._dbtype.Value);
if (typeMap._signType == true)
{
bool sign = (GetColAttribute(i, ODBC32.SQL_DESC.UNSIGNED, ODBC32.SQL_COLUMN.UNSIGNED, ODBC32.HANDLER.THROW).ToInt64() != 0);
typeMap = TypeMap.UpgradeSignedType(typeMap, sign);
info._dbtype = typeMap._sql_type;
}
}
else
{
typeMap = TypeMap.FromSqlType(info._dbtype.Value);
}
Connection!.SetSupportedType(info._dbtype.Value);
return typeMap;
}
public override bool IsDBNull(int i)
{
// Note: ODBC SQLGetData doesn't allow retrieving the column value twice.
// The rationale is that for ForwardOnly access (the default and LCD of drivers)
// we cannot obtain the data more than once, and even GetData(0) (to determine is-null)
// still obtains data for fixed length types.
// So simple code like:
// if (!rReader.IsDBNull(i))
// rReader.GetInt32(i)
//
// Would fail, unless we cache on the IsDBNull call, and return the cached
// item for GetInt32. This actually improves perf anyway, (even if the driver could
// support it), since we are not making a separate interop call...
// Bug SQLBUVSTS01:110664 - available cases:
// 1. random access - always cache the value (as before the fix), to minimize regression risk
// 2. sequential access, fixed-size value: continue caching the value as before, again to minimize regression risk
// 3. sequential access, variable-length value: this scenario did not work properly before the fix. Fix
// it now by calling GetData(length = 0).
// 4. sequential access, cache value exists: just check the cache for DbNull (no validations done, again to minimize regressions)
if (!IsCommandBehavior(CommandBehavior.SequentialAccess))
return Convert.IsDBNull(GetValue(i)); // case 1, cache the value
// in 'ideal' Sequential access support, we do not want cache the value in order to check if it is DbNull or not.
// But, to minimize regressions, we will continue caching the fixed-size values (case 2), even with SequentialAccess
// only in case of SequentialAccess with variable length data types (case 3), we will use GetData with zero length.
object? cachedObj = _dataCache![i];
if (cachedObj != null)
{
// case 4 - if cached object was created before, use it
return Convert.IsDBNull(cachedObj);
}
// no cache, check for the type (cases 2 and 3)
TypeMap typeMap = GetSqlType(i);
if (typeMap._bufferSize > 0)
{
// case 2 - fixed-size types have _bufferSize set to positive value
// call GetValue(i) as before the fix of SQLBUVSTS01:110664
// note, when SQLGetData is called for a fixed length type, the buffer size is always ignored and
// the data will always be read off the wire
return Convert.IsDBNull(GetValue(i));
}
else
{
// case 3 - the data has variable-length type, read zero-length data to query for null
// QueryFieldInfo will return false only if the object cached as DbNull
// QueryFieldInfo will put DbNull in cache only if the SQLGetData returns SQL_NULL_DATA, otherwise it does not change it
int dummy;
return !QueryFieldInfo(i, typeMap._sql_c, out dummy);
}
}
public override byte GetByte(int i)
{
return (byte)internalGetByte(i);
}
private object internalGetByte(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.UTINYINT))
{
_dataCache[i] = Buffer.ReadByte(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override char GetChar(int i)
{
return (char)internalGetChar(i);
}
private object internalGetChar(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.WCHAR))
{
_dataCache[i] = Buffer.ReadChar(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override short GetInt16(int i)
{
return (short)internalGetInt16(i);
}
private object internalGetInt16(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.SSHORT))
{
_dataCache[i] = Buffer.ReadInt16(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override int GetInt32(int i)
{
return (int)internalGetInt32(i);
}
private object internalGetInt32(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.SLONG))
{
_dataCache[i] = Buffer.ReadInt32(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override long GetInt64(int i)
{
return (long)internalGetInt64(i);
}
// ---------------------------------------------------------------------------------------------- //
// internal internalGetInt64
// -------------------------
// Get Value of type SQL_BIGINT
// Since the driver refused to accept the type SQL_BIGINT we read that
// as SQL_C_WCHAR and convert it back to the Int64 data type
//
private object internalGetInt64(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.WCHAR))
{
string value = (string)Buffer.MarshalToManaged(0, ODBC32.SQL_C.WCHAR, ODBC32.SQL_NTS);
_dataCache[i] = long.Parse(value, CultureInfo.InvariantCulture);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override bool GetBoolean(int i)
{
return (bool)internalGetBoolean(i);
}
private object internalGetBoolean(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.BIT))
{
_dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.BIT, -1);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override float GetFloat(int i)
{
return (float)internalGetFloat(i);
}
private object internalGetFloat(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.REAL))
{
_dataCache[i] = Buffer.ReadSingle(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public DateTime GetDate(int i)
{
return (DateTime)internalGetDate(i);
}
private object internalGetDate(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.TYPE_DATE))
{
_dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_DATE, -1);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override DateTime GetDateTime(int i)
{
return (DateTime)internalGetDateTime(i);
}
private object internalGetDateTime(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.TYPE_TIMESTAMP))
{
_dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIMESTAMP, -1);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override decimal GetDecimal(int i)
{
return (decimal)internalGetDecimal(i);
}
// ---------------------------------------------------------------------------------------------- //
// internal GetDecimal
// -------------------
// Get Value of type SQL_DECIMAL or SQL_NUMERIC
// Due to provider incompatibilities with SQL_DECIMAL or SQL_NUMERIC types we always read the value
// as SQL_C_WCHAR and convert it back to the Decimal data type
//
private object internalGetDecimal(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.WCHAR))
{
string? s = null;
try
{
s = (string)Buffer.MarshalToManaged(0, ODBC32.SQL_C.WCHAR, ODBC32.SQL_NTS);
_dataCache[i] = decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture);
}
catch (OverflowException)
{
_dataCache[i] = s;
throw;
}
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override double GetDouble(int i)
{
return (double)internalGetDouble(i);
}
private object internalGetDouble(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.DOUBLE))
{
_dataCache[i] = Buffer.ReadDouble(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override Guid GetGuid(int i)
{
return (Guid)internalGetGuid(i);
}
private object internalGetGuid(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.GUID))
{
_dataCache[i] = Buffer.ReadGuid(0);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public override string GetString(int i)
{
return (string)internalGetString(i);
}
private object internalGetString(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
// Obtain _ALL_ the characters
// Note: We can bind directly as WCHAR in ODBC and the DM will convert to and
// from ANSI if not supported by the driver.
//
// Note: The driver always returns the raw length of the data, minus the
// terminator. This means that our buffer length always includes the terminator
// charactor, so when determining which characters to count, and if more data
// exists, it should not take the terminator into effect.
//
CNativeBuffer buffer = Buffer;
// that does not make sense unless we expect four byte terminators
int cbMaxData = buffer.Length - 4;
// The first time GetData returns the true length (so we have to min it).
// We also pass in the true length to the marshal function since there could be
// embedded nulls
//
int lengthOrIndicator;
if (GetData(i, ODBC32.SQL_C.WCHAR, buffer.Length - 2, out lengthOrIndicator))
{
// RFC 50002644: we do not expect negative values from GetData call except SQL_NO_TOTAL(== -4)
// note that in general you should not trust third-party providers so such asserts should be
// followed by exception. I did not add it now to avoid breaking change
Debug.Assert(lengthOrIndicator >= 0 || lengthOrIndicator == ODBC32.SQL_NO_TOTAL, "unexpected lengthOrIndicator value");
if (lengthOrIndicator <= cbMaxData && (ODBC32.SQL_NO_TOTAL != lengthOrIndicator))
{
// all data read? good! Directly marshal to a string and we're done
//
string strdata = buffer.PtrToStringUni(0, Math.Min(lengthOrIndicator, cbMaxData) / 2);
_dataCache[i] = strdata;
return strdata;
}
// We need to chunk the data
// Char[] buffer for the junks
// StringBuilder for the actual string
//
char[] rgChars = new char[cbMaxData / 2];
// RFC 50002644: negative value cannot be used for capacity.
// in case of SQL_NO_TOTAL, set the capacity to cbMaxData, StringBuilder will automatically reallocate
// its internal buffer when appending more data
int cbBuilderInitialCapacity = (lengthOrIndicator == ODBC32.SQL_NO_TOTAL) ? cbMaxData : lengthOrIndicator;
StringBuilder builder = new StringBuilder(cbBuilderInitialCapacity / 2);
bool gotData;
int cchJunk;
int cbActual = cbMaxData;
int cbMissing = (ODBC32.SQL_NO_TOTAL == lengthOrIndicator) ? -1 : lengthOrIndicator - cbActual;
do
{
cchJunk = cbActual / 2;
buffer.ReadChars(0, rgChars, 0, cchJunk);
builder.Append(rgChars, 0, cchJunk);
if (0 == cbMissing)
{
break; // done
}
gotData = GetData(i, ODBC32.SQL_C.WCHAR, buffer.Length - 2, out lengthOrIndicator);
// RFC 50002644: we do not expect negative values from GetData call except SQL_NO_TOTAL(== -4)
// note that in general you should not trust third-party providers so such asserts should be
// followed by exception. I did not add it now to avoid breaking change
Debug.Assert(lengthOrIndicator >= 0 || lengthOrIndicator == ODBC32.SQL_NO_TOTAL, "unexpected lengthOrIndicator value");
if (ODBC32.SQL_NO_TOTAL != lengthOrIndicator)
{
cbActual = Math.Min(lengthOrIndicator, cbMaxData);
if (0 < cbMissing)
{
cbMissing -= cbActual;
}
else
{
// it is a last call to SqlGetData that started with SQL_NO_TOTAL
// the last call to SqlGetData must always return the length of the
// data, not zero or SqlNoTotal (see Odbc Programmers Reference)
Debug.Assert(cbMissing == -1 && lengthOrIndicator <= cbMaxData);
cbMissing = 0;
}
}
}
while (gotData);
_dataCache[i] = builder.ToString();
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
public TimeSpan GetTime(int i)
{
return (TimeSpan)internalGetTime(i);
}
private object internalGetTime(int i)
{
if (_isRead)
{
if (_dataCache!.AccessIndex(i) == null)
{
if (GetData(i, ODBC32.SQL_C.TYPE_TIME))
{
_dataCache[i] = Buffer.MarshalToManaged(0, ODBC32.SQL_C.TYPE_TIME, -1);
}
}
return _dataCache[i]!;
}
throw ADP.DataReaderNoData();
}
private void SetCurrentRowColumnInfo(int row, int column)
{
if (_row != row || _column != column)
{
_row = row;
_column = column;
// reset the blob reader when moved to new column
_sequentialBytesRead = 0;
}
}
public override long GetBytes(int i, long dataIndex, byte[]? buffer, int bufferIndex, int length)
{
return GetBytesOrChars(i, dataIndex, buffer, false /* bytes buffer */, bufferIndex, length);
}
public override long GetChars(int i, long dataIndex, char[]? buffer, int bufferIndex, int length)
{
return GetBytesOrChars(i, dataIndex, buffer, true /* chars buffer */, bufferIndex, length);
}
// unify the implementation of GetChars and GetBytes to prevent code duplicate
private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsBuffer, int bufferIndex, int length)
{
if (IsClosed)
{
throw ADP.DataReaderNoData();
}
if (!_isRead)
{
throw ADP.DataReaderNoData();
}
if (dataIndex < 0)
{
// test only for negative value here, Int32.MaxValue will be validated only in case of random access
throw ADP.ArgumentOutOfRange(nameof(dataIndex));
}
if (bufferIndex < 0)
{
throw ADP.ArgumentOutOfRange(nameof(bufferIndex));
}
if (length < 0)
{
throw ADP.ArgumentOutOfRange(nameof(length));
}
string originalMethodName = isCharsBuffer ? "GetChars" : "GetBytes";
// row/column info will be reset only if changed
SetCurrentRowColumnInfo(_row, i);
// Possible cases:
// 1. random access, user asks for the value first time: bring it and cache the value
// 2. random access, user already queried the value: use the cache
// 3. sequential access, cache exists: user already read this value using different method (it becomes cached)
// use the cache - preserve the original behavior to minimize regression risk
// 4. sequential access, no cache: (fixed now) user reads the bytes/chars in sequential order (no cache)
object? cachedObj = null; // The cached object (if there is one)
// Get cached object, ensure the correct type using explicit cast, to preserve same behavior as before
if (isCharsBuffer)
cachedObj = (string?)_dataCache![i];
else
cachedObj = (byte[]?)_dataCache![i];
bool isRandomAccess = !IsCommandBehavior(CommandBehavior.SequentialAccess);
if (isRandomAccess || (cachedObj != null))
{
// random access (cases 1 or 2) and sequential access with cache (case 3)
// preserve the original behavior as before the fix
if (int.MaxValue < dataIndex)
{
// indices greater than allocable size are not supported in random access
// (negative value is already tested in the beginning of ths function)
throw ADP.ArgumentOutOfRange(nameof(dataIndex));
}
if (cachedObj == null)
{
// case 1, get the value and cache it
// internalGetString/internalGetBytes will get the entire value and cache it,
// since we are not in SequentialAccess (isRandomAccess is true), it is OK
if (isCharsBuffer)
{
cachedObj = (string)internalGetString(i);
Debug.Assert((cachedObj != null), "internalGetString should always return non-null or raise exception");
}
else
{
cachedObj = (byte[])internalGetBytes(i);
Debug.Assert((cachedObj != null), "internalGetBytes should always return non-null or raise exception");
}
// continue to case 2
}
// after this point the value is cached (case 2 or 3)
// if it is DbNull, cast exception will be raised (same as before the 110664 fix)
int cachedObjectLength = isCharsBuffer ? ((string)cachedObj).Length : ((byte[])cachedObj).Length;
// the user can ask for the length of the field by passing in a null pointer for the buffer
if (buffer == null)
{
// return the length if that's all what user needs
return cachedObjectLength;
}
// user asks for bytes
if (length == 0)
{
return 0; // Nothing to do ...
}
if (dataIndex >= cachedObjectLength)
{
// no more bytes to read
// see also MDAC bug 73298
return 0;
}
int lengthFromDataIndex = cachedObjectLength - (int)dataIndex;
int lengthOfCopy = Math.Min(lengthFromDataIndex, length);
// silently reduce the length to avoid regression from EVERETT
lengthOfCopy = Math.Min(lengthOfCopy, buffer.Length - bufferIndex);
if (lengthOfCopy <= 0) return 0; // MDAC Bug 73298
if (isCharsBuffer)
((string)cachedObj).CopyTo((int)dataIndex, (char[])buffer, bufferIndex, lengthOfCopy);
else
Array.Copy((byte[])cachedObj, (int)dataIndex, (byte[])buffer, bufferIndex, lengthOfCopy);
return lengthOfCopy;
}
else
{
// sequential access, case 4
// SQLBU:532243 -- For SequentialAccess we need to read a chunk of
// data and not cache it.
// Note: If the object was previous cached (see case 3 above), the function will go thru 'if' path, to minimize
// regressions
// the user can ask for the length of the field by passing in a null pointer for the buffer
if (buffer == null)
{
// Get len. of remaining data from provider
ODBC32.SQL_C sqlctype;
int cbLengthOrIndicator;
bool isDbNull;
sqlctype = isCharsBuffer ? ODBC32.SQL_C.WCHAR : ODBC32.SQL_C.BINARY;
isDbNull = !QueryFieldInfo(i, sqlctype, out cbLengthOrIndicator);
if (isDbNull)
{
// SQLBU 266054:
// GetChars:
// in Orcas RTM: GetChars has always raised InvalidCastException.
// in Orcas SP1: GetChars returned 0 if DbNull is not cached yet and InvalidCastException if it is in cache (from case 3).
// Managed Providers team has decided to fix the GetChars behavior and raise InvalidCastException, as it was in RTM
// Reason: returing 0 is wrong behavior since it conflicts with return value in case of empty data
// GetBytes:
// In Orcas RTM: GetBytes(null buffer) returned -1 for null value if DbNull is not cached yet.
// But, after calling IsDBNull, GetBytes(null) raised InvalidCastException.
// In Orcas SP1: GetBytes always raises InvalidCastException for null value.
// Managed Providers team has decided to keep the behavior of RTM for this case to fix the RTM's breaking change.
// Reason: while -1 is wrong behavior, people might be already relying on it, so we should not be changing it.
// Note: this will happen only on the first call to GetBytes(with null buffer).
// If IsDbNull has already been called before or for second call to query for size,
// DBNull is cached and GetBytes raises InvalidCastException in case 3 (see the cases above in this method).
if (isCharsBuffer)
{
throw ADP.InvalidCast();
}
else
{
return -1;
}
}
else
{
// the value is not null
// SQLBU 266054:
// If cbLengthOrIndicator is SQL_NO_TOTAL (-4), this call returns -4 or -2, depending on the type (GetChars=>-2, GetBytes=>-4).
// This is the Orcas RTM and SP1 behavior, changing this would be a breaking change.
// SQL_NO_TOTAL means that the driver does not know what is the remained lenght of the data, so we cannot really guess the value here.
// Reason: while returning different negative values depending on the type seems inconsistent,
// this is what we did in Orcas RTM and SP1 and user code might rely on this behavior => changing it would be a breaking change.
if (isCharsBuffer)
{
return cbLengthOrIndicator / 2; // return length in wide characters or -2 if driver returns SQL_NO_TOTAL
}
else
{
return cbLengthOrIndicator; // return length in bytes or -4 if driver returns SQL_NO_TOTAL
}
}
}
else
{
// buffer != null, read the data
// check if user tries to read data that was already received
// if yes, this violates 'sequential access'
if ((isCharsBuffer && dataIndex < _sequentialBytesRead / 2) ||
(!isCharsBuffer && dataIndex < _sequentialBytesRead))
{
// backward reading is not allowed in sequential access
throw ADP.NonSeqByteAccess(
dataIndex,
_sequentialBytesRead,
originalMethodName
);
}
// note that it is actually not possible to read with an offset (dataIndex)
// therefore, adjust the data index relative to number of bytes already read
if (isCharsBuffer)
dataIndex -= _sequentialBytesRead / 2;
else
dataIndex -= _sequentialBytesRead;
if (dataIndex > 0)
{
// user asked to skip bytes - it is OK, even in case of sequential access
// forward the stream by dataIndex bytes/chars
int charsOrBytesRead = readBytesOrCharsSequentialAccess(i, null, isCharsBuffer, 0, dataIndex);
if (charsOrBytesRead < dataIndex)
{
// the stream ended before we forwarded to the requested index, stop now
return 0;
}
}
// ODBC driver now points to the correct position, start filling the user buffer from now
// Make sure we don't overflow the user provided buffer
// Note: SqlDataReader will raise exception if there is no enough room for length requested.
// In case of ODBC, I decided to keep this consistent with random access after consulting with PM.
length = Math.Min(length, buffer.Length - bufferIndex);
if (length <= 0)
{
// SQLBU 266054:
// if the data is null, the ideal behavior here is to raise InvalidCastException. But,
// * GetBytes returned 0 in Orcas RTM and SP1, continue to do so to avoid breaking change from Orcas RTM and SP1.
// * GetChars raised exception in RTM, and returned 0 in SP1: we decided to revert back to the RTM's behavior and raise InvalidCast
if (isCharsBuffer)
{
// for GetChars, ensure data is not null
// 2 bytes for '\0' termination, no data is actually read from the driver
int cbLengthOrIndicator;
bool isDbNull = !QueryFieldInfo(i, ODBC32.SQL_C.WCHAR, out cbLengthOrIndicator);
if (isDbNull)
{
throw ADP.InvalidCast();
}
}
// else - GetBytes - return now
return 0;
}
// fill the user's buffer
return readBytesOrCharsSequentialAccess(i, buffer, isCharsBuffer, bufferIndex, length);
}
}
}
// fill the user's buffer (char[] or byte[], depending on isCharsBuffer)
// if buffer is null, just skip the bytesOrCharsLength bytes or chars
private int readBytesOrCharsSequentialAccess(int i, Array? buffer, bool isCharsBuffer, int bufferIndex, long bytesOrCharsLength)
{
Debug.Assert(bufferIndex >= 0, "Negative buffer index");
Debug.Assert(bytesOrCharsLength >= 0, "Negative number of bytes or chars to read");
// validated by the caller
Debug.Assert(buffer == null || bytesOrCharsLength <= (buffer.Length - bufferIndex), "Not enough space in user's buffer");
int totalBytesOrCharsRead = 0;
// we need length in bytes, b/c that is what SQLGetData expects
long cbLength = (isCharsBuffer) ? checked(bytesOrCharsLength * 2) : bytesOrCharsLength;
// continue reading from the driver until we fill the user's buffer or until no more data is available
// the data is pumped first into the internal native buffer and after that copied into the user's one if buffer is not null
CNativeBuffer internalNativeBuffer = this.Buffer;
// read the data in loop up to th user's length
// if the data size is less than requested or in case of error, the while loop will stop in the middle
while (cbLength > 0)
{
// max data to be read, in bytes, not including null-terminator for WCHARs
int cbReadMax;
// read from the driver
bool isNotDbNull;
int cbTotal;
// read either bytes or chars, depending on the method called
if (isCharsBuffer)
{
// for WCHAR buffers, we need to leave space for null-terminator (2 bytes)
// reserve 2 bytes for null-terminator and 2 bytes to prevent assert in GetData
// if SQL_NO_TOTAL is returned, this ammount is read from the wire, in bytes
cbReadMax = (int)Math.Min(cbLength, internalNativeBuffer.Length - 4);
// SQLGetData will always append it - we do not to copy it to user's buffer
isNotDbNull = GetData(i, ODBC32.SQL_C.WCHAR, cbReadMax + 2, out cbTotal);
}
else
{
// reserve 2 bytes to prevent assert in GetData
// when querying bytes, no need to reserve space for null
cbReadMax = (int)Math.Min(cbLength, internalNativeBuffer.Length - 2);
isNotDbNull = GetData(i, ODBC32.SQL_C.BINARY, cbReadMax, out cbTotal);
}
if (!isNotDbNull)
{
// DbNull received, neither GetBytes nor GetChars should be used with DbNull value
// two options
// 1. be consistent with SqlDataReader, raise SqlNullValueException
// 2. be consistent with other Get* methods of OdbcDataReader and raise InvalidCastException
// after consulting with Himanshu (PM), decided to go with option 2 (raise cast exception)
throw ADP.InvalidCast();
}
int cbRead; // will hold number of bytes read in this loop
bool noDataRemained = false;
if (cbTotal == 0)
{
// no bytes read, stop
break;
}
else if (ODBC32.SQL_NO_TOTAL == cbTotal)
{
// the driver has filled the internal buffer, but the length of remained data is still unknown
// we will continue looping until SQLGetData indicates the end of data or user buffer is fully filled
cbRead = cbReadMax;
}
else
{
Debug.Assert((cbTotal > 0), "GetData returned negative value, which is not SQL_NO_TOTAL");
// GetData uses SQLGetData, which StrLen_or_IndPtr (cbTotal in our case) to the current buf + remained buf (if any)
if (cbTotal > cbReadMax)
{
// in this case the amount of bytes/chars read will be the max requested (and more bytes can be read)
cbRead = cbReadMax;
}
else
{
// SQLGetData read all the available data, no more remained
// continue processing this chunk and stop
cbRead = cbTotal;
noDataRemained = true;
}
}
_sequentialBytesRead += cbRead;
// update internal state and copy the data to user's buffer
if (isCharsBuffer)
{
int cchRead = cbRead / 2;
if (buffer != null)
{
internalNativeBuffer.ReadChars(0, (char[])buffer, bufferIndex, cchRead);
bufferIndex += cchRead;
}
totalBytesOrCharsRead += cchRead;
}
else
{
if (buffer != null)
{
internalNativeBuffer.ReadBytes(0, (byte[])buffer, bufferIndex, cbRead);
bufferIndex += cbRead;
}
totalBytesOrCharsRead += cbRead;
}
cbLength -= cbRead;
// stop if no data remained
if (noDataRemained)
break;
}
return totalBytesOrCharsRead;
}
private object internalGetBytes(int i)
{
if (_dataCache!.AccessIndex(i) == null)
{
// Obtain _ALL_ the bytes...
// The first time GetData returns the true length (so we have to min it).
byte[] rgBytes;
int cbBufferLen = Buffer.Length - 4;
int cbActual;
int cbOffset = 0;
if (GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual))
{
CNativeBuffer buffer = Buffer;
if (ODBC32.SQL_NO_TOTAL != cbActual)
{
rgBytes = new byte[cbActual];
Buffer.ReadBytes(0, rgBytes, cbOffset, Math.Min(cbActual, cbBufferLen));
// Chunking. The data may be larger than our native buffer. In which case
// instead of growing the buffer (out of control), we will read in chunks to
// reduce memory footprint size.
while (cbActual > cbBufferLen)
{
// The first time GetData returns the true length. Then successive calls
// return the remaining data.
bool flag = GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual);
Debug.Assert(flag, "internalGetBytes - unexpected invalid result inside if-block");
cbOffset += cbBufferLen;
buffer.ReadBytes(0, rgBytes, cbOffset, Math.Min(cbActual, cbBufferLen));
}
}
else
{
List<byte[]> junkArray = new List<byte[]>();
int junkSize;
int totalSize = 0;
do
{
junkSize = (ODBC32.SQL_NO_TOTAL != cbActual) ? cbActual : cbBufferLen;
rgBytes = new byte[junkSize];
totalSize += junkSize;
buffer.ReadBytes(0, rgBytes, 0, junkSize);
junkArray.Add(rgBytes);
}
while ((ODBC32.SQL_NO_TOTAL == cbActual) && GetData(i, ODBC32.SQL_C.BINARY, cbBufferLen, out cbActual));
rgBytes = new byte[totalSize];
foreach (byte[] junk in junkArray)
{
junk.CopyTo(rgBytes, cbOffset);
cbOffset += junk.Length;
}
}
// always update the cache
_dataCache[i] = rgBytes;
}
}
return _dataCache[i]!;
}
// GetColAttribute
// ---------------
// [IN] iColumn ColumnNumber
// [IN] v3FieldId FieldIdentifier of the attribute for version3 drivers (>=3.0)
// [IN] v2FieldId FieldIdentifier of the attribute for version2 drivers (<3.0)
//
// returns the value of the FieldIdentifier field of the column
// or -1 if the FieldIdentifier wasn't supported by the driver
//
private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler)
{
short cchNameLength = 0;
SQLLEN numericAttribute;
ODBC32.RetCode retcode;
// protect against dead connection, dead or canceling command.
if ((Connection == null) || _cmdWrapper!.Canceling)
{
return -1;
}
//Ordinals are 1:base in odbc
OdbcStatementHandle stmt = StatementHandle;
if (Connection.IsV3Driver)
{
retcode = stmt.ColumnAttribute(iColumn + 1, (short)v3FieldId, Buffer, out cchNameLength, out numericAttribute);
}
else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1))
{
retcode = stmt.ColumnAttribute(iColumn + 1, (short)v2FieldId, Buffer, out cchNameLength, out numericAttribute);
}
else
{
return 0;
}
if (retcode != ODBC32.RetCode.SUCCESS)
{
if (retcode == ODBC32.RetCode.ERROR)
{
if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId);
}
}
if (handler == ODBC32.HANDLER.THROW)
{
Connection.HandleError(stmt, retcode);
}
return -1;
}
return numericAttribute;
}
// GetColAttributeStr
// ---------------
// [IN] iColumn ColumnNumber
// [IN] v3FieldId FieldIdentifier of the attribute for version3 drivers (>=3.0)
// [IN] v2FieldId FieldIdentifier of the attribute for version2 drivers (<3.0)
//
// returns the stringvalue of the FieldIdentifier field of the column
// or null if the string returned was empty or if the FieldIdentifier wasn't supported by the driver
//
private string? GetColAttributeStr(int i, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler)
{
ODBC32.RetCode retcode;
short cchNameLength = 0;
SQLLEN numericAttribute;
CNativeBuffer buffer = Buffer;
buffer.WriteInt16(0, 0);
OdbcStatementHandle? stmt = StatementHandle;
// protect against dead connection
if (Connection == null || _cmdWrapper!.Canceling || stmt == null)
{
return "";
}
if (Connection.IsV3Driver)
{
retcode = stmt.ColumnAttribute(i + 1, (short)v3FieldId, buffer, out cchNameLength, out numericAttribute);
}
else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1))
{
retcode = stmt.ColumnAttribute(i + 1, (short)v2FieldId, buffer, out cchNameLength, out numericAttribute);
}
else
{
return null;
}
if ((retcode != ODBC32.RetCode.SUCCESS) || (cchNameLength == 0))
{
if (retcode == ODBC32.RetCode.ERROR)
{
if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(v3FieldId, v2FieldId);
}
}
if (handler == ODBC32.HANDLER.THROW)
{
Connection.HandleError(stmt, retcode);
}
return null;
}
string retval = buffer.PtrToStringUni(0, cchNameLength / 2 /*cch*/);
return retval;
}
// todo: Another 3.0 only attribute that is guaranteed to fail on V2 driver.
// need to special case this for V2 drivers.
//
private string? GetDescFieldStr(int i, ODBC32.SQL_DESC attribute, ODBC32.HANDLER handler)
{
int numericAttribute = 0;
// protect against dead connection, dead or canceling command.
if ((Connection == null) || _cmdWrapper!.Canceling)
{
return "";
}
// APP_PARAM_DESC is a (ODBCVER >= 0x0300) attribute
if (!Connection.IsV3Driver)
{
Debug.Fail("Non-V3 driver. Must not call GetDescFieldStr");
return null;
}
ODBC32.RetCode retcode;
CNativeBuffer buffer = Buffer;
// Need to set the APP_PARAM_DESC values here
using (OdbcDescriptorHandle hdesc = new OdbcDescriptorHandle(StatementHandle, ODBC32.SQL_ATTR.APP_PARAM_DESC))
{
//SQLGetDescField
retcode = hdesc.GetDescriptionField(i + 1, attribute, buffer, out numericAttribute);
//Since there are many attributes (column, statement, etc), that may or may not be
//supported, we don't want to throw (which obtains all errorinfo, marshals strings,
//builds exceptions, etc), in common cases, unless we absolutely need this info...
if ((retcode != ODBC32.RetCode.SUCCESS) || (numericAttribute == 0))
{
if (retcode == ODBC32.RetCode.ERROR)
{
if ("HY091" == Command!.GetDiagSqlState())
{
Connection.FlagUnsupportedColAttr(attribute, (ODBC32.SQL_COLUMN)0);
}
}
if (handler == ODBC32.HANDLER.THROW)
{
Connection.HandleError(StatementHandle, retcode);
}
return null;
}
}
string retval = buffer.PtrToStringUni(0, numericAttribute / 2 /*cch*/);
return retval;
}
/// <summary>
/// This methods queries the following field information: isDbNull and remained size/indicator. No data is read from the driver.
/// If the value is DbNull, this value will be cached. Refer to GetData for more details.
/// </summary>
/// <returns>false if value is DbNull, true otherwise</returns>
private bool QueryFieldInfo(int i, ODBC32.SQL_C sqlctype, out int cbLengthOrIndicator)
{
int cb = 0;
if (sqlctype == ODBC32.SQL_C.WCHAR)
{
// SQLBU 266054 - in case of WCHAR data, we need to provide buffer with a space for null terminator (two bytes)
cb = 2;
}
return GetData(i, sqlctype, cb /* no data should be lost */, out cbLengthOrIndicator);
}
private bool GetData(int i, ODBC32.SQL_C sqlctype)
{
// Never call GetData with anything larger than _buffer.Length-2.
// We keep reallocating native buffers and it kills performance!!!
int dummy;
return GetData(i, sqlctype, Buffer.Length - 4, out dummy);
}
/// <summary>
/// Note: use only this method to call SQLGetData! It caches the null value so the fact that the value is null is kept and no other calls
/// are made after it.
///
/// retrieves the data into this.Buffer.
/// * If the data is DbNull, the value be also cached and false is returned.
/// * if the data is not DbNull, the value is not cached and true is returned
///
/// Note: cbLengthOrIndicator can be either the length of (remained) data or SQL_NO_TOTAL (-4) when the length is not known.
/// in case of SQL_NO_TOTAL, driver fills the buffer till the end.
/// The indicator will NOT be SQL_NULL_DATA, GetData will replace it with zero and return false.
/// </summary>
/// <returns>false if value is DbNull, true otherwise</returns>
private bool GetData(int i, ODBC32.SQL_C sqlctype, int cb, out int cbLengthOrIndicator)
{
IntPtr cbActual = IntPtr.Zero; // Length or an indicator value
if (IsCancelingCommand)
{
throw ADP.DataReaderNoData();
}
Debug.Assert(null != StatementHandle, "Statement handle is null in DateReader");
// see notes on ODBC32.RetCode.NO_DATA case below.
Debug.Assert(_dataCache == null || !Convert.IsDBNull(_dataCache[i]), "Cannot call GetData without checking for cache first!");
// Never call GetData with anything larger than _buffer.Length-2.
// We keep reallocating native buffers and it kills performance!!!
Debug.Assert(cb <= Buffer.Length - 2, "GetData needs to Reallocate. Perf bug");
// SQLGetData
CNativeBuffer buffer = Buffer;
ODBC32.RetCode retcode = StatementHandle.GetData(
(i + 1), // Column ordinals start at 1 in odbc
sqlctype,
buffer,
cb,
out cbActual);
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
break;
case ODBC32.RetCode.SUCCESS_WITH_INFO:
if ((int)cbActual == ODBC32.SQL_NO_TOTAL)
{
break;
}
// devnote: don't we want to fire an event?
break;
case ODBC32.RetCode.NO_DATA:
// SQLBU 266054: System.Data.Odbc: Fails with truncated error when we pass BufferLength as 0
// NO_DATA return value is success value - it means that the driver has fully consumed the current column value
// but did not move to the next column yet.
// For fixed-size values, we do not expect this to happen because we fully consume the data and store it in cache after the first call.
// For variable-length values (any character or binary data), SQLGetData can be called several times on the same column,
// to query for the next chunk of value, even after reaching its end!
// Thus, ignore NO_DATA for variable length data, but raise exception for fixed-size types
if (sqlctype != ODBC32.SQL_C.WCHAR && sqlctype != ODBC32.SQL_C.BINARY)
{
Connection!.HandleError(StatementHandle, retcode);
}
if (cbActual == (IntPtr)ODBC32.SQL_NO_TOTAL)
{
// ensure SQL_NO_TOTAL value gets replaced with zero if the driver has fully consumed the current column
cbActual = (IntPtr)0;
}
break;
default:
Connection!.HandleError(StatementHandle, retcode);
break;
}
// reset the current row and column
SetCurrentRowColumnInfo(_row, i);
// test for SQL_NULL_DATA
if (cbActual == (IntPtr)ODBC32.SQL_NULL_DATA)
{
// Store the DBNull value in cache. Note that if we need to do it, because second call into the SQLGetData returns NO_DATA, which means
// we already consumed the value (see above) and the NULL information is lost. By storing the null in cache, we avoid second call into the driver
// for the same row/column.
_dataCache![i] = DBNull.Value;
// the indicator is never -1 (and it should not actually be used if the data is DBNull)
cbLengthOrIndicator = 0;
return false;
}
else
{
//Return the actual size (for chunking scenarios)
// note the return value can be SQL_NO_TOTAL (-4)
cbLengthOrIndicator = (int)cbActual;
return true;
}
}
public override bool Read()
{
if (IsClosed)
{
throw ADP.DataReaderClosed("Read");
}
if (IsCancelingCommand)
{
_isRead = false;
return false;
}
// HasRows needs to call into Read so we don't want to read on the actual Read call
if (_skipReadOnce)
{
_skipReadOnce = false;
return _isRead;
}
if (_noMoreRows || _noMoreResults || IsCommandBehavior(CommandBehavior.SchemaOnly))
return false;
if (!_isValidResult)
{
return false;
}
ODBC32.RetCode retcode;
//SQLFetch is only valid to call for row returning queries
//We get: [24000]Invalid cursor state. So we could either check the count
//ahead of time (which is cached), or check on error and compare error states.
//Note: SQLFetch is also invalid to be called on a prepared (schemaonly) statement
//SqlFetch
retcode = StatementHandle.Fetch();
switch (retcode)
{
case ODBC32.RetCode.SUCCESS_WITH_INFO:
Connection!.HandleErrorNoThrow(StatementHandle, retcode);
_hasRows = HasRowsStatus.HasRows;
_isRead = true;
break;
case ODBC32.RetCode.SUCCESS:
_hasRows = HasRowsStatus.HasRows;
_isRead = true;
break;
case ODBC32.RetCode.NO_DATA:
_isRead = false;
if (_hasRows == HasRowsStatus.DontKnow)
{
_hasRows = HasRowsStatus.HasNoRows;
}
break;
default:
Connection!.HandleError(StatementHandle, retcode);
break;
}
//Null out previous cached row values.
_dataCache!.FlushValues();
// if CommandBehavior == SingleRow we set _noMoreResults to true so that following reads will fail
if (IsCommandBehavior(CommandBehavior.SingleRow))
{
_noMoreRows = true;
// no more rows, set to -1
SetCurrentRowColumnInfo(-1, 0);
}
else
{
// move to the next row
SetCurrentRowColumnInfo(_row + 1, 0);
}
return _isRead;
}
// Called by odbccommand when executed for the first time
internal void FirstResult()
{
short cCols;
SQLLEN cRowsAffected;
cRowsAffected = GetRowCount(); // get rowcount of the current resultset (if any)
CalculateRecordsAffected(cRowsAffected); // update recordsaffected
ODBC32.RetCode retcode = FieldCountNoThrow(out cCols);
if ((retcode == ODBC32.RetCode.SUCCESS) && (cCols == 0))
{
NextResult();
}
else
{
_isValidResult = true;
}
}
public override bool NextResult()
{
return NextResult(false, false);
}
private bool NextResult(bool disposing, bool allresults)
{
// if disposing, loop through all the remaining results and ignore error messages
// if allresults, loop through all results and collect all error messages for a single exception
// callers are via Close(false, true), Dispose(true, false), NextResult(false,false)
Debug.Assert(!disposing || !allresults, "both disposing & allresults are true");
const int MaxConsecutiveFailure = 2000; // see WebData 72126 for why more than 1000
SQLLEN cRowsAffected;
short cColsAffected;
ODBC32.RetCode retcode, firstRetCode = ODBC32.RetCode.SUCCESS;
bool hasMoreResults;
bool hasColumns = false;
bool singleResult = IsCommandBehavior(CommandBehavior.SingleResult);
if (IsClosed)
{
throw ADP.DataReaderClosed("NextResult");
}
_fieldNameLookup = null;
if (IsCancelingCommand || _noMoreResults)
{
return false;
}
//Blow away the previous cache (since the next result set will have a different shape,
//different schema data, and different data.
_isRead = false;
_hasRows = HasRowsStatus.DontKnow;
_fieldNameLookup = null;
_metadata = null;
_schemaTable = null;
int loop = 0; // infinite loop protection, max out after 2000 consecutive failed results
OdbcErrorCollection? errors = null; // SQLBU 342112
do
{
_isValidResult = false;
retcode = StatementHandle.MoreResults();
hasMoreResults = ((retcode == ODBC32.RetCode.SUCCESS)
|| (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO));
if (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)
{
Connection!.HandleErrorNoThrow(StatementHandle, retcode);
}
else if (!disposing && (retcode != ODBC32.RetCode.NO_DATA) && (ODBC32.RetCode.SUCCESS != retcode))
{
// allow for building comulative error messages.
if (null == errors)
{
firstRetCode = retcode;
errors = new OdbcErrorCollection();
}
ODBC32.GetDiagErrors(errors, null, StatementHandle, retcode);
++loop;
}
if (!disposing && hasMoreResults)
{
loop = 0;
cRowsAffected = GetRowCount(); // get rowcount of the current resultset (if any)
CalculateRecordsAffected(cRowsAffected); // update recordsaffected
if (!singleResult)
{
// update row- and columncount
FieldCountNoThrow(out cColsAffected);
hasColumns = (0 != cColsAffected);
_isValidResult = hasColumns;
}
}
} while ((!singleResult && hasMoreResults && !hasColumns) // repeat for results with no columns
|| ((ODBC32.RetCode.NO_DATA != retcode) && allresults && (loop < MaxConsecutiveFailure)) // or process all results until done
|| (singleResult && hasMoreResults)); // or for any result in singelResult mode
if (retcode == ODBC32.RetCode.NO_DATA)
{
_dataCache = null;
_noMoreResults = true;
}
if (null != errors)
{
Debug.Assert(!disposing, "errors while disposing");
errors.SetSource(Connection!.Driver);
OdbcException exception = OdbcException.CreateException(errors, firstRetCode);
Connection.ConnectionIsAlive(exception);
throw exception;
}
return (hasMoreResults);
}
private void BuildMetaDataInfo()
{
int count = FieldCount;
MetaData[] metaInfos = new MetaData[count];
List<string>? qrytables;
bool needkeyinfo = IsCommandBehavior(CommandBehavior.KeyInfo);
bool isKeyColumn;
bool isHidden;
ODBC32.SQL_NULLABILITY nullable;
if (needkeyinfo)
qrytables = new List<string>();
else
qrytables = null;
// Find out all the metadata info, not all of this info will be available in all cases
//
for (int i = 0; i < count; i++)
{
metaInfos[i] = new MetaData();
metaInfos[i].ordinal = i;
TypeMap typeMap;
// for precision and scale we take the SQL_COLUMN_ attributes.
// Those attributes are supported by all provider versions.
// for size we use the octet length. We can't use column length because there is an incompatibility with the jet driver.
// furthermore size needs to be special cased for wchar types
//
typeMap = TypeMap.FromSqlType((ODBC32.SQL_TYPE)unchecked((int)GetColAttribute(i, ODBC32.SQL_DESC.CONCISE_TYPE, ODBC32.SQL_COLUMN.TYPE, ODBC32.HANDLER.THROW)));
if (typeMap._signType == true)
{
bool sign = (GetColAttribute(i, ODBC32.SQL_DESC.UNSIGNED, ODBC32.SQL_COLUMN.UNSIGNED, ODBC32.HANDLER.THROW).ToInt64() != 0);
// sign = true if the column is unsigned
typeMap = TypeMap.UpgradeSignedType(typeMap, sign);
}
metaInfos[i].typemap = typeMap;
metaInfos[i].size = GetColAttribute(i, ODBC32.SQL_DESC.OCTET_LENGTH, ODBC32.SQL_COLUMN.LENGTH, ODBC32.HANDLER.IGNORE);
// special case the 'n' types
//
switch (metaInfos[i].typemap._sql_type)
{
case ODBC32.SQL_TYPE.WCHAR:
case ODBC32.SQL_TYPE.WLONGVARCHAR:
case ODBC32.SQL_TYPE.WVARCHAR:
metaInfos[i].size /= 2;
break;
}
metaInfos[i].precision = (byte)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_COLUMN.PRECISION, ODBC32.SQL_COLUMN.PRECISION, ODBC32.HANDLER.IGNORE);
metaInfos[i].scale = (byte)GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_COLUMN.SCALE, ODBC32.SQL_COLUMN.SCALE, ODBC32.HANDLER.IGNORE);
metaInfos[i].isAutoIncrement = GetColAttribute(i, ODBC32.SQL_DESC.AUTO_UNIQUE_VALUE, ODBC32.SQL_COLUMN.AUTO_INCREMENT, ODBC32.HANDLER.IGNORE) == 1;
metaInfos[i].isReadOnly = (GetColAttribute(i, ODBC32.SQL_DESC.UPDATABLE, ODBC32.SQL_COLUMN.UPDATABLE, ODBC32.HANDLER.IGNORE) == (int)ODBC32.SQL_UPDATABLE.READONLY);
nullable = (ODBC32.SQL_NULLABILITY)(int)GetColAttribute(i, ODBC32.SQL_DESC.NULLABLE, ODBC32.SQL_COLUMN.NULLABLE, ODBC32.HANDLER.IGNORE);
metaInfos[i].isNullable = (nullable == ODBC32.SQL_NULLABILITY.NULLABLE);
switch (metaInfos[i].typemap._sql_type)
{
case ODBC32.SQL_TYPE.LONGVARCHAR:
case ODBC32.SQL_TYPE.WLONGVARCHAR:
case ODBC32.SQL_TYPE.LONGVARBINARY:
metaInfos[i].isLong = true;
break;
default:
metaInfos[i].isLong = false;
break;
}
if (IsCommandBehavior(CommandBehavior.KeyInfo))
{
// Note: Following two attributes are SQL Server specific (hence _SS in the name)
// SSS_WARNINGS_OFF
if (!Connection!.ProviderInfo.NoSqlCASSColumnKey)
{
isKeyColumn = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1;
if (isKeyColumn)
{
metaInfos[i].isKeyColumn = isKeyColumn;
metaInfos[i].isUnique = true;
needkeyinfo = false;
}
}
// SSS_WARNINGS_ON
metaInfos[i].baseSchemaName = GetColAttributeStr(i, ODBC32.SQL_DESC.SCHEMA_NAME, ODBC32.SQL_COLUMN.OWNER_NAME, ODBC32.HANDLER.IGNORE);
metaInfos[i].baseCatalogName = GetColAttributeStr(i, ODBC32.SQL_DESC.CATALOG_NAME, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE);
metaInfos[i].baseTableName = GetColAttributeStr(i, ODBC32.SQL_DESC.BASE_TABLE_NAME, ODBC32.SQL_COLUMN.TABLE_NAME, ODBC32.HANDLER.IGNORE);
metaInfos[i].baseColumnName = GetColAttributeStr(i, ODBC32.SQL_DESC.BASE_COLUMN_NAME, ODBC32.SQL_COLUMN.NAME, ODBC32.HANDLER.IGNORE);
if (Connection.IsV3Driver)
{
if (string.IsNullOrEmpty(metaInfos[i].baseTableName))
{
// Driver didn't return the necessary information from GetColAttributeStr.
// Try GetDescField()
metaInfos[i].baseTableName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_TABLE_NAME, ODBC32.HANDLER.IGNORE);
}
if (string.IsNullOrEmpty(metaInfos[i].baseColumnName))
{
// Driver didn't return the necessary information from GetColAttributeStr.
// Try GetDescField()
metaInfos[i].baseColumnName = GetDescFieldStr(i, ODBC32.SQL_DESC.BASE_COLUMN_NAME, ODBC32.HANDLER.IGNORE);
}
}
if ((metaInfos[i].baseTableName is string baseTableName) && !(qrytables!.Contains(baseTableName)))
{
qrytables.Add(baseTableName);
}
}
// If primary key or autoincrement, then must also be unique
if (metaInfos[i].isKeyColumn || metaInfos[i].isAutoIncrement)
{
if (nullable == ODBC32.SQL_NULLABILITY.UNKNOWN)
metaInfos[i].isNullable = false; // We can safely assume these are not nullable
}
}
// now loop over the hidden columns (if any)
// SSS_WARNINGS_OFF
if (!Connection!.ProviderInfo.NoSqlCASSColumnKey)
{
for (int i = count; i < count + _hiddenColumns; i++)
{
isKeyColumn = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1;
if (isKeyColumn)
{
isHidden = GetColAttribute(i, (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_HIDDEN, (ODBC32.SQL_COLUMN)(-1), ODBC32.HANDLER.IGNORE) == 1;
if (isHidden)
{
for (int j = 0; j < count; j++)
{
metaInfos[j].isKeyColumn = false; // downgrade keycolumn
metaInfos[j].isUnique = false; // downgrade uniquecolumn
}
}
}
}
}
// SSS_WARNINGS_ON
// Blow away the previous metadata
_metadata = metaInfos;
// If key info is requested, then we have to make a few more calls to get the
// special columns. This may not succeed for all drivers, so ignore errors and
// fill in as much as possible.
if (IsCommandBehavior(CommandBehavior.KeyInfo))
{
if ((qrytables != null) && (qrytables.Count > 0))
{
List<string>.Enumerator tablesEnum = qrytables.GetEnumerator();
QualifiedTableName qualifiedTableName = new QualifiedTableName(Connection.QuoteChar(ADP.GetSchemaTable));
while (tablesEnum.MoveNext())
{
// Find the primary keys, identity and autincrement columns
qualifiedTableName.Table = tablesEnum.Current;
if (RetrieveKeyInfo(needkeyinfo, qualifiedTableName, false) <= 0)
{
RetrieveKeyInfo(needkeyinfo, qualifiedTableName, true);
}
}
}
else
{
// Some drivers ( < 3.x ?) do not provide base table information. In this case try to
// find it by parsing the statement
QualifiedTableName qualifiedTableName = new QualifiedTableName(Connection.QuoteChar(ADP.GetSchemaTable), GetTableNameFromCommandText());
if (!string.IsNullOrEmpty(qualifiedTableName.Table))
{ // fxcop
SetBaseTableNames(qualifiedTableName);
if (RetrieveKeyInfo(needkeyinfo, qualifiedTableName, false) <= 0)
{
RetrieveKeyInfo(needkeyinfo, qualifiedTableName, true);
}
}
}
}
}
private DataTable NewSchemaTable()
{
DataTable schematable = new DataTable("SchemaTable");
schematable.Locale = CultureInfo.InvariantCulture;
schematable.MinimumCapacity = this.FieldCount;
//Schema Columns
DataColumnCollection columns = schematable.Columns;
columns.Add(new DataColumn("ColumnName", typeof(string)));
columns.Add(new DataColumn("ColumnOrdinal", typeof(int))); // UInt32
columns.Add(new DataColumn("ColumnSize", typeof(int))); // UInt32
columns.Add(new DataColumn("NumericPrecision", typeof(short))); // UInt16
columns.Add(new DataColumn("NumericScale", typeof(short)));
columns.Add(new DataColumn("DataType", typeof(object)));
columns.Add(new DataColumn("ProviderType", typeof(int)));
columns.Add(new DataColumn("IsLong", typeof(bool)));
columns.Add(new DataColumn("AllowDBNull", typeof(bool)));
columns.Add(new DataColumn("IsReadOnly", typeof(bool)));
columns.Add(new DataColumn("IsRowVersion", typeof(bool)));
columns.Add(new DataColumn("IsUnique", typeof(bool)));
columns.Add(new DataColumn("IsKey", typeof(bool)));
columns.Add(new DataColumn("IsAutoIncrement", typeof(bool)));
columns.Add(new DataColumn("BaseSchemaName", typeof(string)));
columns.Add(new DataColumn("BaseCatalogName", typeof(string)));
columns.Add(new DataColumn("BaseTableName", typeof(string)));
columns.Add(new DataColumn("BaseColumnName", typeof(string)));
// MDAC Bug 79231
foreach (DataColumn column in columns)
{
column.ReadOnly = true;
}
return schematable;
}
// The default values are already defined in DbSchemaRows (see DbSchemaRows.cs) so there is no need to set any default value
//
public override DataTable? GetSchemaTable()
{
if (IsClosed)
{ // MDAC 68331
throw ADP.DataReaderClosed("GetSchemaTable"); // can't use closed connection
}
if (_noMoreResults)
{
return null; // no more results
}
if (null != _schemaTable)
{
return _schemaTable; // return cached schematable
}
//Delegate, to have the base class setup the structure
DataTable schematable = NewSchemaTable();
if (FieldCount == 0)
{
return schematable;
}
if (_metadata == null)
{
BuildMetaDataInfo();
}
DataColumn columnName = schematable.Columns["ColumnName"]!;
DataColumn columnOrdinal = schematable.Columns["ColumnOrdinal"]!;
DataColumn columnSize = schematable.Columns["ColumnSize"]!;
DataColumn numericPrecision = schematable.Columns["NumericPrecision"]!;
DataColumn numericScale = schematable.Columns["NumericScale"]!;
DataColumn dataType = schematable.Columns["DataType"]!;
DataColumn providerType = schematable.Columns["ProviderType"]!;
DataColumn isLong = schematable.Columns["IsLong"]!;
DataColumn allowDBNull = schematable.Columns["AllowDBNull"]!;
DataColumn isReadOnly = schematable.Columns["IsReadOnly"]!;
DataColumn isRowVersion = schematable.Columns["IsRowVersion"]!;
DataColumn isUnique = schematable.Columns["IsUnique"]!;
DataColumn isKey = schematable.Columns["IsKey"]!;
DataColumn isAutoIncrement = schematable.Columns["IsAutoIncrement"]!;
DataColumn baseSchemaName = schematable.Columns["BaseSchemaName"]!;
DataColumn baseCatalogName = schematable.Columns["BaseCatalogName"]!;
DataColumn baseTableName = schematable.Columns["BaseTableName"]!;
DataColumn baseColumnName = schematable.Columns["BaseColumnName"]!;
//Populate the rows (1 row for each column)
int count = FieldCount;
for (int i = 0; i < count; i++)
{
DataRow row = schematable.NewRow();
row[columnName] = GetName(i); //ColumnName
row[columnOrdinal] = i; //ColumnOrdinal
row[columnSize] = unchecked((int)Math.Min(Math.Max(int.MinValue, _metadata![i].size.ToInt64()), int.MaxValue));
row[numericPrecision] = (short)_metadata[i].precision;
row[numericScale] = (short)_metadata[i].scale;
row[dataType] = _metadata[i].typemap._type; //DataType
row[providerType] = _metadata[i].typemap._odbcType; // ProviderType
row[isLong] = _metadata[i].isLong; // IsLong
row[allowDBNull] = _metadata[i].isNullable; //AllowDBNull
row[isReadOnly] = _metadata[i].isReadOnly; // IsReadOnly
row[isRowVersion] = _metadata[i].isRowVersion; //IsRowVersion
row[isUnique] = _metadata[i].isUnique; //IsUnique
row[isKey] = _metadata[i].isKeyColumn; // IsKey
row[isAutoIncrement] = _metadata[i].isAutoIncrement; //IsAutoIncrement
//BaseSchemaName
row[baseSchemaName] = _metadata[i].baseSchemaName;
//BaseCatalogName
row[baseCatalogName] = _metadata[i].baseCatalogName;
//BaseTableName
row[baseTableName] = _metadata[i].baseTableName;
//BaseColumnName
row[baseColumnName] = _metadata[i].baseColumnName;
schematable.Rows.Add(row);
row.AcceptChanges();
}
_schemaTable = schematable;
return schematable;
}
internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTableName, bool quoted)
{
Debug.Assert(_metadata != null);
ODBC32.RetCode retcode;
string columnname;
int ordinal;
int keyColumns = 0;
IntPtr cbActual = IntPtr.Zero;
if (IsClosed || (_cmdWrapper == null))
{
return 0; // Can't do anything without a second handle
}
_cmdWrapper.CreateKeyInfoStatementHandle();
CNativeBuffer buffer = Buffer;
bool mustRelease = false;
Debug.Assert(buffer.Length >= 264, "Native buffer to small (_buffer.Length < 264)");
try
{
buffer.DangerousAddRef(ref mustRelease);
if (needkeyinfo)
{
if (!Connection!.ProviderInfo.NoSqlPrimaryKeys)
{
// Get the primary keys
retcode = KeyInfoStatementHandle.PrimaryKeys(
qualifiedTableName.Catalog,
qualifiedTableName.Schema,
qualifiedTableName.GetTable(quoted)!);
if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO))
{
bool noUniqueKey = false;
// We are only interested in column name
buffer.WriteInt16(0, 0);
retcode = KeyInfoStatementHandle.BindColumn2(
(short)(ODBC32.SQL_PRIMARYKEYS.COLUMNNAME), // Column Number
ODBC32.SQL_C.WCHAR,
buffer.PtrOffset(0, 256),
(IntPtr)256,
buffer.PtrOffset(256, IntPtr.Size).Handle);
while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch()))
{
cbActual = buffer.ReadIntPtr(256);
columnname = buffer.PtrToStringUni(0, (int)cbActual / 2/*cch*/);
ordinal = this.GetOrdinalFromBaseColName(columnname);
if (ordinal != -1)
{
keyColumns++;
_metadata[ordinal].isKeyColumn = true;
_metadata[ordinal].isUnique = true;
_metadata[ordinal].isNullable = false;
_metadata[ordinal].baseTableName = qualifiedTableName.Table;
if (_metadata[ordinal].baseColumnName == null)
{
_metadata[ordinal].baseColumnName = columnname;
}
}
else
{
noUniqueKey = true;
break; // no need to go over the remaining columns anymore
}
}
//
// if we got keyinfo from the column we dont even get to here!
//
// reset isUnique flag if the key(s) are not unique
//
if (noUniqueKey)
{
foreach (MetaData metadata in _metadata)
{
metadata.isKeyColumn = false;
}
}
// Unbind the column
retcode = KeyInfoStatementHandle.BindColumn3(
(short)(ODBC32.SQL_PRIMARYKEYS.COLUMNNAME), // SQLUSMALLINT ColumnNumber
ODBC32.SQL_C.WCHAR, // SQLSMALLINT TargetType
buffer.DangerousGetHandle()); // SQLLEN * StrLen_or_Ind
}
else
{
if ("IM001" == Command!.GetDiagSqlState())
{
Connection.ProviderInfo.NoSqlPrimaryKeys = true;
}
}
}
if (keyColumns == 0)
{
// SQLPrimaryKeys did not work. Have to use the slower SQLStatistics to obtain key information
KeyInfoStatementHandle.MoreResults();
keyColumns += RetrieveKeyInfoFromStatistics(qualifiedTableName, quoted);
}
KeyInfoStatementHandle.MoreResults();
}
// Get the special columns for version
retcode = KeyInfoStatementHandle.SpecialColumns(qualifiedTableName.GetTable(quoted)!);
if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO))
{
// We are only interested in column name
cbActual = IntPtr.Zero;
buffer.WriteInt16(0, 0);
retcode = KeyInfoStatementHandle.BindColumn2(
(short)(ODBC32.SQL_SPECIALCOLUMNSET.COLUMN_NAME),
ODBC32.SQL_C.WCHAR,
buffer.PtrOffset(0, 256),
(IntPtr)256,
buffer.PtrOffset(256, IntPtr.Size).Handle);
while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch()))
{
cbActual = buffer.ReadIntPtr(256);
columnname = buffer.PtrToStringUni(0, (int)cbActual / 2/*cch*/);
ordinal = this.GetOrdinalFromBaseColName(columnname);
if (ordinal != -1)
{
_metadata[ordinal].isRowVersion = true;
if (_metadata[ordinal].baseColumnName == null)
{
_metadata[ordinal].baseColumnName = columnname;
}
}
}
// Unbind the column
retcode = KeyInfoStatementHandle.BindColumn3(
(short)(ODBC32.SQL_SPECIALCOLUMNSET.COLUMN_NAME),
ODBC32.SQL_C.WCHAR,
buffer.DangerousGetHandle());
retcode = KeyInfoStatementHandle.MoreResults();
}
else
{
// i've seen "DIAG [HY000] [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt (0) "
// how did we get here? SqlServer does not allow a second handle (Keyinfostmt) anyway...
//
/*
string msg = "Unexpected failure of SQLSpecialColumns. Code = " + Command.GetDiagSqlState();
Debug.Assert (false, msg);
*/
}
}
finally
{
if (mustRelease)
{
buffer.DangerousRelease();
}
}
return keyColumns;
}
// Uses SQLStatistics to retrieve key information for a table
private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, bool quoted)
{
Debug.Assert(_metadata != null);
ODBC32.RetCode retcode;
string columnname = string.Empty;
string indexname = string.Empty;
string currentindexname = string.Empty;
int[] indexcolumnordinals = new int[16];
int[] pkcolumnordinals = new int[16];
int npkcols = 0;
int ncols = 0; // No of cols in the index
bool partialcolumnset = false;
int ordinal;
int indexordinal;
IntPtr cbIndexLen = IntPtr.Zero;
IntPtr cbColnameLen = IntPtr.Zero;
int keyColumns = 0;
// devnote: this test is already done by calling method ...
// if (IsClosed) return; // protect against dead connection
string tablename1 = qualifiedTableName.GetTable(quoted)!;
// Select only unique indexes
retcode = KeyInfoStatementHandle.Statistics(tablename1);
if (retcode != ODBC32.RetCode.SUCCESS)
{
// We give up at this point
return 0;
}
CNativeBuffer buffer = Buffer;
bool mustRelease = false;
Debug.Assert(buffer.Length >= 544, "Native buffer to small (_buffer.Length < 544)");
try
{
buffer.DangerousAddRef(ref mustRelease);
const int colnameBufOffset = 0;
const int indexBufOffset = 256;
const int ordinalBufOffset = 512;
const int colnameActualOffset = 520;
const int indexActualOffset = 528;
const int ordinalActualOffset = 536;
HandleRef colnamebuf = buffer.PtrOffset(colnameBufOffset, 256);
HandleRef indexbuf = buffer.PtrOffset(indexBufOffset, 256);
HandleRef ordinalbuf = buffer.PtrOffset(ordinalBufOffset, 4);
IntPtr colnameActual = buffer.PtrOffset(colnameActualOffset, IntPtr.Size).Handle;
IntPtr indexActual = buffer.PtrOffset(indexActualOffset, IntPtr.Size).Handle;
IntPtr ordinalActual = buffer.PtrOffset(ordinalActualOffset, IntPtr.Size).Handle;
//We are interested in index name, column name, and ordinal
buffer.WriteInt16(indexBufOffset, 0);
retcode = KeyInfoStatementHandle.BindColumn2(
(short)(ODBC32.SQL_STATISTICS.INDEXNAME),
ODBC32.SQL_C.WCHAR,
indexbuf,
(IntPtr)256,
indexActual);
retcode = KeyInfoStatementHandle.BindColumn2(
(short)(ODBC32.SQL_STATISTICS.ORDINAL_POSITION),
ODBC32.SQL_C.SSHORT,
ordinalbuf,
(IntPtr)4,
ordinalActual);
buffer.WriteInt16(ordinalBufOffset, 0);
retcode = KeyInfoStatementHandle.BindColumn2(
(short)(ODBC32.SQL_STATISTICS.COLUMN_NAME),
ODBC32.SQL_C.WCHAR,
colnamebuf,
(IntPtr)256,
colnameActual);
// Find the best unique index on the table, use the ones whose columns are
// completely covered by the query.
while (ODBC32.RetCode.SUCCESS == (retcode = KeyInfoStatementHandle.Fetch()))
{
cbColnameLen = buffer.ReadIntPtr(colnameActualOffset);
cbIndexLen = buffer.ReadIntPtr(indexActualOffset);
// If indexname is not returned, skip this row
if (0 == buffer.ReadInt16(indexBufOffset))
continue; // Not an index row, get next row.
columnname = buffer.PtrToStringUni(colnameBufOffset, (int)cbColnameLen / 2/*cch*/);
indexname = buffer.PtrToStringUni(indexBufOffset, (int)cbIndexLen / 2/*cch*/);
ordinal = (int)buffer.ReadInt16(ordinalBufOffset);
if (SameIndexColumn(currentindexname, indexname, ordinal, ncols))
{
// We are still working on the same index
if (partialcolumnset)
continue; // We don't have all the keys for this index, so we can't use it
ordinal = this.GetOrdinalFromBaseColName(columnname, qualifiedTableName.Table);
if (ordinal == -1)
{
partialcolumnset = true;
}
else
{
// Add the column to the index column set
if (ncols < 16)
indexcolumnordinals[ncols++] = ordinal;
else // Can't deal with indexes > 16 columns
partialcolumnset = true;
}
}
else
{
// We got a new index, save the previous index information
if (!partialcolumnset && (ncols != 0))
{
// Choose the unique index with least columns as primary key
if ((npkcols == 0) || (npkcols > ncols))
{
npkcols = ncols;
for (int i = 0; i < ncols; i++)
pkcolumnordinals[i] = indexcolumnordinals[i];
}
}
// Reset the parameters for a new index
ncols = 0;
currentindexname = indexname;
partialcolumnset = false;
// Add this column to index
ordinal = this.GetOrdinalFromBaseColName(columnname, qualifiedTableName.Table);
if (ordinal == -1)
{
partialcolumnset = true;
}
else
{
// Add the column to the index column set
indexcolumnordinals[ncols++] = ordinal;
}
}
// Go on to the next column
}
// Do we have an index?
if (!partialcolumnset && (ncols != 0))
{
// Choose the unique index with least columns as primary key
if ((npkcols == 0) || (npkcols > ncols))
{
npkcols = ncols;
for (int i = 0; i < ncols; i++)
pkcolumnordinals[i] = indexcolumnordinals[i];
}
}
// Mark the chosen index as primary key
if (npkcols != 0)
{
for (int i = 0; i < npkcols; i++)
{
indexordinal = pkcolumnordinals[i];
keyColumns++;
_metadata[indexordinal].isKeyColumn = true;
// should we set isNullable = false?
// This makes the QuikTest against Jet fail
//
// test test test - we don't know if this is nulalble or not so why do we want to set it to a value?
_metadata[indexordinal].isNullable = false;
_metadata[indexordinal].isUnique = true;
if (_metadata[indexordinal].baseTableName == null)
{
_metadata[indexordinal].baseTableName = qualifiedTableName.Table;
}
if (_metadata[indexordinal].baseColumnName == null)
{
_metadata[indexordinal].baseColumnName = columnname;
}
}
}
// Unbind the columns
_cmdWrapper!.FreeKeyInfoStatementHandle(ODBC32.STMT.UNBIND);
}
finally
{
if (mustRelease)
{
buffer.DangerousRelease();
}
}
return keyColumns;
}
internal bool SameIndexColumn(string currentindexname, string indexname, int ordinal, int ncols)
{
if (string.IsNullOrEmpty(currentindexname))
{
return false;
}
if ((currentindexname == indexname) &&
(ordinal == ncols + 1))
return true;
return false;
}
internal int GetOrdinalFromBaseColName(string? columnname)
{
return GetOrdinalFromBaseColName(columnname, null);
}
internal int GetOrdinalFromBaseColName(string? columnname, string? tablename)
{
if (string.IsNullOrEmpty(columnname))
{
return -1;
}
if (_metadata != null)
{
int count = FieldCount;
for (int i = 0; i < count; i++)
{
if ((_metadata[i].baseColumnName != null) &&
(columnname == _metadata[i].baseColumnName))
{
if (!string.IsNullOrEmpty(tablename))
{
if (tablename == _metadata[i].baseTableName)
{
return i;
} // end if
} // end if
else
{
return i;
} // end else
}
}
}
// We can't find it in base column names, try regular colnames
return this.IndexOf(columnname);
}
// We try parsing the SQL statement to get the table name as a last resort when
// the driver doesn't return this information back to us.
//
// we can't handle multiple tablenames (JOIN)
// only the first tablename will be returned
internal string? GetTableNameFromCommandText()
{
if (_command == null)
{
return null;
}
string localcmdtext = _cmdText;
if (string.IsNullOrEmpty(localcmdtext))
{ // fxcop
return null;
}
string tablename;
int idx;
CStringTokenizer tokenstmt = new CStringTokenizer(localcmdtext, Connection!.QuoteChar(ADP.GetSchemaTable)[0], Connection.EscapeChar(ADP.GetSchemaTable));
if (tokenstmt.StartsWith("select") == true)
{
// select command, search for from clause
idx = tokenstmt.FindTokenIndex("from");
}
else
{
if ((tokenstmt.StartsWith("insert") == true) ||
(tokenstmt.StartsWith("update") == true) ||
(tokenstmt.StartsWith("delete") == true))
{
// Get the following word
idx = tokenstmt.CurrentPosition;
}
else
idx = -1;
}
if (idx == -1)
return null;
// The next token is the table name
tablename = tokenstmt.NextToken();
localcmdtext = tokenstmt.NextToken();
if ((localcmdtext.Length > 0) && (localcmdtext[0] == ','))
{
return null; // can't handle multiple tables
}
if ((localcmdtext.Length == 2) &&
((localcmdtext[0] == 'a') || (localcmdtext[0] == 'A')) &&
((localcmdtext[1] == 's') || (localcmdtext[1] == 'S')))
{
// aliased table, skip the alias name
localcmdtext = tokenstmt.NextToken();
localcmdtext = tokenstmt.NextToken();
if ((localcmdtext.Length > 0) && (localcmdtext[0] == ','))
{
return null; // Multiple tables
}
}
return tablename;
}
internal void SetBaseTableNames(QualifiedTableName qualifiedTableName)
{
int count = FieldCount;
for (int i = 0; i < count; i++)
{
if (_metadata![i].baseTableName == null)
{
_metadata[i].baseTableName = qualifiedTableName.Table;
_metadata[i].baseSchemaName = qualifiedTableName.Schema;
_metadata[i].baseCatalogName = qualifiedTableName.Catalog;
}
}
return;
}
internal sealed class QualifiedTableName
{
private readonly string? _catalogName;
private readonly string? _schemaName;
private string? _tableName;
private string? _quotedTableName;
private readonly string _quoteChar;
internal string? Catalog
{
get
{
return _catalogName;
}
}
internal string? Schema
{
get
{
return _schemaName;
}
}
internal string? Table
{
get
{
return _tableName;
}
set
{
_quotedTableName = value;
_tableName = UnQuote(value);
}
}
internal string? QuotedTable
{
get
{
return _quotedTableName;
}
}
internal string? GetTable(bool flag)
{
return (flag ? QuotedTable : Table);
}
internal QualifiedTableName(string quoteChar)
{
_quoteChar = quoteChar;
}
internal QualifiedTableName(string quoteChar, string? qualifiedname)
{
_quoteChar = quoteChar;
string?[] names = ParseProcedureName(qualifiedname, quoteChar, quoteChar);
_catalogName = UnQuote(names[1]);
_schemaName = UnQuote(names[2]);
_quotedTableName = names[3];
_tableName = UnQuote(names[3]);
}
private string? UnQuote(string? str)
{
if ((str != null) && (str.Length > 0))
{
char quoteChar = _quoteChar[0];
if (str[0] == quoteChar)
{
Debug.Assert(str.Length > 1, "Illegal string, only one char that is a quote");
Debug.Assert(str[str.Length - 1] == quoteChar, "Missing quote at end of string that begins with quote");
if (str.Length > 1 && str[str.Length - 1] == quoteChar)
{
str = str.Substring(1, str.Length - 2);
}
}
}
return str;
}
// Note: copy-and pasted from internal DbCommandBuilder implementation
// Note: Per definition (ODBC reference) the CatalogSeparator comes before and after the
// catalog name, the SchemaSeparator is undefined. Does it come between Schema and Table?
internal static string?[] ParseProcedureName(string? name, string? quotePrefix, string? quoteSuffix)
{
// Procedure may consist of up to four parts:
// 0) Server
// 1) Catalog
// 2) Schema
// 3) ProcedureName
//
// Parse the string into four parts, allowing the last part to contain '.'s.
// If less than four period delimited parts, use the parts from procedure backwards.
//
const string Separator = ".";
string?[] qualifiers = new string[4];
if (!string.IsNullOrEmpty(name))
{
bool useQuotes = !string.IsNullOrEmpty(quotePrefix) && !string.IsNullOrEmpty(quoteSuffix);
int currentPos = 0, parts;
for (parts = 0; (parts < qualifiers.Length) && (currentPos < name.Length); ++parts)
{
int startPos = currentPos;
// does the part begin with a quotePrefix?
if (useQuotes && (name.IndexOf(quotePrefix!, currentPos, quotePrefix!.Length, StringComparison.Ordinal) == currentPos))
{
Debug.Assert(quotePrefix != null && quoteSuffix != null);
currentPos += quotePrefix.Length; // move past the quotePrefix
// search for the quoteSuffix (or end of string)
while (currentPos < name.Length)
{
currentPos = name.IndexOf(quoteSuffix, currentPos, StringComparison.Ordinal);
if (currentPos < 0)
{
// error condition, no quoteSuffix
currentPos = name.Length;
break;
}
else
{
currentPos += quoteSuffix.Length; // move past the quoteSuffix
// is this a double quoteSuffix?
if ((currentPos < name.Length) && (name.IndexOf(quoteSuffix, currentPos, quoteSuffix.Length, StringComparison.Ordinal) == currentPos))
{
// a second quoteSuffix, continue search for terminating quoteSuffix
currentPos += quoteSuffix.Length; // move past the second quoteSuffix
}
else
{
// found the terminating quoteSuffix
break;
}
}
}
}
// search for separator (either no quotePrefix or already past quoteSuffix)
if (currentPos < name.Length)
{
currentPos = name.IndexOf(Separator, currentPos, StringComparison.Ordinal);
if ((currentPos < 0) || (parts == qualifiers.Length - 1))
{
// last part that can be found
currentPos = name.Length;
}
}
qualifiers[parts] = name.Substring(startPos, currentPos - startPos);
currentPos += Separator.Length;
}
// allign the qualifiers if we had less than MaxQualifiers
for (int j = qualifiers.Length - 1; 0 <= j; --j)
{
qualifiers[j] = ((0 < parts) ? qualifiers[--parts] : null);
}
}
return qualifiers;
}
}
private sealed class MetaData
{
internal int ordinal;
internal TypeMap typemap = null!; // Lazy-initialized
internal SQLLEN size;
internal byte precision;
internal byte scale;
internal bool isAutoIncrement;
internal bool isUnique;
internal bool isReadOnly;
internal bool isNullable;
internal bool isRowVersion;
internal bool isLong;
internal bool isKeyColumn;
internal string? baseSchemaName;
internal string? baseCatalogName;
internal string? baseTableName;
internal string? baseColumnName;
}
}
}
| 42.051862 | 198 | 0.484568 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs | 126,492 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Epam.Task2.Rectangle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Epam.Task2.Rectangle")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("39624d28-7c19-4556-a57f-6301fb93df8d")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.486486 | 99 | 0.766598 | [
"MIT"
] | MaxiKvaksi/XT-2018Q4 | Epam.Task2/Epam.Task2.Rectangle/Properties/AssemblyInfo.cs | 2,041 | C# |
using Ocelot.Configuration.File;
namespace Ocelot.Configuration.Creator
{
public interface IHeaderFindAndReplaceCreator
{
HeaderTransformations Create(FileReRoute fileReRoute);
}
}
| 21 | 63 | 0.738095 | [
"MIT"
] | 520xchly/Ocelot | src/Ocelot/Configuration/Creator/IHeaderFindAndReplaceCreator.cs | 210 | C# |
using System.Threading.Tasks;
using Jugnoon.BLL;
using Jugnoon.Utility;
using Jugnoon.Models;
using Jugnoon.Framework;
using System.Collections.Generic;
namespace Jugnoon.Services
{
public static class EmailSenderExtensions
{
/// <summary>
/// Send email through contact us form
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static Task ContactUsEmailAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, ContactUsViewModel entity)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
var lst = MailTemplateBLL.Get_Template(context, "CONTACTUS").Result;
if (lst.Count > 0)
{
string subject = MailProcess.Process2(lst[0].subject, "\\[fullname\\]", entity.SenderName);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[fullname\\]", entity.SenderName);
contents = MailProcess.Process2(contents, "\\[phone\\]", entity.PhoneNumber);
contents = MailProcess.Process2(contents, "\\[email\\]", entity.EmailAddress);
contents = MailProcess.Process2(contents, "\\[message\\]", entity.Body);
// attach signature
contents = MailProcess.Process2(contents, "\\[website\\]", Settings.Configs.GeneralSettings.website_title);
contents = MailProcess.Process2(contents, "\\[website_url\\]", SiteConfiguration.URL);
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(email, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Send email reset autorization and processing link to user
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <param name="link"></param>
/// <returns></returns>
public static Task ChangeEmailResetAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, string username, string link)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
if (username.Contains("@"))
username = "User";
var lst = MailTemplateBLL.Get_Template(context, "USREMLCREQ").Result;
if (lst.Count > 0)
{
string subject = MailProcess.Process2(lst[0].subject, "\\[username\\]", username);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[username\\]", username);
contents = MailProcess.Process2(contents, "\\[key_url\\]", System.Text.Encodings.Web.HtmlEncoder.Default.Encode(link));
contents = MailProcess.Process2(contents, "\\[emailaddress\\]", email);
contents = MailProcess.Process2(contents, "\\[domainname\\]", Jugnoon.Settings.Configs.GeneralSettings.website_title);
contents = MailProcess.Process2(contents, "\\[unsubscribeurl\\]", UrlConfig.UnsubscribeUrl);
// attach signature
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(email, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Send notification to user when email reset event completed successfully
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <returns></returns>
public static Task ChangeEmailResetCompletedAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, string username)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
if (username.Contains("@"))
username = "User";
var lst = MailTemplateBLL.Get_Template(context, "USREMLCHNG").Result;
if (lst.Count > 0)
{
string subject = MailProcess.Process2(lst[0].subject, "\\[username\\]", username);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[username\\]", username);
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(email, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Sending password reset and processling link to user email
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <param name="link"></param>
/// <returns></returns>
public static Task SendForgotPasswordResetAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, string username, string link)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
if (username.Contains("@"))
username = "User";
var lst = MailTemplateBLL.Get_Template(context, "FORPASS").Result;
if (lst.Count > 0)
{
string subject = MailProcess.Process2(lst[0].subject, "\\[username\\]", username);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[username\\]", username);
string url = "<a href=\"" + link + "\">" + link + "</a>";
contents = MailProcess.Process2(contents, "\\[key_url\\]", System.Text.Encodings.Web.HtmlEncoder.Default.Encode(link));
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(email, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Send notification to user when password reset event completed successfully
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <param name="link"></param>
/// <param name="password"></param>
/// <returns></returns>
public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, string username, string link, string password)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
var lst = MailTemplateBLL.Get_Template(context, "USRREG").Result;
if (lst.Count > 0)
{
if (username.Contains("@"))
username = "User";
string subject = MailProcess.Process2(lst[0].subject, "\\[username\\]", username);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[username\\]", username);
contents = MailProcess.Process2(contents, "\\[email\\]", email);
contents = MailProcess.Process2(contents, "\\[password\\]", password);
string url = "<a href=\"" + link + "\">" + link + "</a>";
contents = MailProcess.Process2(contents, "\\[key_url\\]", System.Text.Encodings.Web.HtmlEncoder.Default.Encode(link));
// attach signature
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(email, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Send email notification to admin when new user signup
/// </summary>
/// <param name="emailSender"></param>
/// <param name="context"></param>
/// <param name="email"></param>
/// <param name="username"></param>
/// <returns></returns>
public static Task SendEmailNotificationAsync(this IEmailSender emailSender, ApplicationDbContext context, string email, string username)
{
if (Settings.Configs.SmtpSettings.enable_email)
{
var lst = MailTemplateBLL.Get_Template(context, "USRREGADM").Result;
if (lst.Count > 0)
{
string subject = MailProcess.Process2(lst[0].subject, "\\[username\\]", username);
subject = MailProcess.Prepare_Email_Signature(subject);
string contents = MailProcess.Process2(lst[0].contents, "\\[username\\]", username);
contents = MailProcess.Process2(contents, "\\[email\\]", email);
// attach signature
contents = MailProcess.Prepare_Email_Signature(contents);
return emailSender.SendEmailAsync(Jugnoon.Settings.Configs.GeneralSettings.admin_mail, subject, contents);
}
}
return Task.CompletedTask;
}
/// <summary>
/// Sample method for sending email via Mandril using Mailchimp Email Templates
/// </summary>
/// <param name="emailSender"></param>
/// <param name="email"></param>
/// <param name="activation_link"></param>
/// <param name="contact_link"></param>
/// <param name="templateName"></param>
/// <returns></returns>
public static Task Mandril_Template(this IEmailSender emailSender, string email, string activation_link, string contact_link, string templateName)
{
var templateVariables = new Dictionary<string, dynamic>();
// Mailchimp Email Template Variables
templateVariables.Add("ACTIVATION_LINK", activation_link);
templateVariables.Add("CONTACT_FORM", contact_link);
// Email Subject
var subject = "Account Activation.";
// Send Email
return emailSender.SendEmailAsync(email, "", "", subject, templateName, templateVariables);
}
}
}
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
* Copyright 2007 - 2020 MediaSoftPro
* For more information email at support@mediasoftpro.com
*/
| 45.304 | 175 | 0.570634 | [
"MIT"
] | mediasoftpro/dictionaryengine | DictionaryEngine/DictionaryEngine/Models/Extensions/EmailSenderExtension.cs | 11,328 | C# |
public class Dinglemouse
{
private string firstName;
private string lastName;
public string FullName
{
get
{
return (firstName + " " + lastName).Trim();
}
}
public Dinglemouse(string firstName, string lastName)
{
this.firstName = firstName.Trim();
this.lastName = lastName.Trim();
}
} | 18.277778 | 55 | 0.641337 | [
"MIT"
] | collenirwin/Codewars-Solutions | Solutions/C#/FIXME Get Full Name(7 kyu).cs | 329 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace CSharp_Basics
{
// [] - defines attributes we will take closer look at them in day 3
[TestFixture]
public class DataTypesAndVariables
{
/*
*1. Select each test and uncomment it (Ctrl+K, Ctrl+U)
*2. Then follow the rules described in summary.
*3. run test.
*4. If test passed, you could move to next exercise.
*/
// usefull link: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types
// /// <summary>
// /// Integers are symbolized as int
// /// create 3 integers with following names
// /// singleDigit, number, lessThenZero
// /// make they values: 6 14 -100
// /// </summary>
// [Test]
// public void Creating_Integeres()
// {
// // int - describes type
// // example - is name of variable, english names are preferred
// // = equal sign is used for assigning values.
// // 0 - the value
// // ; - IMPORTANT ';' sign means and of the command usually it is on end of the line - remember about it
// int example = 0;
//
// Assert.AreEqual(example, 0, "Example Has wrong value did you changed it?");
// Assert.AreEqual(singleDigit, 6, "Example Has wrong value did you changed it?");
// Assert.That(singleDigit, Is.TypeOf<int>(), "You sure it is int?");
// Assert.AreEqual(number, 14, "Example Has wrong value did you changed it?");
// Assert.That(singleDigit, Is.TypeOf<int>(), "You sure it is int?");
// Assert.AreEqual(lessThenZero, -100, "Example Has wrong value did you changed it?");
// Assert.That(singleDigit, Is.TypeOf<int>(), "You sure it is int?");
// }
// /// <summary>
// /// Basic operations at integers are
// /// add(+), subtract(-), multiply(*), divide(/)
// /// make integer variables: subtract, multiply and divide perform operations.
// /// discuss why divide is not working
// /// </summary>
// [Test]
// public void Operation_On_Integers()
// {
// int X = 4;
// int Y = 5;
//
// /*
// * There are few other ways you can do this
// * int add = 0;
// * add = x+y;
// */
// int add = X + Y;
//
// Assert.AreEqual(9, add, "Example Has wrong value did you changed it?");
// Assert.AreEqual(-1, subtract, "Wrong value maybe other way around?");
// Assert.That(subtract, Is.TypeOf<int>(), "You sure it is int?");
// Assert.AreEqual(20, multiply, "Example Has wrong value did you changed it?");
// Assert.That(multiply, Is.TypeOf<int>(), "You sure it is int?");
// Assert.AreEqual(1.25, divide, "Example Has wrong value did you changed it?");
// Assert.That(divide, Is.TypeOf<int>(), "You sure it is int?");
// }
// /// <summary>
// /// There are more way of changing value if you want to only increase x you can
// /// x = x+5;
// /// or
// /// x+=5;
// /// both means the same
// /// but if you want increment only by one you can do
// /// x++;
// /// Take moment to play with it.
// /// you can do same with other math operations.
// /// </summary>
// [Test]
// public void Int_Increments()
// {
// int example = 5;
// example += 10;
// //example is 15
// example++;
// //example is 16 know;
// Assert.AreEqual(example, 16);
// }
// /// <summary>
// /// bool is the most straightforward and most useful it can only accept true and false.
// /// We will talk more about it later, for now, create two bools:
// /// truth and notTruth.
// /// Assign to them true and false.
// /// Try to assign number 6 to them.
// /// </summary>
// public void Bool()
// {
// Assert.True(truth);
// Assert.True(notTruth);
// }
// /// <summary>
// /// There are many ways to store real numbers
// /// Float, Double and Decimal.
// /// Decimal is most accurate but most expensive that why is is usual used for financial data.
// /// Float, Double are faster but not always accurate. Ask your teacher for more details.
// /// repeat operations add, subtract, divide, and multiply for double
// /// </summary>
// public void float_double_decimal()
// {
// decimal exampleDecimal = new decimal(10.5);
//
// double X = 140000000000000000000000000.001;
// double Y = 0.0000000000000000000000000008;
//
// }
// /// <summary>
// /// Extra exercise
// /// create a variable of each data type, and DOT assign any value!;
// /// Display them - you can do it Console.WriteLine(yourVariable);
// /// Try to explain what happened.
// /// </summary>
// public void Default_Values()
// {
//
// }
//Additonal read:
// There are more types we didn't cover but it is worth knowing about
}
}
| 44.013793 | 126 | 0.459417 | [
"MIT"
] | mar115115/koszalinCsharp | CSharp_Basics/CSharp_Basics/DataTypesAndVariables.cs | 6,384 | C# |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.AutomatonymousIntegration.Tests
{
using System;
using System.Threading.Tasks;
using Automatonymous;
using GreenPipes;
using NUnit.Framework;
using Saga;
using TestFramework;
using Testing;
[TestFixture]
public class Correlation_a_state_machine_by_guid :
StateMachineTestFixture
{
InMemorySagaRepository<TransactionState> _repository;
TransactionStateMachine _machine;
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
base.ConfigureInMemoryReceiveEndpoint(configurator);
_repository = new InMemorySagaRepository<TransactionState>();
_machine = new TransactionStateMachine();
configurator.StateMachineSaga(_machine, _repository, x =>
{
x.Message<BeginTransaction>(m => m.UsePartitioner(4, p => p.Message.TransactionId));
});
}
class TransactionState :
SagaStateMachineInstance
{
public State CurrentState { get; set; }
public Guid TransactionId { get; set; }
public Guid CorrelationId { get; set; }
}
class TransactionStateMachine :
MassTransitStateMachine<TransactionState>
{
public TransactionStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => Begin, x =>
{
x.CorrelateById(state => state.TransactionId, context => context.Message.TransactionId);
x.SelectId(context => context.Message.TransactionId);
x.InsertOnInitial = true;
x.SetSagaFactory(context => new TransactionState
{
CorrelationId = context.Message.TransactionId,
TransactionId = context.Message.TransactionId
});
});
Event(() => Commit, x =>
{
x.CorrelateById(state => state.TransactionId, context => context.Message.TransactionId);
x.SelectId(context => context.Message.TransactionId);
});
Initially(
When(Begin)
.TransitionTo(Active));
During(Active,
When(Commit)
.Finalize());
}
public State Active { get; private set; }
public Event<BeginTransaction> Begin { get; private set; }
public Event<CommitTransaction> Commit { get; private set; }
}
public interface BeginTransaction
{
Guid TransactionId { get; }
}
public interface CommitTransaction
{
Guid TransactionId { get; }
}
[Test]
public async Task Should_properly_map_to_the_instance()
{
Guid id = NewId.NextGuid();
await Bus.Publish<BeginTransaction>(new
{
TransactionId = id
});
Guid? saga = await _repository.ShouldContainSaga(state => state.TransactionId == id && state.CurrentState == _machine.Active, TestTimeout);
Assert.IsTrue(saga.HasValue);
await Bus.Publish<CommitTransaction>(new
{
TransactionId = id
});
saga = await _repository.ShouldContainSaga(state => state.TransactionId == id && state.CurrentState == _machine.Final, TestTimeout);
Assert.IsTrue(saga.HasValue);
}
}
} | 34.10687 | 152 | 0.56513 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit.AutomatonymousIntegration.Tests/CorrelateGuid_Specs.cs | 4,470 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
// ReSharper disable ConvertPropertyToExpressionBody
namespace Ccr.Dnc.Data.EntityFramework.Infrastucture
{
public class Repository<
TEntity,
TKey,
TContext>
: IRepository<TEntity>,
IRepository<TEntity, TKey>
where TEntity
: class
where TKey
: IComparable
where TContext
: DbContext
{
protected readonly TContext _context;
private DbSet<TEntity> _dbSet;
protected virtual DbSet<TEntity> DBSet
{
get => _dbSet
?? (_dbSet = _context.Set<TEntity>());
}
private Func<TEntity, TKey> _primaryKeyFunc;
protected Func<TEntity, TKey> PrimaryKeyFunc
{
get => _primaryKeyFunc
?? (_primaryKeyFunc = PrimaryKeyExpression.Compile());
}
private readonly EntityPrimaryKeyResolver<TEntity, TKey, TContext> _primaryKeyResolver;
private Expression<Func<TEntity, TKey>> _primaryKeyExpression;
public virtual Expression<Func<TEntity, TKey>> PrimaryKeyExpression
{
get
{
if (_primaryKeyExpression != null)
return _primaryKeyExpression;
return _primaryKeyExpression = _primaryKeyResolver
.PrimaryKeyGetterExpression;
}
}
private Expression<Func<TEntity, IComparable>> _primaryKeyExpressionBase;
public Expression<Func<TEntity, IComparable>> PrimaryKeyExpressionBase
{
get
{
throw new Exception();
//if (_primaryKeyExpressionBase != null)
// return _primaryKeyExpressionBase;
// return _primaryKeyExpressionBase = _primaryKeyResolver.CreatePrimaryKeyExpressionPredicateBase();
// //.PrimaryKeyExpressionBase;
}
}
public TEntity Fetch(
TKey primaryKey)
{
var entity = FetchOrDefault(primaryKey);
if (entity == null)
throw new KeyNotFoundException();
return entity;
}
public TEntity FetchOrDefault(TKey primaryKey)
{
return DBSet.Find(primaryKey);
}
public IList<object> DeleteRelatedEntries(
TEntity entity,
TKey[] keyListOfIgnoreEntites)
{
throw new NotImplementedException();
/*var deletedEntities = new List<object>();
foreach (var relatedEntity in resolveRelatedEntityObjects(entity))
{
var relatedTEntity = relatedEntity as TEntity;
if (relatedTEntity != null)
{
var keyValue = PrimaryKeyFunc(relatedTEntity);
if (keyListOfIgnoreEntites.Contains(keyValue))
continue;
var removedEntity = _DBSet.Remove(relatedTEntity);
deletedEntities.Add(removedEntity);
}
else
{
var propertyInfo = relatedEntity.GetType().GetProperty(_primaryKeyResolver.PropertyInfo.Name);
if (null != propertyInfo)
{
var value = propertyInfo.GetValue(relatedEntity, null).As<TKey>();
if (keyListOfIgnoreEntites.Contains(value))
continue;
var _currentDBSet = _context
.Reflect()
.InvokeMethodGeneric<object>(
MemberDescriptor.Any,
"Set",
new[] { relatedEntity.GetType() },
new object[] { });
var removedEntity = _currentDBSet
.Reflect()
.InvokeMethod<object>(
MemberDescriptor.Any,
"Remove",
relatedEntity);
deletedEntities.Add(removedEntity);
}
}
}
return deletedEntities;*/
}
public Repository(
TContext context)
{
_context = context;
_primaryKeyResolver = new EntityPrimaryKeyResolver<
TEntity,
TKey,
TContext>(
context);
}
public int Count()
{
return DBSet
.Count();
}
public void Insert(
TEntity entity)
{
DBSet
.Add(
entity);
}
public void InsertOrAttach(
TEntity entity)
{
}
public void AddOrUpdate(
TEntity entity)
{
var primaryKeyValue = _primaryKeyFunc(entity);
var equalityExpression = _primaryKeyResolver
.CreatePrimaryKeyExpressionPredicate(primaryKeyValue);
var existingEntity = DBSet.FirstOrDefault(
equalityExpression);
if (existingEntity == default(TEntity))
{
_context.Add(entity);
}
else
{
var x = _context.Update(existingEntity);
}
}
public void InsertAll(
IEnumerable<TEntity> entities)
{
DBSet.AddRange(
entities);
}
public void DeleteAll(
IEnumerable<TEntity> entities)
{
DBSet.RemoveRange(
entities);
}
public void Delete(
TEntity entity)
{
DBSet.Remove(
entity);
}
public IList<object> DeleteRelatedEntriesBase(
TEntity entity,
IComparable[] keyListOfIgnoreEntites)
{
return DeleteRelatedEntries(
entity,
keyListOfIgnoreEntites
.Cast<TKey>()
.ToArray());
}
public IList<TResult> Select<TResult>(
Expression<Func<TEntity, TResult>> selector)
{
return DBSet
.Select(
selector)
.ToList();
}
public IList<TEntity> FetchAll()
{
return DBSet
.ToList();
}
public IList<TEntity> FetchWhere(
Expression<Func<TEntity, bool>> predicate)
{
return DBSet
.Where(
predicate)
.ToList();
}
public TEntity FetchSingle(
Expression<Func<TEntity, bool>> predicate)
{
return DBSet
.Single(
predicate);
}
public TEntity FetchSingleOrDefault(
Expression<Func<TEntity, bool>> predicate)
{
return DBSet
.SingleOrDefault(
predicate);
}
//private static IEnumerable<EntityObject> resolveRelatedEntityObjects(TEntity entity)
//{
// return entity.As<IEntityWithRelationships>()
// .RelationshipManager.GetAllRelatedEnds()
// .SelectMany(t => t.CreateSourceQuery().OfType<EntityObject>())
// .Distinct()
// .ToArray();
//}
}
}
| 22.328467 | 108 | 0.61981 | [
"MIT"
] | vreniose95/Ccr | Ccr.Dnc.Data.EntityFramework/Dnc/Data/EntityFramework/Infrastucture/Repository.cs | 6,120 | C# |
/* Camera Follow C# Script (version: 1.5)
SPACE for UNITY - Space Scene Construction Kit
https://www.imphenzia.com/space-for-unity
(c) 2017 Imphenzia AB
DESCRIPTION:
Smooth camera follow script used to follow an object (Transform)
INSTRUCTIONS:
Attach this script to a camera (e.g. Main Camera) and specify which target Transform to
follow.
You can also modify parameters such as:
updateMode (to reduce camera jitter - camera can be updated in FixedUpdate, Update, or LateUpdate)
followMode (whether camera should chase behind Transform or as a spectator that follows the Transform)
distance (minimum distance to target)
chaseHeight (height over target in chase mode)
followDamping (smoothness of movement, lower value is smoother)
lookAtDamping (smoothness for rotation, lower value is smoother)
freezeKey (freeze camera movement while this key is pressed)
Version History
1.5 - Added ORBIT follow mode
1.02 - Renamed to SU_CameraFollow to avoid naming conflicts.
1.01 - Initial Release.
*/
using UnityEngine;
using System.Collections;
public class SU_CameraFollow : MonoBehaviour
{
// Using UpdateMode you can select when the camera should be updated
// Depending on your design camera jitter may occur which may be reduced if you change
// the update mode. In the included demo the best result is achieved when camera is
// updated in the FixedUpdate() function.
public enum UpdateMode { FIXED_UPDATE, UPDATE, LATE_UPDATE }
public UpdateMode updateMode = UpdateMode.FIXED_UPDATE;
// Select the chase mode (chase behind target or moving spectator)
// CHASE = smooth chase behind target at distance and height
// SPECTATOR = smooth look at target from a chasing spectator position
public enum FollowMode { CHASE, SPECTATOR, ORBIT }
public FollowMode followMode = FollowMode.SPECTATOR;
// Target to follow
public Transform target;
// Distance to follow from (this is the minimum distance,
// depending on damping the distance will increase at speed)
public float distance = 60.0f;
// Height for chase mode camera
public float chaseHeight = 15.0f;
// Follow (movement) damping. Lower value = smoother
public float followDamping = 0.3f;
// Look at (rotational) damping. Lower value = smoother
public float lookAtDamping = 4.0f;
// Optional hotkey for freezing camera movement
public KeyCode freezeKey = KeyCode.None;
private Vector2 _orbitPosition = new Vector2();
public float orbitDistance = 50.0f;
public Vector2 orbitSpeed = new Vector2(70.0f, 70.0f);
public float orbitDistanceMin = 20f;
public float orbitDistanceMax = 200.0f;
private Transform _cacheTransform;
void Start()
{
// Cache reference to transform to increase performance
_cacheTransform = transform;
if (followMode == FollowMode.ORBIT)
{
_orbitPosition = new Vector2(transform.eulerAngles.y, transform.eulerAngles.x);
}
}
void FixedUpdate()
{
if (updateMode == UpdateMode.FIXED_UPDATE) DoCamera();
}
void Update()
{
if (updateMode == UpdateMode.UPDATE) DoCamera();
}
void LateUpdate()
{
if (updateMode == UpdateMode.LATE_UPDATE) DoCamera();
}
void DoCamera()
{
// Return if no target is set
if (target == null) return;
Quaternion _lookAt;
switch (followMode)
{
case FollowMode.SPECTATOR:
// Smooth lookat interpolation
_lookAt = Quaternion.LookRotation(target.position - _cacheTransform.position);
_cacheTransform.rotation = Quaternion.Lerp(_cacheTransform.rotation, _lookAt, Time.deltaTime * lookAtDamping);
// Smooth follow interpolation
if (!Input.GetKey(freezeKey))
{
if (Vector3.Distance(_cacheTransform.position, target.position) > distance)
{
_cacheTransform.position = Vector3.Lerp(_cacheTransform.position, target.position, Time.deltaTime * followDamping);
}
}
break;
case FollowMode.CHASE:
if (!Input.GetKey(freezeKey))
{
// Smooth lookat interpolation
_lookAt = target.rotation;
_cacheTransform.rotation = Quaternion.Lerp(_cacheTransform.rotation, _lookAt, Time.deltaTime * lookAtDamping);
// Smooth follow interpolation
_cacheTransform.position = Vector3.Lerp(_cacheTransform.position, target.position - target.forward * distance + target.up * chaseHeight, Time.deltaTime * followDamping * 10);
}
break;
case FollowMode.ORBIT:
if (!Input.GetKey(freezeKey))
{
// Smooth lookat interpolation
_orbitPosition.x += Input.GetAxis("Mouse X") * orbitSpeed.x * distance * 0.002f;
_orbitPosition.y -= Input.GetAxis("Mouse Y") * orbitSpeed.y * 0.2f;
_orbitPosition.y = Mathf.Clamp(_orbitPosition.y, -80.0f, 80.0f);
Quaternion _rot = Quaternion.Euler(_orbitPosition.y, _orbitPosition.x, 0);
orbitDistance = Mathf.Clamp(orbitDistance - Input.GetAxis("Mouse ScrollWheel") * 200, orbitDistanceMin, orbitDistanceMax);
transform.rotation = _rot;
transform.position = (_rot * new Vector3(0, 0, -orbitDistance)) + target.position;
}
break;
}
}
}
| 40.265734 | 194 | 0.638069 | [
"MIT"
] | Tsuihao/Reinforcement-Learning-unity-ml-agents-spacecraft-docking-2D | Materials/Space/_Demo/Scrips/SU_CameraFollow.cs | 5,758 | C# |
#region Usings
using System;
using Xunit;
#endregion
namespace Extend.Testing
{
public partial class ArrayExTest
{
[Fact]
public void GenericClearAllTest()
{
var array = new[]
{
"test",
"test"
};
array.ClearAll();
Assert.Null( array[0] );
Assert.Null( array[1] );
}
[Fact]
public void GenericClearAllTest1()
{
String[] array = null;
// ReSharper disable once AssignNullToNotNullAttribute
Action test = () => array.ClearAll();
Assert.Throws<ArgumentNullException>( test );
}
}
} | 20.75 | 67 | 0.464525 | [
"MIT"
] | DaveSenn/Extend | .Src/Extend.Testing/System.Array/System.Array.Generic/Array.Generic.ClearAll.Test.cs | 714 | C# |
using SixLabors.ImageSharp.Formats;
namespace R8.FileHandlers
{
/// <summary>
/// An <see cref="IMyFileConfigurationImageBase"/> interface.
/// </summary>
public interface IMyFileConfigurationImageBase : IMyFileRuntime
{
/// <summary>
/// Gets or sets An <see cref="IImageEncoder"/> interface that representing Encoder for saving images. If left null, will be set to <c>JpegEncoder</c>
/// </summary>
IImageEncoder ImageEncoder { get; set; }
/// <summary>
/// Gets or sets and <see cref="int"/> that representing image max size. Leave it <c>null</c>, if no need to resize image.
/// </summary>
int? ResizeToSize { get; set; }
/// <summary>
/// Gets or sets an <see cref="string"/> value that representing a watermark image url.
/// </summary>
string? WatermarkPath { get; set; }
}
} | 36.24 | 158 | 0.611479 | [
"MIT"
] | arashaan/R8 | src/R8.FileHandlers/IMyFileConfigurationImageBase.cs | 908 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace OnceBuild {
public class SluaAdapter : MonoBehaviour {
public static SluaAdapter Instance = null;
public object DoString(string str) {
return null;
}
}
}
namespace SLua{
public class LuaFunction {
public object call(params object[] args) {
return null;
}
}
} | 22.75 | 51 | 0.595604 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | yangfawen/RAVVAR-XunAPI | Assets/RAVVAR/XunAPI/script/SluaAdapter.cs | 457 | C# |
namespace P07_SecretChat
{
using System;
using System.Linq;
public class StartUp
{
const string COMMAND_TO_STOP = "Reveal";
const string RESULT_MESSAGE = "You have a new text message: {0}";
public static void Main()
{
string input = Console.ReadLine();
while (true)
{
string[] arg = Console.ReadLine()
.Split(":|:", StringSplitOptions.RemoveEmptyEntries);
bool isStopCommand = arg[0] == COMMAND_TO_STOP;
if (isStopCommand)
{
PrintResult(input);
break;
}
string command = arg[0];
string substring = string.Empty;
switch (command)
{
case "InsertSpace":
int index = int.Parse(arg[1]);
input = InsertSpace(input, index);
break;
case "Reverse":
substring = arg[1];
input = Reverse(input, substring);
break;
case "ChangeAll":
substring = arg[1];
string replacement = arg[2];
input = ChangeAll(input, substring, replacement);
break;
}
}
}
private static string InsertSpace(string input, int index)
{
input = input.Insert(index, " ");
PrintStringAfterOperation(input);
return input;
}
private static string Reverse(string input, string substring)
{
string reversedSubstringAsString = string.Empty;
bool isSubstringExist = input.Contains(substring);
if (isSubstringExist)
{
int index = input.IndexOf(substring);
input = input.Remove(index, substring.Length);
char[] reversedSubstring = substring.Reverse().ToArray();
for (int i = 0; i < reversedSubstring.Length; i++)
{
reversedSubstringAsString += reversedSubstring[i];
}
input += reversedSubstringAsString;
PrintStringAfterOperation(input);
}
else
{
Console.WriteLine("error");
}
return input;
}
private static string ChangeAll(string input, string substring, string replacement)
{
int index = input.IndexOf(substring);
while (index != -1)
{
input = input.Replace(substring, replacement);
index = input.IndexOf(substring);
}
PrintStringAfterOperation(input);
return input;
}
private static void PrintStringAfterOperation(string str)
{
Console.WriteLine(str);
}
private static void PrintResult(string str)
{
Console.WriteLine(string.Format(RESULT_MESSAGE, str));
}
}
}
| 29.486239 | 91 | 0.472931 | [
"MIT"
] | Statev7/SoftUni | C01_C#ProgrammingFundamentals-May-2021/P24_Exam-Exercise/P07_SecretChat/StartUp.cs | 3,216 | C# |
using Microsoft.AspNetCore.Mvc;
namespace _2.ChapterTwo2._9.Controllers
{
[ApiController]
[Route("[controller]")]
public class CustomerController : Controller
{
[HttpGet]
public string GetName()
{
return "Customer name";
}
}
}
| 19.25 | 49 | 0.561688 | [
"MIT"
] | bpbpublications/Implementing-Design-Patterns-in-C-and-.NET-5 | Chapter 02/2.ChapterTwo2.9/Controllers/CustomerController.cs | 310 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using RoseByte.SharpFiles.CopyFileEx;
using RoseByte.SharpFiles.Extensions;
namespace RoseByte.SharpFiles.Internal
{
public class File : FsFile
{
public override string Name => System.IO.Path.GetFileName(Path);
public override string NameWithoutExtension => System.IO.Path.GetFileNameWithoutExtension(Path);
private string _content;
public override string Content => _content ?? (_content = System.IO.File.ReadAllText(Path));
private byte[] _hash;
public override byte[] Hash
{
get => _hash ?? (_hash = SHA256.Create().ComputeHash(System.IO.File.ReadAllBytes(Path)));
}
protected override long GetSize() => new FileInfo(Path).Length;
internal File(string value) : base(value) { }
private void PrepareCopy(FsFile target)
{
target.Parent.Create();
if (target.Exists && (System.IO.File.GetAttributes(target) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
System.IO.File.SetAttributes(target, FileAttributes.Normal);
};
}
public override Encoding Encoding
{
get
{
// Read the BOM
var bom = new byte[4];
using (var file = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
file.Read(bom, 0, 4);
}
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
return Encoding.ASCII;
}
}
public override bool HasEncoding(Encoding encoding) => Equals(Encoding, encoding);
public override void Copy(FsFile target)
{
try
{
PrepareCopy(target);
System.IO.File.Copy(Path, target, true);
}
catch (Exception exception)
{
InspectException(exception, false);
throw new Exception($"File '{Path}' could not be copied to '{target}': {exception.Message}");
}
}
public override void Copy(FsFile target, Action<long, long> progress)
{
try
{
PrepareCopy(target);
new FileEx(progress).Copy(this, target);
}
catch (Exception exception)
{
InspectException(exception, true);
throw new Exception($"File '{Path}' could not be copied to '{target}': {exception.Message}");
}
}
public override void Copy(FsFile target, Action<int> progress)
{
try
{
void Adapter(long x, long y) => progress((int) (100 * y / Size));
PrepareCopy(target);
new FileEx(Adapter).Copy(this, target);
}
catch (Exception exception)
{
InspectException(exception, true);
throw new Exception($"File '{Path}' could not be copied to '{target}': {exception.Message}");
}
}
public override void Remove()
{
if (!Exists)
{
return;
}
try
{
if ((System.IO.File.GetAttributes(Path) & FileAttributes.ReadOnly) != 0)
{
System.IO.File.SetAttributes(Path, FileAttributes.Normal);
};
System.IO.File.Delete(Path);
}
catch (Exception exception)
{
InspectException(exception, false);
throw new Exception($"File '{Path}' could not be deleted: {exception.Message}");
}
}
private void InspectException(Exception exception, bool inspectHandlers)
{
if (!inspectHandlers && exception.HResult != -2147024891)
{
return;
}
var handlers = new List<string>();
try
{
handlers.AddRange(FileUtil.WhoIsLocking(Path).Select(x => $"{x.ProcessName} ({x.Id})"));
}
catch (Exception e)
{
try
{
handlers.AddRange(GetHandler().Select(x => $"{x.Value} ({x.Key})"));
}
catch
{
return;
}
}
if (!handlers.Any())
{
return;
}
throw new Exception($"File '{Path}' is locked by: {string.Join(", ", handlers)}");
}
private Dictionary<int, string> GetHandler(bool kill = false)
{
var hndl = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
hndl += "\\Helpers\\Handle.exe";
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = hndl,
Arguments = Path + " /accepteula",
CreateNoWindow = true
}
};
p.Start();
var output = p.StandardOutput.ReadToEnd().Split('\n');
var result = new Dictionary<int, string>();
var rgxPid = new Regex("^(.+?)\\spid: (\\d+)");
p.WaitForExit();
for (var i = 5; i < output.Length; i++)
{
var matches = rgxPid.Match(output[i]);
if (matches.Success)
{
result.Add(int.Parse(matches.Groups[2].Value), matches.Groups[1].Value);
}
}
return result;
}
public override FsFolder Parent => System.IO.Path.GetDirectoryName(Path).ToFolder();
public override bool Exists => System.IO.File.Exists(Path);
public override void Write(string content)
{
try
{
PrepareCopy(this);
System.IO.File.WriteAllText(Path, content, Encoding.UTF8);
}
catch (Exception exception)
{
InspectException(exception, false);
throw new Exception($"Cannot write to '{Path}': {exception.Message}");
}
}
}
}
| 32.954545 | 125 | 0.482759 | [
"MIT"
] | mgottvald/SharpFilePath | SharpFilePath/Internal/File.cs | 7,252 | C# |
using System;
using System.Threading.Tasks.Dataflow;
using Xunit;
namespace Example
{
public class Examples
{
[Fact]
public void TestLinkToAssert()
{
var t1 = new TransformBlock<int, int>(x => x + 2);
var t2 = new TransformBlock<int, int>(x => x * 2);
var log = new TransformBlock<int, int>(x => { Console.WriteLine($"TransformBlock has {x}"); return x; });
var test = new ActionBlock<int>(x => Assert.Equal((8 + 2) * 2, x));
var options = new DataflowLinkOptions { PropagateCompletion = true };
t1.LinkTo(t2, options);
t2.LinkTo(log, options);
log.LinkTo(test, options);
t1.Post(8);
t1.Complete();
test.Completion.Wait();
}
[Fact]
public void TestBoundedCapacity()
{
var t1 = new TransformBlock<int, int>(x => x + 2);
var t2 = new TransformBlock<int, string>(x => (x * 2).ToString());
var b = new BufferBlock<string>(new DataflowBlockOptions { BoundedCapacity = 1 });
var log = new TransformBlock<string, string>(x => { Console.WriteLine($"TransformBlock has {x}"); return x; });
var test = new ActionBlock<string>(x => Assert.Equal("8", x));
var options = new DataflowLinkOptions { PropagateCompletion = true };
t1.LinkTo(t2, options);
t2.LinkTo(b, options);
b.LinkTo(log, options);
log.LinkTo(test, options);
t1.Post(2);
t1.Complete();
test.Completion.Wait();
}
[Fact]
public void TestDegreeOfParallelism()
{
var t1 = new TransformBlock<int, int>(x => x * 4);
var t2 = new TransformBlock<int, string>(
x => $"Hello number {x}",
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded }
);
var log = new TransformBlock<string, string>(x => { Console.WriteLine($"TransformBlock has {x}"); return x; });
var test = new ActionBlock<string>(x => Assert.Equal("Hello number 8", x));
var options = new DataflowLinkOptions { PropagateCompletion = true };
t1.LinkTo(t2, options);
t2.LinkTo(log, options);
log.LinkTo(test, options);
t1.Post(2);
t1.Complete();
test.Completion.Wait();
}
}
}
| 35.564103 | 124 | 0.487743 | [
"Apache-2.0"
] | MikeMKH/concurrency-in-csharp-cookbook | ch05/Example/Examples.cs | 2,774 | C# |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// 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.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework.Api;
namespace NUnit.Framework.Internal.Commands
{
/// <summary>
/// TODO: Documentation needed for class
/// </summary>
public class ExpectedExceptionCommand : DelegatingTestCommand
{
private ExpectedExceptionData exceptionData;
/// <summary>
/// Initializes a new instance of the <see cref="ExpectedExceptionCommand"/> class.
/// </summary>
/// <param name="innerCommand">The inner command.</param>
/// <param name="exceptionData">The exception data.</param>
public ExpectedExceptionCommand(TestCommand innerCommand, ExpectedExceptionData exceptionData)
: base(innerCommand)
{
this.exceptionData = exceptionData;
}
/// <summary>
/// Runs the test, saving a TestResult in the supplied TestExecutionContext
/// </summary>
/// <param name="context">The context in which the test is to be run.</param>
/// <returns>A TestResult</returns>
public override TestResult Execute(TestExecutionContext context)
{
try
{
context.CurrentResult = innerCommand.Execute(context);
if (context.CurrentResult.ResultState == ResultState.Success)
ProcessNoException(context);
}
catch (Exception ex)
{
#if !NETCF && !SILVERLIGHT
if (ex is ThreadAbortException)
Thread.ResetAbort();
#endif
ProcessException(ex, context);
}
return context.CurrentResult;
}
/// <summary>
/// Handles processing when no exception was thrown.
/// </summary>
/// <param name="context">The execution context.</param>
public void ProcessNoException(TestExecutionContext context)
{
context.CurrentResult.SetResult(ResultState.Failure, NoExceptionMessage());
}
/// <summary>
/// Handles processing when an exception was thrown.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="context">The execution context.</param>
public void ProcessException(Exception exception, TestExecutionContext context)
{
if (exception is NUnitException)
exception = exception.InnerException;
if (IsExpectedExceptionType(exception))
{
if (IsExpectedMessageMatch(exception))
{
MethodInfo exceptionMethod = exceptionData.GetExceptionHandler(context.TestObject.GetType());
if (exceptionMethod != null)
{
Reflect.InvokeMethod(exceptionMethod, context.TestObject, exception);
}
else
{
IExpectException handler = context.TestObject as IExpectException;
if (handler != null)
handler.HandleException(exception);
}
context.CurrentResult.SetResult(ResultState.Success);
}
else
{
context.CurrentResult.SetResult(ResultState.Failure, WrongTextMessage(exception), GetStackTrace(exception));
}
}
else
{
context.CurrentResult.RecordException(exception);
// If it shows as an error, change it to a failure due to the wrong type
if (context.CurrentResult.ResultState == ResultState.Error)
context.CurrentResult.SetResult(ResultState.Failure, WrongTypeMessage(exception), GetStackTrace(exception));
}
}
#region Helper Methods
private bool IsExpectedExceptionType(Exception exception)
{
return exceptionData.ExpectedExceptionName == null ||
exceptionData.ExpectedExceptionName.Equals(exception.GetType().FullName);
}
private bool IsExpectedMessageMatch(Exception exception)
{
if (exceptionData.ExpectedMessage == null)
return true;
switch (exceptionData.MatchType)
{
case MessageMatch.Exact:
default:
return exceptionData.ExpectedMessage.Equals(exception.Message);
case MessageMatch.Contains:
return exception.Message.IndexOf(exceptionData.ExpectedMessage) >= 0;
case MessageMatch.Regex:
return Regex.IsMatch(exception.Message, exceptionData.ExpectedMessage);
case MessageMatch.StartsWith:
return exception.Message.StartsWith(exceptionData.ExpectedMessage);
}
}
private string NoExceptionMessage()
{
string expectedType = exceptionData.ExpectedExceptionName == null ? "An Exception" : exceptionData.ExpectedExceptionName;
return CombineWithUserMessage(expectedType + " was expected");
}
private string WrongTypeMessage(Exception exception)
{
return CombineWithUserMessage(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: " + exceptionData.ExpectedExceptionName + Env.NewLine +
" but was: " + exception.GetType().FullName + " : " + exception.Message);
}
private string WrongTextMessage(Exception exception)
{
string expectedText;
switch (exceptionData.MatchType)
{
default:
case MessageMatch.Exact:
expectedText = "Expected: ";
break;
case MessageMatch.Contains:
expectedText = "Expected message containing: ";
break;
case MessageMatch.Regex:
expectedText = "Expected message matching: ";
break;
case MessageMatch.StartsWith:
expectedText = "Expected message starting: ";
break;
}
return CombineWithUserMessage(
"The exception message text was incorrect" + Env.NewLine +
expectedText + exceptionData.ExpectedMessage + Env.NewLine +
" but was: " + exception.Message);
}
private string CombineWithUserMessage(string message)
{
if (exceptionData.UserMessage == null)
return message;
return exceptionData.UserMessage + Env.NewLine + message;
}
private string GetStackTrace(Exception exception)
{
try
{
return exception.StackTrace;
}
catch (Exception)
{
return "No stack trace available";
}
}
#endregion
}
} | 38.884793 | 133 | 0.57881 | [
"MIT"
] | KirillOsenkov/guiunit | src/framework/Internal/Commands/ExpectedExceptionCommand.cs | 8,440 | C# |
using System;
using Server;
using Server.Network;
namespace Server.Items
{
public class UnderworldSwitchWE : BaseSwitch
{
[Constructable]
public UnderworldSwitchWE() : base( 0x1091, 0x1092, 1042901, 1042900, true )
{
//1042901 = You hear a deep rumbling as something seems to happen.
//1042900 = There seems to be no further effect right now.
//true = It do something, it is not useless or broken switch.
}
public override void DoSomethingSpecial( Mobile from )
{
foreach ( Item item in GetItemsInRange( 8 ) )
{
if ( item.ItemID == 0x3660 && item.Hue == 1000 ) //Dark Globe of Sosaria
{
Timer m_timerA = new MoveTimer( item, 1 );
m_timerA.Start();
}
}
}
private class MoveTimer : Timer
{
private Item item;
private int num;
private int m_Stage;
private int m_Cicle;
public MoveTimer( Item sphere, int coord ) : base( TimeSpan.FromSeconds( 0.0 ), TimeSpan.FromSeconds( 1.5 ) )
{
item = sphere;
num = coord;
}
protected override void OnTick()
{
if ( item.Deleted )
{
Stop();
return;
}
m_Stage++;
if ( m_Cicle == 0 )
item.Z += 1;
else if ( m_Cicle == 1 )
item.Z += 0;
else
item.Z += -1;
if ( m_Stage == 8 )
m_Cicle++;
else if ( m_Stage == 14 )
m_Cicle++;
else if ( m_Stage == 22 )
Stop();
}
}
public UnderworldSwitchWE( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 20.116279 | 112 | 0.606936 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Customs/Nerun's Distro/SA/Items/Construction/Switches.cs | 1,730 | 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("ManagedUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ManagedUI")]
[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("fa2b3204-560c-48f8-8a9c-da91c48bc20d")]
// 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.567568 | 85 | 0.725298 | [
"MIT"
] | GiovanniDicanio/SafeArraySamples | SafeArraySamples/ManagedUI/Properties/AssemblyInfo.cs | 1,430 | C# |
using System;
using Events;
using Game_Scripts.Monster;
using Game_Scripts.Monster.State_Machine;
using UnityEngine;
namespace Player.Player_Collisions{
public class DoorCollision : BaseCollision{
private int _numberOfKeysNeeded;
private AudioSource _audioSource;
[SerializeField] private AudioClip[] _audioClipsArray;
private void Start() {
var keysGameObjsArray = GameObject.FindGameObjectsWithTag("Key");
_numberOfKeysNeeded = keysGameObjsArray.Length;
_audioSource = GetComponent<AudioSource>();
print($"Precisa de {_numberOfKeysNeeded} chaves");
}
protected override void defaultMethod(Collision2D other) {
if (PlayerKeyInventory.KeyCount >= _numberOfKeysNeeded && !_audioSource.isPlaying) {
_audioSource.clip = _audioClipsArray[0];
_audioSource.Play();
EventManager.InvokeOnGameWin();
var monsterStatemachine = MonsterSingleton.Instance.GetComponent<MonsterStateMachineManager>();
monsterStatemachine.ChangeCurrentState(monsterStatemachine.NullState);
}
else if(!_audioSource.isPlaying) {
_audioSource.clip = _audioClipsArray[1];
_audioSource.Play();
}
}
}
} | 31.409091 | 111 | 0.636035 | [
"MIT"
] | Lucasdvs10/Dark-House | Dark_House_GameDev/Assets/Scripts/Game_Scripts/Player/Player_Collisions/DoorCollision.cs | 1,384 | C# |
namespace MyRecipes.Data.Repositories
{
using System;
using System.Linq;
using MyRecipes.Data.Common.Models;
using MyRecipes.Data.Common.Repositories;
using Microsoft.EntityFrameworkCore;
public class EfDeletableEntityRepository<TEntity> : EfRepository<TEntity>, IDeletableEntityRepository<TEntity>
where TEntity : class, IDeletableEntity
{
public EfDeletableEntityRepository(ApplicationDbContext context)
: base(context)
{
}
public override IQueryable<TEntity> All() => base.All().Where(x => !x.IsDeleted);
public override IQueryable<TEntity> AllAsNoTracking() => base.AllAsNoTracking().Where(x => !x.IsDeleted);
public IQueryable<TEntity> AllWithDeleted() => base.All().IgnoreQueryFilters();
public IQueryable<TEntity> AllAsNoTrackingWithDeleted() => base.AllAsNoTracking().IgnoreQueryFilters();
public void HardDelete(TEntity entity) => base.Delete(entity);
public void Undelete(TEntity entity)
{
entity.IsDeleted = false;
entity.DeletedOn = null;
this.Update(entity);
}
public override void Delete(TEntity entity)
{
entity.IsDeleted = true;
entity.DeletedOn = DateTime.UtcNow;
this.Update(entity);
}
}
}
| 30.795455 | 114 | 0.650923 | [
"MIT"
] | psp87/MyRecipes | Data/MyRecipes.Data/Repositories/EfDeletableEntityRepository.cs | 1,357 | C# |
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Threading;
using Moq;
using Nerdbank.Streams;
using Xunit;
using Xunit.Abstractions;
[Obsolete("Tests functionality that .NET now exposes directly through PipeReader.Create(Stream)")]
public class StreamUseStrictPipeReaderTests : StreamPipeReaderTestBase
{
public StreamUseStrictPipeReaderTests(ITestOutputHelper logger)
: base(logger)
{
}
[Fact]
public async Task StreamFails()
{
var expectedException = new InvalidOperationException();
var unreadableStream = new Mock<Stream>(MockBehavior.Strict);
unreadableStream.SetupGet(s => s.CanRead).Returns(true);
// Set up for either ReadAsync method to be called. We expect it will be Memory<T> on .NET Core 2.1 and byte[] on all the others.
#if SPAN_BUILTIN
unreadableStream.Setup(s => s.ReadAsync(It.IsAny<Memory<byte>>(), It.IsAny<CancellationToken>())).ThrowsAsync(expectedException);
#else
unreadableStream.Setup(s => s.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())).ThrowsAsync(expectedException);
#endif
PipeReader? reader = this.CreatePipeReader(unreadableStream.Object);
InvalidOperationException? actualException = await Assert.ThrowsAsync<InvalidOperationException>(() => reader.ReadAsync(this.TimeoutToken).AsTask());
Assert.Same(expectedException, actualException);
}
protected override PipeReader CreatePipeReader(Stream stream, int sizeHint = 0) => stream.UseStrictPipeReader(sizeHint);
}
| 40.106383 | 165 | 0.74695 | [
"MIT"
] | tmat/Nerdbank.Streams | test/Nerdbank.Streams.Tests/StreamUseStrictPipeReaderTests.cs | 1,887 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.EmployerCommitmentsV2.Web.Models.Apprentice;
using System.Threading;
using System.Threading.Tasks;
namespace SFA.DAS.EmployerCommitmentsV2.Web.UnitTests.Controllers.ApprenticeControllerTests
{
public class WhenRequestingConfirmEditApprenticeshipTests
{
private WhenRequestingConfirmEditApprenticeshipFixture _fixture;
[SetUp]
public void Arrange()
{
_fixture = new WhenRequestingConfirmEditApprenticeshipFixture();
}
[Test]
public async Task VerifyViewModelMapperIsCalled()
{
await _fixture.ConfirmEditApprenticeship();
_fixture.VerifyViewModelMapperIsCalled();
}
[Test]
public async Task VerifyViewIsReturned()
{
var result = await _fixture.ConfirmEditApprenticeship();
_fixture.VerifyViewResultIsReturned(result);
}
}
public class WhenRequestingConfirmEditApprenticeshipFixture : ApprenticeControllerTestFixtureBase
{
public WhenRequestingConfirmEditApprenticeshipFixture() : base ()
{
_controller.TempData = new TempDataDictionary( Mock.Of<HttpContext>(), Mock.Of<ITempDataProvider>());
}
public async Task<IActionResult> ConfirmEditApprenticeship()
{
return await _controller.ConfirmEditApprenticeship();
}
public void VerifyValidationApiIsCalled()
{
_mockCommitmentsApiClient.Verify(x => x.ValidateApprenticeshipForEdit(It.IsAny<ValidateApprenticeshipForEditRequest>(), CancellationToken.None), Times.Once());
}
internal void VerifyViewModelMapperIsCalled()
{
_mockMapper.Verify(x => x.Map<ConfirmEditApprenticeshipViewModel>(It.IsAny<EditApprenticeshipRequestViewModel>()), Times.Once());
}
internal void VerifyViewResultIsReturned(IActionResult result)
{
Assert.IsInstanceOf<ViewResult>(result);
}
}
}
| 33.378788 | 171 | 0.69133 | [
"MIT"
] | SkillsFundingAgency/das-employercommitments-v2 | src/SFA.DAS.EmployerCommitmentsV2.Web.UnitTests/Controllers/ApprenticeControllerTests/WhenRequestingConfirmEditApprenticeshipTests.cs | 2,205 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using WebApp.UI.Helpers;
using WebApp.UI.Models;
namespace WebApp.UI.Pages
{
public class ProductModel : PageModel
{
private ISessionManager _sessionManager;
public string ApiUrl { get; }
public ProductModel(ISessionManager sessionManager)
{
_sessionManager = sessionManager;
ApiUrl = ApiUrls.Rootlocal;
}
[BindProperty] public InputModel Input { get; set; }
public class InputModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Value { get; set; }
public bool IsInCart { get; set; }
public IEnumerable<ProductImage> ProductImages { get; set; }
}
public class ProductImage
{
public Guid ProductId { get; set; }
public string Name { get; set; }
public long Width { get; set; }
public string RelativePath { get; set; }
public string GlobalPath { get; set; }
public string Type { get; set; }
public string Extention { get; set; }
}
public async Task<IActionResult> OnGet(string name)
{
using var client = new HttpClient();
var updateProductsUri = new Uri(ApiUrls.Product.GetProductByName + "?name=" + name.Replace("-", " "));
var postTask = await client.GetAsync(updateProductsUri);
var result = postTask.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var data = JsonConvert.DeserializeObject<InputModel>(result);
Input = data;
var cartList = _sessionManager.GetCart(x => new InputModel
{
Name = x.Name,
Value = x.Value,
Id = x.ProductId,
});
foreach (var product in cartList)
{
if (cartList != null)
{
var productViewModels = cartList.ToList();
if (productViewModels.Any(x => x.Id == Input.Id))
{
product.IsInCart = true;
}
else
{
product.IsInCart = false;
}
}
}
if (data == null)
return RedirectToPage("Index");
else
return Page();
}
}
}
| 31.848837 | 114 | 0.525739 | [
"Apache-2.0"
] | dpk2789/aow-razor-pages | Solution1/WebApp.UI/Pages/Product.cshtml.cs | 2,739 | C# |
#pragma checksum "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "20c348eca9f15c3b05794d8d444f5dec93e18714"
// <auto-generated/>
#pragma warning disable 1591
namespace SimpleInvoiceManagementSoftware.Pages
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\_Imports.razor"
using SimpleInvoiceManagementSoftware.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using Radzen;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using Radzen.Blazor;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using SimpleInvoiceManagementSoftware.Models.SimpleInvoice;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using SimpleInvoiceManagementSoftware.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 11 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
[Authorize]
#line default
#line hidden
#nullable disable
[Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))]
[Microsoft.AspNetCore.Components.RouteAttribute("/application-users")]
public partial class ApplicationUsers : SimpleInvoiceManagementSoftware.Pages.ApplicationUsersComponent
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.OpenComponent<Radzen.Blazor.RadzenContent>(0);
__builder.AddAttribute(1, "Container", "main");
__builder.AddAttribute(2, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
__builder2.OpenComponent<Radzen.Blazor.RadzenHeading>(3);
__builder2.AddAttribute(4, "Size", "H1");
__builder2.AddAttribute(5, "Text", "Users");
__builder2.CloseComponent();
__builder2.AddMarkupContent(6, "\n ");
__builder2.OpenElement(7, "div");
__builder2.AddAttribute(8, "class", "row");
__builder2.OpenElement(9, "div");
__builder2.AddAttribute(10, "class", "col-md-12");
__builder2.OpenComponent<Radzen.Blazor.RadzenButton>(11);
__builder2.AddAttribute(12, "Icon", "add_circle_outline");
__builder2.AddAttribute(13, "style", "margin-bottom: 10px");
__builder2.AddAttribute(14, "Text", "Add");
__builder2.AddAttribute(15, "Click", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.MouseEventArgs>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 20 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
Button0Click
#line default
#line hidden
#nullable disable
)));
__builder2.CloseComponent();
__builder2.AddMarkupContent(16, "\n ");
__builder2.OpenComponent<Radzen.Blazor.RadzenGrid<ApplicationUser>>(17);
__builder2.AddAttribute(18, "AllowFiltering", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
true
#line default
#line hidden
#nullable disable
));
__builder2.AddAttribute(19, "AllowPaging", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
true
#line default
#line hidden
#nullable disable
));
__builder2.AddAttribute(20, "AllowSorting", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
true
#line default
#line hidden
#nullable disable
));
__builder2.AddAttribute(21, "Data", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<ApplicationUser>>(
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
users
#line default
#line hidden
#nullable disable
));
__builder2.AddAttribute(22, "RowSelect", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<ApplicationUser>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<ApplicationUser>(this,
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
Grid0RowSelect
#line default
#line hidden
#nullable disable
)));
__builder2.AddAttribute(23, "Columns", (Microsoft.AspNetCore.Components.RenderFragment)((__builder3) => {
__builder3.OpenComponent<Radzen.Blazor.RadzenGridColumn<ApplicationUser>>(24);
__builder3.AddAttribute(25, "Property", "UserName");
__builder3.AddAttribute(26, "Title", "User Name");
__builder3.CloseComponent();
__builder3.AddMarkupContent(27, "\n ");
__builder3.OpenComponent<Radzen.Blazor.RadzenGridColumn<ApplicationUser>>(28);
__builder3.AddAttribute(29, "Property", "Email");
__builder3.AddAttribute(30, "Title", "Email");
__builder3.CloseComponent();
__builder3.AddMarkupContent(31, "\n ");
__builder3.OpenComponent<Radzen.Blazor.RadzenGridColumn<ApplicationUser>>(32);
__builder3.AddAttribute(33, "Filterable", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 28 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
false
#line default
#line hidden
#nullable disable
));
__builder3.AddAttribute(34, "Sortable", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 28 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
false
#line default
#line hidden
#nullable disable
));
__builder3.AddAttribute(35, "Width", "70px");
__builder3.AddAttribute(36, "Template", (Microsoft.AspNetCore.Components.RenderFragment<ApplicationUser>)((applicationUser) => (__builder4) => {
__builder4.OpenComponent<Radzen.Blazor.RadzenButton>(37);
__builder4.AddAttribute(38, "ButtonStyle", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Radzen.ButtonStyle>(
#nullable restore
#line 30 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
ButtonStyle.Danger
#line default
#line hidden
#nullable disable
));
__builder4.AddAttribute(39, "Icon", "close");
__builder4.AddAttribute(40, "Size", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Radzen.ButtonSize>(
#nullable restore
#line 30 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
ButtonSize.Small
#line default
#line hidden
#nullable disable
));
__builder4.AddAttribute(41, "Visible", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Boolean>(
#nullable restore
#line 30 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
applicationUser.UserName != "administrator"
#line default
#line hidden
#nullable disable
));
__builder4.AddAttribute(42, "Click", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.MouseEventArgs>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 30 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
(args) =>GridDeleteButtonClick(args, applicationUser)
#line default
#line hidden
#nullable disable
)));
__builder4.AddEventStopPropagationAttribute(43, "onclick",
#nullable restore
#line 30 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
true
#line default
#line hidden
#nullable disable
);
__builder4.CloseComponent();
}
));
__builder3.CloseComponent();
}
));
__builder2.AddComponentReferenceCapture(44, (__value) => {
#nullable restore
#line 22 "C:\_blazor\product\BlazorExampleGithubInvoiceManagement\server\Pages\ApplicationUsers.razor"
grid0 = (Radzen.Blazor.RadzenGrid<ApplicationUser>)__value;
#line default
#line hidden
#nullable disable
}
);
__builder2.CloseComponent();
__builder2.CloseElement();
__builder2.CloseElement();
}
));
__builder.CloseComponent();
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 45.837838 | 353 | 0.653892 | [
"MIT"
] | go2ismail/BlazorExampleGithubInvoiceManagement | server/obj/Debug/net5.0/Razor/Pages/ApplicationUsers.razor.g.cs | 13,568 | C# |
namespace Tolbxela.ApexCharts
{
public enum StrokeCurve
{
smooth,
straight
}
} | 14.25 | 31 | 0.54386 | [
"MIT"
] | tolbxela/ApexCharts.NET | Code/Src/Enums/StrokeCurve.cs | 109 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace Cardinal.AspNetCore.Ocelot
{
/// <summary>
/// Swagger for Ocelot middleware.
/// This middleware generate swagger documentation from downstream services for SwaggerUI.
/// </summary>
public class OcelotSwaggerMiddleware
{
private readonly RequestDelegate Next;
private readonly IOptions<List<ReRouteOptions>> ReRoutes;
private readonly Lazy<Dictionary<string, SwaggerEndPointOptions>> SwaggerEndPoints;
private readonly IHttpClientFactory HttpClientFactory;
private readonly ISwaggerJsonTransformer Transformer;
/// <summary>
/// Initializes a new instance of the <see cref="OcelotSwaggerMiddleware"/> class.
/// </summary>
/// <param name="next">The next delegate.</param>
/// <param name="options">The options.</param>
/// <param name="reRoutes">The Ocelot ReRoutes configuration.</param>
/// <param name="swaggerEndPoints">The swagger end points.</param>
/// <param name="httpClientFactory">The HTTP client factory.</param>
/// <param name="transformer"></param>
public OcelotSwaggerMiddleware(RequestDelegate next, SwaggerForOCelotUIOptions options, IOptions<List<ReRouteOptions>> reRoutes, IOptions<List<SwaggerEndPointOptions>> swaggerEndPoints, IHttpClientFactory httpClientFactory, ISwaggerJsonTransformer transformer)
{
this.Transformer = Check.NotNull(transformer, nameof(transformer));
this.Next = Check.NotNull(next, nameof(next));
this.ReRoutes = Check.NotNull(reRoutes, nameof(reRoutes));
Check.NotNull(swaggerEndPoints, nameof(swaggerEndPoints));
this.HttpClientFactory = Check.NotNull(httpClientFactory, nameof(httpClientFactory));
var value = swaggerEndPoints.Value;
SwaggerEndPoints = new Lazy<Dictionary<string, SwaggerEndPointOptions>>(() => value.ToDictionary(p => $"/{p.KeyToPath}", p => p));
}
/// <summary>
/// Invokes the specified context.
/// </summary>
/// <param name="context">The context.</param>
public async Task Invoke(HttpContext context)
{
var endPoint = GetEndPoint(context.Request.Path);
var httpClient = HttpClientFactory.CreateClient();
var content = await httpClient.GetStringAsync(endPoint.Url);
content = Transformer.Transform(content, ReRoutes.Value.Where(p => p.SwaggerKey == endPoint.Key));
await context.Response.WriteAsync(content);
}
private SwaggerEndPointOptions GetEndPoint(string path) => SwaggerEndPoints.Value[path];
}
}
| 46.064516 | 268 | 0.683824 | [
"MIT"
] | kandrakah/Cardinal.AspNetCore | Addons/Cardinal.AspNetCore.Ocelot.Swagger/Middlewares/OcelotSwaggerMiddleware.cs | 2,858 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="ApiInvoker.cs">
// Copyright (c) 2003-2020 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Metadata.Cloud.Sdk.Client
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
internal class ApiInvoker
{
private const string GroupDocsClientHeaderName = "x-groupdocs-client";
private const string GroupDocsClientVersionHeaderName = "x-groupdocs-client-version";
private readonly Dictionary<string, string> defaultHeaderMap = new Dictionary<string, string>();
private readonly List<IRequestHandler> requestHandlers;
private readonly int _timeout;
public ApiInvoker(List<IRequestHandler> requestHandlers, int timeout)
{
var sdkVersion = this.GetType().Assembly.GetName().Version;
this.AddDefaultHeader(GroupDocsClientHeaderName, ".net sdk");
this.AddDefaultHeader(GroupDocsClientVersionHeaderName, string.Format("{0}.{1}", sdkVersion.Major, sdkVersion.Minor));
this.requestHandlers = requestHandlers;
this._timeout = timeout;
}
public string InvokeApi(
string path,
string method,
string body = null,
Dictionary<string, string> headerParams = null,
Dictionary<string, object> formParams = null,
string contentType = "application/json")
{
return this.InvokeInternal(path, method, false, body, headerParams, formParams, contentType) as string;
}
public Stream InvokeBinaryApi(
string path,
string method,
string body,
Dictionary<string, string> headerParams,
Dictionary<string, object> formParams,
string contentType = "application/json")
{
return (Stream)this.InvokeInternal(path, method, true, body, headerParams, formParams, contentType);
}
public FileInfo ToFileInfo(Stream stream, string paramName)
{
string contentType = paramName.Equals("File", StringComparison.InvariantCultureIgnoreCase)
? "application/octet-stream"
: "application/json";
return new FileInfo
{
Name = paramName,
MimeType = contentType,
FileContent = StreamHelper.ReadAsBytes(stream)
};
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new MemoryStream();
bool needsClrf = false;
if (postParameters.Count > 1)
{
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsClrf)
{
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
}
needsClrf = true;
if (param.Value is FileInfo)
{
var fileInfo = (FileInfo)param.Value;
string postData =
string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
fileInfo.MimeType);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileInfo.FileContent, 0, fileInfo.FileContent.Length);
}
else
{
var stringDaa = SerializationHelper.Serialize(param.Value);
string postData =
string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
stringDaa);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
}
else
{
foreach (var param in postParameters)
{
if (param.Value is FileInfo)
{
var fileInfo = (FileInfo)param.Value;
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileInfo.FileContent, 0, fileInfo.FileContent.Length);
}
else if (param.Value is byte[])
{
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(param.Value as byte[], 0, (param.Value as byte[]).Length);
}
else
{
string postData;
if (!(param.Value is string))
{
postData = SerializationHelper.Serialize(param.Value);
}
else
{
postData = (string)param.Value;
}
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
}
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
private void AddDefaultHeader(string key, string value)
{
if (!this.defaultHeaderMap.ContainsKey(key))
{
this.defaultHeaderMap.Add(key, value);
}
}
private object InvokeInternal(
string path,
string method,
bool binaryResponse,
string body,
Dictionary<string, string> headerParams,
Dictionary<string, object> formParams,
string contentType)
{
if (formParams == null)
{
formParams = new Dictionary<string, object>();
}
if (headerParams == null)
{
headerParams = new Dictionary<string, string>();
}
this.requestHandlers.ForEach(p => path = p.ProcessUrl(path));
WebRequest request;
try
{
request = this.PrepareRequest(path, method, formParams, headerParams, body, contentType);
return this.ReadResponse(request, binaryResponse);
}
catch (NeedRepeatRequestException)
{
request = this.PrepareRequest(path, method, formParams, headerParams, body, contentType);
return this.ReadResponse(request, binaryResponse);
}
}
private WebRequest PrepareRequest(string path, string method, Dictionary<string, object> formParams, Dictionary<string, string> headerParams, string body, string contentType)
{
var client = WebRequest.Create(path);
client.Method = method;
client.Timeout = _timeout;
byte[] formData = null;
if (formParams.Count > 0)
{
string formDataBoundary = "GroupDocsMetadataForCloud_NETSDKFormBoundary";
formData = GetMultipartFormData(formParams, formDataBoundary);
client.ContentLength = formData.Length;
}
else
{
client.ContentType = contentType;
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in this.defaultHeaderMap)
{
if (!headerParams.ContainsKey(defaultHeaderMapItem.Key))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
}
MemoryStream streamToSend = null;
try
{
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
streamToSend = new MemoryStream();
if (formData != null)
{
streamToSend.Write(formData, 0, formData.Length);
}
if (body != null)
{
var requestWriter = new StreamWriter(streamToSend);
requestWriter.Write(body);
requestWriter.Flush();
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
this.requestHandlers.ForEach(p => p.BeforeSend(client, streamToSend));
if (streamToSend != null)
{
using (Stream requestStream = client.GetRequestStream())
{
StreamHelper.CopyTo(streamToSend, requestStream);
}
}
}
finally
{
if (streamToSend != null)
{
streamToSend.Dispose();
}
}
return client;
}
private object ReadResponse(WebRequest client, bool binaryResponse)
{
var webResponse = (HttpWebResponse)this.GetResponse(client);
var resultStream = new MemoryStream();
try
{
StreamHelper.CopyTo(webResponse.GetResponseStream(), resultStream);
this.requestHandlers.ForEach(p => p.ProcessResponse(webResponse, resultStream));
resultStream.Position = 0;
if (binaryResponse)
{
return resultStream;
}
using (var responseReader = new StreamReader(resultStream))
{
var responseData = responseReader.ReadToEnd();
resultStream.Dispose();
return responseData;
}
}
catch (Exception)
{
resultStream.Dispose();
throw;
}
finally
{
webResponse.Close();
}
}
private WebResponse GetResponse(WebRequest request)
{
try
{
return request.GetResponse();
}
catch (WebException wex)
{
if (wex.Response != null)
{
return wex.Response;
}
throw;
}
}
}
}
| 38.378531 | 182 | 0.503018 | [
"MIT"
] | groupdocs-metadata-cloud/groupdocs-metadata-cloud-dotnet- | src_net2.0/GroupDocs.Metadata.Cloud.Sdk/Client/ApiInvoker.cs | 13,586 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using OmniSharp.Helpers;
using OmniSharp.Models.Diagnostics;
using OmniSharp.Roslyn.CSharp.Services.Diagnostics;
namespace OmniSharp.Roslyn.CSharp.Workers.Diagnostics
{
public class CSharpDiagnosticWorker: ICsDiagnosticWorker, IDisposable
{
private readonly ILogger _logger;
private readonly OmniSharpWorkspace _workspace;
private readonly DiagnosticEventForwarder _forwarder;
private readonly IObserver<string> _openDocuments;
private readonly IDisposable _disposable;
public CSharpDiagnosticWorker(OmniSharpWorkspace workspace, DiagnosticEventForwarder forwarder, ILoggerFactory loggerFactory)
{
_workspace = workspace;
_forwarder = forwarder;
_logger = loggerFactory.CreateLogger<CSharpDiagnosticWorker>();
var openDocumentsSubject = new Subject<string>();
_openDocuments = openDocumentsSubject;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
_workspace.DocumentOpened += OnDocumentOpened;
_workspace.DocumentClosed += OnDocumentOpened;
_disposable = openDocumentsSubject
.GroupByUntil(x => true, group => Observable.Amb(
group.Throttle(TimeSpan.FromMilliseconds(200)),
group.Distinct().Skip(99))
)
.Select(x => x.ToArray())
.Merge()
.SubscribeOn(TaskPoolScheduler.Default)
.Select(ProcessQueue)
.Merge()
.Subscribe();
}
private void OnDocumentOpened(object sender, DocumentEventArgs args)
{
if (!_forwarder.IsEnabled)
{
return;
}
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs changeEvent)
{
if (!_forwarder.IsEnabled)
{
return;
}
if (changeEvent.Kind == WorkspaceChangeKind.DocumentAdded || changeEvent.Kind == WorkspaceChangeKind.DocumentChanged || changeEvent.Kind == WorkspaceChangeKind.DocumentReloaded)
{
var newDocument = changeEvent.NewSolution.GetDocument(changeEvent.DocumentId);
EmitDiagnostics(_workspace.GetOpenDocumentIds().Select(x => _workspace.CurrentSolution.GetDocument(x).FilePath).ToArray());
}
else if (changeEvent.Kind == WorkspaceChangeKind.ProjectAdded || changeEvent.Kind == WorkspaceChangeKind.ProjectReloaded)
{
EmitDiagnostics(changeEvent.NewSolution.GetProject(changeEvent.ProjectId).Documents.Select(x => x.FilePath).ToArray());
}
}
public void QueueDiagnostics(params string[] documents)
{
if (!_forwarder.IsEnabled)
{
return;
}
this.EmitDiagnostics(documents);
}
private void EmitDiagnostics(params string[] documents)
{
if (!_forwarder.IsEnabled)
{
return;
}
foreach (var document in documents)
{
_openDocuments.OnNext(document);
}
}
private IObservable<Unit> ProcessQueue(IEnumerable<string> filePaths)
{
return Observable.FromAsync(async () =>
{
var results = await Task.WhenAll(filePaths.Distinct().Select(ProcessNextItem));
var message = new DiagnosticMessage()
{
Results = results
};
_forwarder.Forward(message);
});
}
private async Task<DiagnosticResult> ProcessNextItem(string filePath)
{
var documents = _workspace.GetDocuments(filePath);
var semanticModels = await Task.WhenAll(documents.Select(doc => doc.GetSemanticModelAsync()));
var items = semanticModels
.SelectMany(sm => sm.GetDiagnostics());
return new DiagnosticResult()
{
FileName = filePath,
QuickFixes = items.Select(x => x.ToDiagnosticLocation()).Distinct().ToArray()
};
}
public ImmutableArray<DocumentId> QueueForDiagnosis(ImmutableArray<string> documentPaths)
{
this.EmitDiagnostics(documentPaths.ToArray());
return ImmutableArray<DocumentId>.Empty;
}
public async Task<ImmutableArray<DocumentDiagnostics>> GetDiagnostics(ImmutableArray<string> documentPaths)
{
if (!documentPaths.Any()) return ImmutableArray<DocumentDiagnostics>.Empty;
var results = new List<DocumentDiagnostics>();
var documents =
(await Task.WhenAll(
documentPaths
.Select(docPath => _workspace.GetDocumentsFromFullProjectModelAsync(docPath)))
).SelectMany(s => s);
foreach (var document in documents)
{
if(document?.Project?.Name == null)
continue;
var projectName = document.Project.Name;
var diagnostics = await GetDiagnosticsForDocument(document, projectName);
results.Add(new DocumentDiagnostics(document.Id, document.FilePath, document.Project.Id, document.Project.Name, diagnostics));
}
return results.ToImmutableArray();
}
private static async Task<ImmutableArray<Diagnostic>> GetDiagnosticsForDocument(Document document, string projectName)
{
// Only basic syntax check is available if file is miscellanous like orphan .cs file.
// Those projects are on hard coded virtual project named 'MiscellaneousFiles.csproj'.
if (projectName == "MiscellaneousFiles.csproj")
{
var syntaxTree = await document.GetSyntaxTreeAsync();
return syntaxTree.GetDiagnostics().ToImmutableArray();
}
else
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel.GetDiagnostics();
}
}
public ImmutableArray<DocumentId> QueueDocumentsForDiagnostics()
{
var documents = _workspace.CurrentSolution.Projects.SelectMany(x => x.Documents);
QueueForDiagnosis(documents.Select(x => x.FilePath).ToImmutableArray());
return documents.Select(x => x.Id).ToImmutableArray();
}
public ImmutableArray<DocumentId> QueueDocumentsForDiagnostics(ImmutableArray<ProjectId> projectIds)
{
var documents = projectIds.SelectMany(projectId => _workspace.CurrentSolution.GetProject(projectId).Documents);
QueueForDiagnosis(documents.Select(x => x.FilePath).ToImmutableArray());
return documents.Select(x => x.Id).ToImmutableArray();
}
public Task<ImmutableArray<DocumentDiagnostics>> GetAllDiagnosticsAsync()
{
var documents = _workspace.CurrentSolution.Projects.SelectMany(x => x.Documents).Select(x => x.FilePath).ToImmutableArray();
return GetDiagnostics(documents);
}
public void Dispose()
{
_workspace.WorkspaceChanged -= OnWorkspaceChanged;
_workspace.DocumentOpened -= OnDocumentOpened;
_workspace.DocumentClosed -= OnDocumentOpened;
_disposable.Dispose();
}
}
}
| 37.990385 | 189 | 0.614401 | [
"MIT"
] | Samirat/omnisharp-roslyn | src/OmniSharp.Roslyn.CSharp/Workers/Diagnostics/CSharpDiagnosticWorker.cs | 7,902 | C# |
class Program {
static void Main(string[] args) {
string destination = "default";
switch (destination) {
case "Inventory":
AddToInventory();
break;
case "Hotbar":
AddToHotbar();
default:
Debug.Log("Destination Unknown");
break;
}
}
static void AddToInventory() {}
static void AddToHotbar() {
/* inserted */
int _19 = 29;
}
}
class Debug {
public static void Log(string v) {}
}
| 18.833333 | 39 | 0.586283 | [
"Apache-2.0"
] | thufv/DeepFix-C- | data/Mutation/CS0163_2_mutation_14/[E]CS0163.cs | 454 | C# |
namespace PeanutButter.RandomGenerators.Tests.PerformanceTest
{
public class BankingDetails : EntityBase
{
public string AccountNumber { get; set; }
public string BankName { get; set; }
public string BankBranch { get; set; }
public string BankBranchCode { get; set; }
}
} | 31.6 | 62 | 0.661392 | [
"BSD-3-Clause"
] | Geosong/PeanutButter | source/TestUtils/PeanutButter.RandomGenerators.Tests/PerformanceTest/BankingDetails.cs | 318 | C# |
using System;
using System.Collections.Generic;
using BackEndServer.Models.DBModels;
namespace BackEndServer.Models.ViewModels
{
public class LocationInformationList
{
public List<LocationInformation> LocationList { get; set; }
public LocationInformationList()
{
LocationList = new List<LocationInformation>();
}
public LocationInformationList(List<DatabaseLocation> dbAddressList)
{
LocationList = new List<LocationInformation>();
foreach (var databaseAddress in dbAddressList)
{
LocationList.Add(new LocationInformation(databaseAddress));
}
}
}
}
| 26.148148 | 76 | 0.637394 | [
"MIT"
] | Loriko/group2049-project | BackEnd/BackEndServer/Models/ViewModels/LocationInformationList.cs | 708 | C# |
// Copyright © .NET Foundation and Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="NetUserEnumFilter"/> nested type.
/// </content>
public partial class NetApi32
{
/// <summary>
/// Allowed values for the filter parameter of the <see cref="NetUserEnum(string, NetUserEnumLevel, NetUserEnumFilter, byte*, uint, out uint, out uint, ref uint)"/> function.
/// </summary>
[Flags]
public enum NetUserEnumFilter : uint
{
/// <summary>
/// Enumerates account data for users whose primary account is in another domain. This account type provides user access to this domain, but not to any domain that trusts this domain. The User Manager refers to this account type as a local user account.
/// </summary>
FILTER_TEMP_DUPLICATE_ACCOUNT = 0x0001,
/// <summary>
/// Enumerates normal user account data. This account type is associated with a typical user.
/// </summary>
FILTER_NORMAL_ACCOUNT = 0x0002,
/// <summary>
/// Enumerates interdomain trust account data. This account type is associated with a trust account for a domain that trusts other domains.
/// </summary>
FILTER_INTERDOMAIN_TRUST_ACCOUNT = 0x0008,
/// <summary>
/// Enumerates workstation or member server trust account data. This account type is associated with a machine account for a computer that is a member of the domain.
/// </summary>
FILTER_WORKSTATION_TRUST_ACCOUNT = 0x0010,
/// <summary>
/// numerates member server machine account data. This account type is associated with a computer account for a backup domain controller that is a member of the domain.
/// </summary>
FILTER_SERVER_TRUST_ACCOUNT = 0x0020,
}
}
}
| 45.23913 | 265 | 0.639116 | [
"MIT"
] | vatsan-madhavan/pinvoke | src/NetApi32/NetApi32+NetUserEnumFilter.cs | 2,084 | C# |
using System.Collections.Generic;
namespace DSIS.LineIterator
{
public class PointList<T> : IPointList<T>, IStackEnumerator<T>, IPointListWriter<T>
{
private readonly LinkedList<T> myList;
public PointList()
{
myList = new LinkedList<T>();
}
public T First
{
get { return myList.First.Value; }
}
public T Last
{
get { return myList.Last.Value; }
}
public int Count
{
get { return myList.Count; }
}
public IPointListWriter<T> PointWriter()
{
return this;
}
public void AddAll(IPointList<T> points)
{
foreach (var value in points.Values)
{
myList.AddLast(value);
}
}
public IStackEnumerator<T> StackEnumerator()
{
return this;
}
public IEnumerable<T> Values
{
get { return myList; }
}
public bool IsEmpty
{
get { return myList.Count == 0; }
}
public T Peek()
{
return First;
}
public void Pop()
{
myList.RemoveFirst();
}
public void Push(T value)
{
myList.AddFirst(value);
}
public void AddPoint(T pt)
{
myList.AddLast(pt);
}
public void Dispose()
{
}
}
} | 16.419753 | 86 | 0.515789 | [
"Apache-2.0"
] | jonnyzzz/phd-project | dsis/src/LineIterator/src/PointList.cs | 1,330 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rafy.MetaModel;
using Rafy.MetaModel.View;
namespace JXC.WPF.ViewConfig
{
internal class TimeSpanCriteriaConfig : WPFViewConfig<TimeSpanCriteria>
{
protected override void ConfigView()
{
View.DomainName("查询条件");
//横向显示查询面板。
View.UseDetailAsHorizontal();
using (View.OrderProperties())
{
View.Property(TimeSpanCriteria.TimeSpanTypeProperty)
.HasLabel("入库日期").ShowIn(ShowInWhere.Detail);
View.Property(TimeSpanCriteria.FromProperty)
.HasLabel("从").ShowInDetail(labelSize: 30);
View.Property(TimeSpanCriteria.ToProperty)
.HasLabel("至").ShowInDetail(labelSize: 30);
}
}
}
} | 30.333333 | 76 | 0.582418 | [
"MIT"
] | zgynhqf/trunk | Demo/JXC.WPF/ViewConfig/TimeSpanCriteriaConfig.cs | 950 | C# |
namespace VetSolutionRationLib.Models.Units;
public interface ISpecificUnit : IUnit
{
string DisplayMention { get; }
}
public sealed class SpecificUnit : UnitBase, ISpecificUnit
{
/// <inheritdoc />
public SpecificUnit(string displayMention) : base(UnitKind.Specific)
{
DisplayMention = displayMention;
}
/// <inheritdoc />
public string DisplayMention { get; }
} | 22.388889 | 72 | 0.69727 | [
"MIT"
] | Berreip/VetSolutionRation | VetSolutionRationLib/Models/Units/SpecificUnit.cs | 405 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Sample.WebApi.Controllers.ViewModels;
namespace Sample.WebApi.Controllers.Infrastructures.Filters
{
/// <summary>
/// Exception Filter
/// </summary>
public class ExceptionResultFilter : IAsyncExceptionFilter
{
/// <summary>
/// On Exception
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task OnExceptionAsync(ExceptionContext context)
{
var failResultViewModel = new FailResultViewModel()
{
Id = Guid.NewGuid().ToString(),
Method = $"{context.HttpContext.Request.Method} {context.HttpContext.Request.Path}",
Version = "1.0",
Status = "Error",
Error = new FailInformation
{
ErrorCode = "4000",
ErrorMessage = context.Exception.Message,
Description = context.Exception.ToString()
}
};
context.Result = new ObjectResult(failResultViewModel);
context.ExceptionHandled = true;
return Task.CompletedTask;
}
}
} | 31.658537 | 100 | 0.565485 | [
"MIT"
] | reantoilpc/Sample.WebApi | src/Sample.WebApi/Sample.WebApi/Controllers/Infrastructures/Filters/ExceptionResultFilter.cs | 1,298 | C# |
using Sweeper.Core.Diagnostics.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweeper.Core.Diagnostics
{
public static class DriveManager
{
public static string GetSystemDrive()
{
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
systemPath = Path.GetPathRoot(systemPath);
return systemPath;
}
public static List<DriveInformation> GetDrives()
{
List<DriveInformation> result = new List<DriveInformation>();
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
result.Add(new DriveInformation(drive));
}
}
return result;
}
}
}
| 24.538462 | 93 | 0.593521 | [
"MIT"
] | chungjongsu/Sweeper | source/Sweeper.Core/Diagnostics/DriveManager.cs | 959 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Hosting;
using System.Web.Mvc;
namespace CavemanTools.Mvc.ViewEngines
{
public class FlexibleViewEngine:IViewEngine
{
private FlexibleViewEngineSettings _settings=new FlexibleViewEngineSettings();
public FlexibleViewEngine(Action<FlexibleViewEngineSettings> config=null)
{
if (config != null)
{
config(_settings);
}
}
/// <summary>
/// Finds the specified partial view by using the specified controller context.
/// </summary>
/// <returns>
/// The partial view.
/// </returns>
/// <param name="controllerContext">The controller context.</param><param name="partialViewName">The name of the partial view.</param><param name="useCache">true to specify that the view engine returns the cached view, if a cached view exists; otherwise, false.</param>
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
return GetView(controllerContext, partialViewName, null, useCache, true);
}
/// <summary>
/// Finds the specified view by using the specified controller context.
/// </summary>
/// <returns>
/// The page view.
/// </returns>
/// <param name="controllerContext">The controller context.</param><param name="viewName">The name of the view.</param>
/// <param name="masterName">The name of the master.</param>
/// <param name="useCache">true to specify that the view engine returns the cached view, if a cached view exists; otherwise, false.</param>
public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
return GetView(controllerContext, viewName, masterName, useCache, false);
}
/// <summary>
/// True if the view is part of Mvc display or editor templates
/// </summary>
/// <param name="viewName"></param>
/// <returns></returns>
public static bool IsMvcTemplate(string viewName)
{
return viewName.StartsWith("DisplayTemplates") || viewName.StartsWith("EditorTemplates");
}
/// <summary>
/// Finds view and returns result
/// </summary>
/// <param name="controllerContext"></param>
/// <param name="viewName"></param>
/// <param name="masterName"></param>
/// <param name="useCache">Ignored</param>
/// <param name="isPartial"></param>
/// <returns></returns>
ViewEngineResult GetView(ControllerContext controllerContext, string viewName, string masterName, bool useCache,bool isPartial)
{
if (_settings.Conventions.Count == 0)
{
throw new MissingViewConventionsException();
}
List<string> searched = new List<string>();
foreach (var convention in _settings.Conventions)
{
if (!convention.Match(controllerContext, viewName))
{
continue;
}
var viewPath = convention.GetViewPath(controllerContext, viewName);
if (!FileExists(viewPath))
{
searched.Add(viewPath+" [FlexibleViewEngine]");
continue;
}
var masterPath = "";
if (!isPartial)
{
masterPath = convention.GetMasterPath(controllerContext, masterName);
if (!masterPath.IsNullOrEmpty(true) && !FileExists(masterPath))
{
searched.Add(viewPath + " [FlexibleViewEngine]");
continue;
}
}
var factory = _settings.FindViewFactoryByExtension(GetFileExtension(viewPath));
if (factory == null)
{
searched.Add(viewPath + " [FlexibleViewEngine]");
continue;
}
var settings = new ViewCreationData(controllerContext, viewPath, masterPath);
var view = isPartial?factory.CreatePartial(settings):factory.Create(settings);
return new ViewEngineResult(view, this);
}
return new ViewEngineResult(searched.ToArray());
}
bool FileExists(string virtualPath)
{
return HostingEnvironment.VirtualPathProvider.FileExists(virtualPath);
}
string GetFileExtension(string relativeFilePath)
{
var info = new FileInfo(HostingEnvironment.MapPath(relativeFilePath));
return info.Extension.TrimStart('.');
}
/// <summary>
/// Releases the specified view by using the specified controller context.
/// </summary>
/// <param name="controllerContext">The controller context.</param><param name="view">The view.</param>
public void ReleaseView(ControllerContext controllerContext, IView view)
{
var disp = view as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
}
} | 39.180556 | 278 | 0.553173 | [
"BSD-3-Clause"
] | Rusk85/CavemanToolBySapiensworks | src/CavemanTools.MVC/ViewEngines/FlexibleViewEngine.cs | 5,644 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyStik.TimeTable.DataServices.IO.Horst.Data
{
public class StudyProgramModule
{
public int id { get; set; }
public string title { get; set; }
public int ects { get; set; }
public int sws { get; set; }
public int regularSemester { get; set; }
public bool coursesBound { get; set; }
public bool coursesUnrestricted { get; set; }
public bool gop { get; set; }
public bool locked { get; set; }
public bool editable { get; set; }
public ICollection<StudyProgramExam> exams { get; set; }
public string state { get; set; }
public string stateClasses { get; set; }
public bool courseWarning { get; set; }
public string height { get; set; }
}
}
| 29.032258 | 64 | 0.617778 | [
"MIT"
] | AccelerateX-org/NINE | Sources/TimeTable/MyStik.TimeTable.DataServices/IO/Horst/Data/StudyProgramModule.cs | 902 | C# |
// Copyright 2015 Tosho Toshev
//
// 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 ElmCommunicatorPortable.Commands;
using ElmCommunicatorPortable.Responses.ObdIIResponses.ShowCurrentData;
using NUnit.Framework;
using Rhino.Mocks;
using UnitsNet;
namespace ElmCommunicatorTests.Responses.ObdIIResponses.ShowCurrentData
{
[TestFixture]
public class EngineCoolantTemperatureResponseTests
{
[SetUp]
public void SetUp()
{
_response = new EngineCoolantTemperatureResponse();
}
private const string Message = "41 05 3C";
private EngineCoolantTemperatureResponse _response;
[Test]
public void ShouldGetTheCommand()
{
const string expectedCommand = "4105";
IReceiveMessage response = _response.Parse(Message);
Assert.AreEqual(expectedCommand, response.Command);
}
[Test]
public void ShouldParseTheReceivedMessage()
{
const string expectedCommand = "4105";
const float expectedTemperature = 20;
_response.Parse(Message);
Assert.AreEqual(expectedCommand, _response.Command);
Assert.AreEqual(expectedTemperature, _response.Temperature.DegreesCelsius);
}
[Test]
public void ShouldReturnNullIfInvalidCommand()
{
IReceiveMessage response = _response.Parse("41 00 3C");
Assert.IsNull(response);
}
}
} | 33.229508 | 87 | 0.668476 | [
"Apache-2.0"
] | cracker4o/elm327lib | ElmCommunicator/ElmCommunicatorTests/Responses/ObdIIResponses/ShowCurrentData/EngineCoolantTemperatureResponseTests.cs | 2,029 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Senparc.Weixin.Cache;
using Senparc.Weixin.Cache.Redis;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Test.CommonAPIs;
using Senparc.CO2NET.Cache;
using Senparc.CO2NET.Cache.Redis;
namespace Senparc.Weixin.MP.Test.Containers.Tests
{
//已测试通过
[TestClass]
public class AccessTokenContainerAsyncTest : CommonApiTest
{
[TestMethod]
public void ContainerAsyncTest()
{
bool useRedis = true;
if (useRedis)
{
var redisConfiguration = "localhost:6379";
RedisManager.ConfigurationOption = redisConfiguration;
CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//Redis
}
//注册
AccessTokenContainer.Register(base._appId, base._appSecret);
//获取Token完整结果(包括当前过期秒数)
var dt1 = SystemTime.Now;
var tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result;
var dt2 = SystemTime.Now;
Assert.IsNotNull(tokenResult);
Console.WriteLine(tokenResult.access_token);
Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
//只获取Token字符串
dt1 = SystemTime.Now;
var token = AccessTokenContainer.GetAccessTokenAsync(base._appId).Result;
dt2 = SystemTime.Now;
Assert.AreEqual(tokenResult.access_token, token);
Console.WriteLine(tokenResult.access_token);
Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
//getNewToken
{
dt1 = SystemTime.Now;
token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, false).Result;
dt2 = SystemTime.Now;
Assert.AreEqual(tokenResult.access_token, token);
Console.WriteLine(tokenResult.access_token);
Console.WriteLine("强制重新获取AccessToken");
dt1 = SystemTime.Now;
token = AccessTokenContainer.TryGetAccessTokenAsync(base._appId, base._appSecret, true).Result;
dt2 = SystemTime.Now;
Assert.AreNotEqual(tokenResult.access_token, token);//如果微信服务器缓存,此处会相同
Console.WriteLine(tokenResult.access_token);
Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
}
{
tokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId).Result;
Console.WriteLine("HashCode:{0}", tokenResult.GetHashCode());
dt1 = SystemTime.Now;
var allItems = AccessTokenContainer.GetAllItems();
dt2 = SystemTime.Now;
Assert.IsTrue(allItems.Count > 0);
Assert.AreSame(tokenResult, allItems[0].AccessTokenResult);//证明缓存成功
Console.WriteLine("All Items:{0}", allItems.Count);
Console.WriteLine("HashCode:{0}", allItems[0].AccessTokenResult.GetHashCode());
Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
}
}
[TestMethod]
public void GetTokenResultTest()
{
//注册
AccessTokenContainer.Register(base._appId, base._appSecret);
//模拟多线程获取
List<string> accessTokenList = new List<string>();
int[] threads = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var accessTokenResultInit = AccessTokenContainer.GetAccessTokenResult(base._appId, false);//先获取一次
Parallel.For(0, threads.Length, (i) =>
{
var accessTokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId, false).Result;
accessTokenList.Add(accessTokenResult.access_token);//同时多次获取
Console.WriteLine(accessTokenResult.access_token);
});
Assert.AreEqual(threads.Length, accessTokenList.Count());//只存在同一个Token,实际不会多次刷新
Assert.AreEqual(1, accessTokenList.Distinct().Count());//只存在同一个Token,实际不会多次刷新
Console.WriteLine(accessTokenList[0]);
}
[TestMethod]
public void GetTokenResultAsyncTest()
{
//注册
AccessTokenContainer.Register(base._appId, base._appSecret);
//模拟多线程获取
List<string> accessTokenList = new List<string>();
int threadsCount = 5;//数字不易过大,否则超过微信允许同一个客户端同时并发数量,将可能看不到效果
int round = 10;//测试多少轮
//同步
TimeSpan syncTime =new TimeSpan();
var dt1 = SystemTime.Now;
for (int j = 0; j < round; j++)
{
Console.WriteLine("同步第{0}轮", j+1);
Parallel.For(0, threadsCount, (i) =>
{
var dts = SystemTime.Now;
var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(base._appId, true);
var dte = SystemTime.Now;
accessTokenList.Add(accessTokenResult.access_token);//同时多次获取
Console.WriteLine("{0}同步线程耗时:{1}ms", i, (dte - dts).TotalMilliseconds);
syncTime = syncTime.Add((dte - dts));
//Console.WriteLine(accessTokenResult.access_token);
});
}
var dt2 = SystemTime.Now;
Console.WriteLine("线程用时总和:{0}ms", syncTime.TotalMilliseconds);
Console.WriteLine("{0}线程{1}轮同步时间:{2}ms", threadsCount, round,(dt2 - dt1).TotalMilliseconds);
Console.WriteLine("=================");
//异步
TimeSpan asyncTime =new TimeSpan();
var dt3 = SystemTime.Now;
for (int j = 0; j < round; j++)
{
Console.WriteLine("异步第{0}轮", j+1);
Parallel.For(0, threadsCount, (i) =>
{
var dts = SystemTime.Now;
var accessTokenResult = AccessTokenContainer.GetAccessTokenResultAsync(base._appId, true).Result;
var dte = SystemTime.Now;
accessTokenList.Add(accessTokenResult.access_token); //同时多次获取
Console.WriteLine("{0}异步线程耗时:{1}ms", i, (dte - dts).TotalMilliseconds);
asyncTime = syncTime.Add((dte - dts));
//Console.WriteLine(accessTokenResult.access_token);
});
}
var dt4 = SystemTime.Now;
Console.WriteLine("线程用时总和:{0}ms", asyncTime.TotalMilliseconds);
Console.WriteLine("{0}个线程{1}轮异步时间:{2}ms", threadsCount, round,(dt4 - dt3).TotalMilliseconds);
}
[TestMethod]
public void GetFirstOrDefaultAppIdTest()
{
//此测试需要使用本地缓存进行测试
var registeredAppId = base._appId;//已经注册的AppId
var appId = AccessTokenContainer.GetFirstOrDefaultAppId(PlatformType.MP);
Assert.AreEqual(registeredAppId, appId);
//注册多个AppId
for (int i = 0; i < 100; i++)
{
AccessTokenContainer.Register("TestAppId_" + i, "TestAppSecret");
}
////删除部分AppId
//var collectionList = AccessTokenContainer.GetCollectionList();
//for (int i = 10; i < 50; i++)
//{
// collectionList.Remove("TestAppId_" + i);
//}
//appId = AccessTokenContainer.GetFirstOrDefaultAppId();
//Assert.AreEqual(registeredAppId, appId);
}
}
}
| 40.605634 | 117 | 0.584461 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP.Test/Containers/AccessTokenContainerAsyncTest.cs | 9,201 | C# |
//
// Unit tests for MPRemoteCommandCenter
//
// Authors:
// Sebastien Pouliot <sebastien@xamarin.com>
//
// Copyright 2013 Xamarin Inc. All rights reserved.
//
#if !__WATCHOS__
using System;
#if XAMCORE_2_0
using Foundation;
using MediaPlayer;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.MediaPlayer;
using MonoTouch.UIKit;
#endif
using NUnit.Framework;
namespace MonoTouchFixtures.MediaPlayer {
[TestFixture]
[Preserve (AllMembers = true)]
public class RemoteCommandCenterTest {
[Test]
public void Shared ()
{
if (!UIDevice.CurrentDevice.CheckSystemVersion (7, 1))
Assert.Inconclusive ("Requires 7.1+");
MPRemoteCommandCenter shared = MPRemoteCommandCenter.Shared;
Assert.NotNull (shared.BookmarkCommand, "BookmarkCommand");
Assert.NotNull (shared.ChangePlaybackRateCommand, "ChangePlaybackRateCommand");
Assert.NotNull (shared.ChangeRepeatModeCommand, "ChangeRepeatModeCommand");
Assert.NotNull (shared.ChangeShuffleModeCommand, "ChangeShuffleModeCommand");
Assert.NotNull (shared.DislikeCommand, "DislikeCommand");
Assert.NotNull (shared.LikeCommand, "LikeCommand");
Assert.NotNull (shared.NextTrackCommand, "NextTrackCommand");
Assert.NotNull (shared.PauseCommand, "PauseCommand");
Assert.NotNull (shared.PlayCommand, "PlayCommand");
Assert.NotNull (shared.PreviousTrackCommand, "PreviousTrackCommand");
Assert.NotNull (shared.SeekBackwardCommand, "SeekBackwardCommand");
Assert.NotNull (shared.SeekForwardCommand, "SeekForwardCommand");
Assert.NotNull (shared.SkipBackwardCommand, "SkipBackwardCommand");
Assert.NotNull (shared.SkipForwardCommand, "SkipForwardCommand");
Assert.NotNull (shared.StopCommand, "StopCommand");
Assert.NotNull (shared.TogglePlayPauseCommand, "TogglePlayPauseCommand");
}
}
}
#endif // !__WATCHOS__
| 31.534483 | 82 | 0.7731 | [
"BSD-3-Clause"
] | Acidburn0zzz/xamarin-macios | tests/monotouch-test/MediaPlayer/RemoteCommandCenterTest.cs | 1,829 | C# |
// ReSharper disable InconsistentNaming
namespace Tw.AlphaVantage.Net.Stocks.Parsing.JsonTokens
{
internal static class QuoteEndpointJsonTokens
{
public const string QuoteEndpointHeader = "Global Quote";
public const string QuoteEndpointSymbolToken = "01. symbol";
public const string QuoteEndpointOpenPriceToken = "02. open";
public const string QuoteEndpointHighPriceToken = "03. high";
public const string QuoteEndpointLowPriceToken = "04. low";
public const string QuoteEndpointPriceToken = "05. price";
public const string QuoteEndpointVolumeToken = "06. volume";
public const string QuoteEndpointLatestTradingDayToken = "07. latest trading day";
public const string QuoteEndpointPreviousClosePriceToken = "08. previous close";
public const string QuoteEndpointChangePriceToken = "09. change";
public const string QuoteEndpointChangePctToken = "10. change percent";
}
} | 51.368421 | 90 | 0.732582 | [
"MIT"
] | twesped/AlphaVantage.Net | AlphaVantage.Net/src/AlphaVantage.Net.Stocks/Parsing/JsonTokens/QuoteEndpointJsonTokens.cs | 978 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.