content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using Bio.Util.ArgumentParser;
using ScaffoldUtil.Properties;
namespace ScaffoldUtil
{
/// <summary>
/// Class that provides options to execute step 5 (ScaffoldGeneration) of Comparative assembly.
/// </summary>
public class Program
{
/// <summary>
/// Main method of the utility.
/// </summary>
/// <param name="args">Arguments to the main method.</param>
public static void Main(string[] args)
{
DisplayErrorMessage(Resources.ScaffoldSplashScreen);
try
{
if ((args == null) || (args.Length < 2))
{
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
}
else
{
if (args[0].Equals("Help", StringComparison.OrdinalIgnoreCase))
{
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
}
else
{
ScaffoldGeneration(args);
}
}
}
catch (Exception ex)
{
CatchInnerException(ex);
}
}
#region Private Methods
/// <summary>
/// Catches Inner Exception Messages.
/// </summary>
/// <param name="ex">The Exception.</param>
private static void CatchInnerException(Exception ex)
{
if (ex.InnerException == null || string.IsNullOrEmpty(ex.InnerException.Message))
{
DisplayErrorMessage(ex.Message);
}
else
{
CatchInnerException(ex.InnerException);
}
}
/// <summary>
/// Parses ScaffoldGeneration command line parameters.
/// </summary>
/// <param name="args">The arguments.</param>
private static void ScaffoldGeneration(string[] args)
{
ScaffoldArguments arguments = new ScaffoldArguments();
CommandLineArguments parser = new CommandLineArguments();
// Add scaffold parameters
parser.Parameter(ArgumentType.DefaultArgument, "FilePath", ArgumentValueType.MultipleUniqueStrings, "", "File path");
parser.Parameter(ArgumentType.Optional, "Help", ArgumentValueType.Bool, "h", "Print the help information.");
parser.Parameter(ArgumentType.Optional, "OutputFile", ArgumentValueType.String, "o", "Output file");
parser.Parameter(ArgumentType.Optional, "Verbose", ArgumentValueType.Bool, "v", "Display verbose logging during processing.");
parser.Parameter(ArgumentType.Optional, "KmerLength", ArgumentValueType.Int, "k", "Length of k-mer");
parser.Parameter(ArgumentType.Optional, "Redundancy", ArgumentValueType.Int, "r", "Number of paired read required to connect two contigs.");
parser.Parameter(ArgumentType.Optional, "Depth", ArgumentValueType.Int, "d", "Depth for graph traversal.");
parser.Parameter(ArgumentType.Optional, "CloneLibraryName", ArgumentValueType.String, "n", "Clone Library Name");
parser.Parameter(ArgumentType.Optional, "MeanLengthOfInsert", ArgumentValueType.Int, "i", "Mean Length of clone library.");
parser.Parameter(ArgumentType.Optional, "StandardDeviationOfInsert", ArgumentValueType.Int, "sd", "Standard Deviation of Clone Library.");
if (args.Length > 1)
{
try
{
parser.Parse(args, arguments);
}
catch (ArgumentParserException ex)
{
DisplayErrorMessage(ex.Message);
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
Environment.Exit(-1);
}
if (arguments.Help)
{
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
}
else if (arguments.FilePath.Length == 2)
{
arguments.GenerateScaffolds();
}
else
{
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
}
}
else
{
DisplayErrorMessage(Resources.ScaffoldUtilHelp);
}
}
/// <summary>
/// Display error message on console.
/// </summary>
/// <param name="message">Error message.</param>
private static void DisplayErrorMessage(string message)
{
Console.Write(message);
}
/// <summary>
/// Removes the command line.
/// </summary>
/// <param name="args">Arguments to remove.</param>
/// <returns>Returns the arguments.</returns>
private static string[] RemoveCommandLine(string[] args)
{
string[] arguments = new string[args.Length - 1];
for (int index = 0; index < args.Length - 1; index++)
{
arguments[index] = args[index + 1];
}
return arguments;
}
#endregion
}
}
| 37.042254 | 152 | 0.53403 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | archive/Changesets/mbf/Source/Tools/ScaffoldUtil/Program.cs | 5,262 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the mediaconnect-2018-11-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MediaConnect.Model
{
/// <summary>
/// The entitlements that you want to grant on a flow.
/// </summary>
public partial class GrantEntitlementRequest
{
private int? _dataTransferSubscriberFeePercent;
private string _description;
private Encryption _encryption;
private string _name;
private List<string> _subscribers = new List<string>();
/// <summary>
/// Gets and sets the property DataTransferSubscriberFeePercent. Percentage from 0-100
/// of the data transfer cost to be billed to the subscriber.
/// </summary>
public int DataTransferSubscriberFeePercent
{
get { return this._dataTransferSubscriberFeePercent.GetValueOrDefault(); }
set { this._dataTransferSubscriberFeePercent = value; }
}
// Check to see if DataTransferSubscriberFeePercent property is set
internal bool IsSetDataTransferSubscriberFeePercent()
{
return this._dataTransferSubscriberFeePercent.HasValue;
}
/// <summary>
/// Gets and sets the property Description. A description of the entitlement. This description
/// appears only on the AWS Elemental MediaConnect console and will not be seen by the
/// subscriber or end user.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Encryption. The type of encryption that will be used on
/// the output that is associated with this entitlement.
/// </summary>
public Encryption Encryption
{
get { return this._encryption; }
set { this._encryption = value; }
}
// Check to see if Encryption property is set
internal bool IsSetEncryption()
{
return this._encryption != null;
}
/// <summary>
/// Gets and sets the property Name. The name of the entitlement. This value must be unique
/// within the current flow.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Subscribers. The AWS account IDs that you want to share
/// your content with. The receiving accounts (subscribers) will be allowed to create
/// their own flows using your content as the source.
/// </summary>
[AWSProperty(Required=true)]
public List<string> Subscribers
{
get { return this._subscribers; }
set { this._subscribers = value; }
}
// Check to see if Subscribers property is set
internal bool IsSetSubscribers()
{
return this._subscribers != null && this._subscribers.Count > 0;
}
}
} | 33.64 | 110 | 0.623781 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/MediaConnect/Generated/Model/GrantEntitlementRequest.cs | 4,205 | C# |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Portal.Web;
namespace Site.Areas.Conference.Pages
{
public partial class Home : ConferencePage
{
protected const string ConferenceIdQueryStringParameterName = "conferenceid";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Register_Click(object sender, EventArgs args)
{
if (PortalConference == null)
{
return;
}
var registrationUrl = GetRegistrationUrl(PortalConference.Id);
Response.Redirect(registrationUrl);
}
protected string GetRegistrationUrl(Guid conferenceId)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Conference Registration");
if (page == null)
{
throw new ApplicationException(string.Format("A page couldn't be found for the site marker named {0}.", "Conference Registration"));
}
var url = ServiceContext.GetUrl(page);
if (string.IsNullOrWhiteSpace(url))
{
throw new ApplicationException(string.Format("A URL couldn't be determined for the site marker named {0}.", "Conference Registration"));
}
var urlBuilder = new UrlBuilder(url);
urlBuilder.QueryString.Add(ConferenceIdQueryStringParameterName, conferenceId.ToString());
return urlBuilder.PathWithQueryString;
}
}
}
| 25.859649 | 140 | 0.744233 | [
"MIT"
] | Adoxio/xRM-Portals-Community-Edition | Samples/MasterPortal/Areas/Conference/Pages/Home.aspx.cs | 1,474 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace System.Drawing
{
[DebuggerDisplay("{NameAndARGBValue}")]
[Serializable]
public struct Color
{
public static readonly Color Empty = new Color();
// -------------------------------------------------------------------
// static list of "web" colors...
//
public static Color Transparent => new Color(KnownColor.Transparent);
public static Color AliceBlue => new Color(KnownColor.AliceBlue);
public static Color AntiqueWhite => new Color(KnownColor.AntiqueWhite);
public static Color Aqua => new Color(KnownColor.Aqua);
public static Color Aquamarine => new Color(KnownColor.Aquamarine);
public static Color Azure => new Color(KnownColor.Azure);
public static Color Beige => new Color(KnownColor.Beige);
public static Color Bisque => new Color(KnownColor.Bisque);
public static Color Black => new Color(KnownColor.Black);
public static Color BlanchedAlmond => new Color(KnownColor.BlanchedAlmond);
public static Color Blue => new Color(KnownColor.Blue);
public static Color BlueViolet => new Color(KnownColor.BlueViolet);
public static Color Brown => new Color(KnownColor.Brown);
public static Color BurlyWood => new Color(KnownColor.BurlyWood);
public static Color CadetBlue => new Color(KnownColor.CadetBlue);
public static Color Chartreuse => new Color(KnownColor.Chartreuse);
public static Color Chocolate => new Color(KnownColor.Chocolate);
public static Color Coral => new Color(KnownColor.Coral);
public static Color CornflowerBlue => new Color(KnownColor.CornflowerBlue);
public static Color Cornsilk => new Color(KnownColor.Cornsilk);
public static Color Crimson => new Color(KnownColor.Crimson);
public static Color Cyan => new Color(KnownColor.Cyan);
public static Color DarkBlue => new Color(KnownColor.DarkBlue);
public static Color DarkCyan => new Color(KnownColor.DarkCyan);
public static Color DarkGoldenrod => new Color(KnownColor.DarkGoldenrod);
public static Color DarkGray => new Color(KnownColor.DarkGray);
public static Color DarkGreen => new Color(KnownColor.DarkGreen);
public static Color DarkKhaki => new Color(KnownColor.DarkKhaki);
public static Color DarkMagenta => new Color(KnownColor.DarkMagenta);
public static Color DarkOliveGreen => new Color(KnownColor.DarkOliveGreen);
public static Color DarkOrange => new Color(KnownColor.DarkOrange);
public static Color DarkOrchid => new Color(KnownColor.DarkOrchid);
public static Color DarkRed => new Color(KnownColor.DarkRed);
public static Color DarkSalmon => new Color(KnownColor.DarkSalmon);
public static Color DarkSeaGreen => new Color(KnownColor.DarkSeaGreen);
public static Color DarkSlateBlue => new Color(KnownColor.DarkSlateBlue);
public static Color DarkSlateGray => new Color(KnownColor.DarkSlateGray);
public static Color DarkTurquoise => new Color(KnownColor.DarkTurquoise);
public static Color DarkViolet => new Color(KnownColor.DarkViolet);
public static Color DeepPink => new Color(KnownColor.DeepPink);
public static Color DeepSkyBlue => new Color(KnownColor.DeepSkyBlue);
public static Color DimGray => new Color(KnownColor.DimGray);
public static Color DodgerBlue => new Color(KnownColor.DodgerBlue);
public static Color Firebrick => new Color(KnownColor.Firebrick);
public static Color FloralWhite => new Color(KnownColor.FloralWhite);
public static Color ForestGreen => new Color(KnownColor.ForestGreen);
public static Color Fuchsia => new Color(KnownColor.Fuchsia);
public static Color Gainsboro => new Color(KnownColor.Gainsboro);
public static Color GhostWhite => new Color(KnownColor.GhostWhite);
public static Color Gold => new Color(KnownColor.Gold);
public static Color Goldenrod => new Color(KnownColor.Goldenrod);
public static Color Gray => new Color(KnownColor.Gray);
public static Color Green => new Color(KnownColor.Green);
public static Color GreenYellow => new Color(KnownColor.GreenYellow);
public static Color Honeydew => new Color(KnownColor.Honeydew);
public static Color HotPink => new Color(KnownColor.HotPink);
public static Color IndianRed => new Color(KnownColor.IndianRed);
public static Color Indigo => new Color(KnownColor.Indigo);
public static Color Ivory => new Color(KnownColor.Ivory);
public static Color Khaki => new Color(KnownColor.Khaki);
public static Color Lavender => new Color(KnownColor.Lavender);
public static Color LavenderBlush => new Color(KnownColor.LavenderBlush);
public static Color LawnGreen => new Color(KnownColor.LawnGreen);
public static Color LemonChiffon => new Color(KnownColor.LemonChiffon);
public static Color LightBlue => new Color(KnownColor.LightBlue);
public static Color LightCoral => new Color(KnownColor.LightCoral);
public static Color LightCyan => new Color(KnownColor.LightCyan);
public static Color LightGoldenrodYellow => new Color(KnownColor.LightGoldenrodYellow);
public static Color LightGreen => new Color(KnownColor.LightGreen);
public static Color LightGray => new Color(KnownColor.LightGray);
public static Color LightPink => new Color(KnownColor.LightPink);
public static Color LightSalmon => new Color(KnownColor.LightSalmon);
public static Color LightSeaGreen => new Color(KnownColor.LightSeaGreen);
public static Color LightSkyBlue => new Color(KnownColor.LightSkyBlue);
public static Color LightSlateGray => new Color(KnownColor.LightSlateGray);
public static Color LightSteelBlue => new Color(KnownColor.LightSteelBlue);
public static Color LightYellow => new Color(KnownColor.LightYellow);
public static Color Lime => new Color(KnownColor.Lime);
public static Color LimeGreen => new Color(KnownColor.LimeGreen);
public static Color Linen => new Color(KnownColor.Linen);
public static Color Magenta => new Color(KnownColor.Magenta);
public static Color Maroon => new Color(KnownColor.Maroon);
public static Color MediumAquamarine => new Color(KnownColor.MediumAquamarine);
public static Color MediumBlue => new Color(KnownColor.MediumBlue);
public static Color MediumOrchid => new Color(KnownColor.MediumOrchid);
public static Color MediumPurple => new Color(KnownColor.MediumPurple);
public static Color MediumSeaGreen => new Color(KnownColor.MediumSeaGreen);
public static Color MediumSlateBlue => new Color(KnownColor.MediumSlateBlue);
public static Color MediumSpringGreen => new Color(KnownColor.MediumSpringGreen);
public static Color MediumTurquoise => new Color(KnownColor.MediumTurquoise);
public static Color MediumVioletRed => new Color(KnownColor.MediumVioletRed);
public static Color MidnightBlue => new Color(KnownColor.MidnightBlue);
public static Color MintCream => new Color(KnownColor.MintCream);
public static Color MistyRose => new Color(KnownColor.MistyRose);
public static Color Moccasin => new Color(KnownColor.Moccasin);
public static Color NavajoWhite => new Color(KnownColor.NavajoWhite);
public static Color Navy => new Color(KnownColor.Navy);
public static Color OldLace => new Color(KnownColor.OldLace);
public static Color Olive => new Color(KnownColor.Olive);
public static Color OliveDrab => new Color(KnownColor.OliveDrab);
public static Color Orange => new Color(KnownColor.Orange);
public static Color OrangeRed => new Color(KnownColor.OrangeRed);
public static Color Orchid => new Color(KnownColor.Orchid);
public static Color PaleGoldenrod => new Color(KnownColor.PaleGoldenrod);
public static Color PaleGreen => new Color(KnownColor.PaleGreen);
public static Color PaleTurquoise => new Color(KnownColor.PaleTurquoise);
public static Color PaleVioletRed => new Color(KnownColor.PaleVioletRed);
public static Color PapayaWhip => new Color(KnownColor.PapayaWhip);
public static Color PeachPuff => new Color(KnownColor.PeachPuff);
public static Color Peru => new Color(KnownColor.Peru);
public static Color Pink => new Color(KnownColor.Pink);
public static Color Plum => new Color(KnownColor.Plum);
public static Color PowderBlue => new Color(KnownColor.PowderBlue);
public static Color Purple => new Color(KnownColor.Purple);
public static Color Red => new Color(KnownColor.Red);
public static Color RosyBrown => new Color(KnownColor.RosyBrown);
public static Color RoyalBlue => new Color(KnownColor.RoyalBlue);
public static Color SaddleBrown => new Color(KnownColor.SaddleBrown);
public static Color Salmon => new Color(KnownColor.Salmon);
public static Color SandyBrown => new Color(KnownColor.SandyBrown);
public static Color SeaGreen => new Color(KnownColor.SeaGreen);
public static Color SeaShell => new Color(KnownColor.SeaShell);
public static Color Sienna => new Color(KnownColor.Sienna);
public static Color Silver => new Color(KnownColor.Silver);
public static Color SkyBlue => new Color(KnownColor.SkyBlue);
public static Color SlateBlue => new Color(KnownColor.SlateBlue);
public static Color SlateGray => new Color(KnownColor.SlateGray);
public static Color Snow => new Color(KnownColor.Snow);
public static Color SpringGreen => new Color(KnownColor.SpringGreen);
public static Color SteelBlue => new Color(KnownColor.SteelBlue);
public static Color Tan => new Color(KnownColor.Tan);
public static Color Teal => new Color(KnownColor.Teal);
public static Color Thistle => new Color(KnownColor.Thistle);
public static Color Tomato => new Color(KnownColor.Tomato);
public static Color Turquoise => new Color(KnownColor.Turquoise);
public static Color Violet => new Color(KnownColor.Violet);
public static Color Wheat => new Color(KnownColor.Wheat);
public static Color White => new Color(KnownColor.White);
public static Color WhiteSmoke => new Color(KnownColor.WhiteSmoke);
public static Color Yellow => new Color(KnownColor.Yellow);
public static Color YellowGreen => new Color(KnownColor.YellowGreen);
//
// end "web" colors
// -------------------------------------------------------------------
// NOTE : The "zero" pattern (all members being 0) must represent
// : "not set". This allows "Color c;" to be correct.
private static short s_stateKnownColorValid = 0x0001;
private static short s_stateARGBValueValid = 0x0002;
private static short s_stateValueMask = (short)(s_stateARGBValueValid);
private static short s_stateNameValid = 0x0008;
private static long s_notDefinedValue = 0;
/**
* Shift count and bit mask for A, R, G, B components in ARGB mode!
*/
private const int ARGBAlphaShift = 24;
private const int ARGBRedShift = 16;
private const int ARGBGreenShift = 8;
private const int ARGBBlueShift = 0;
// user supplied name of color. Will not be filled in if
// we map to a "knowncolor"
//
private readonly string name;
// will contain standard 32bit sRGB (ARGB)
//
private readonly long value;
// ignored, unless "state" says it is valid
//
private readonly short knownColor;
// implementation specific information
//
private readonly short state;
internal Color(KnownColor knownColor)
{
value = 0;
state = s_stateKnownColorValid;
name = null;
this.knownColor = unchecked((short)knownColor);
}
private Color(long value, short state, string name, KnownColor knownColor)
{
this.value = value;
this.state = state;
this.name = name;
this.knownColor = unchecked((short)knownColor);
}
public byte R => (byte)((Value >> ARGBRedShift) & 0xFF);
public byte G => (byte)((Value >> ARGBGreenShift) & 0xFF);
public byte B => (byte)((Value >> ARGBBlueShift) & 0xFF);
public byte A => (byte)((Value >> ARGBAlphaShift) & 0xFF);
public bool IsKnownColor => ((state & s_stateKnownColorValid) != 0);
public bool IsEmpty => state == 0;
public bool IsNamedColor => ((state & s_stateNameValid) != 0) || IsKnownColor;
public bool IsSystemColor => IsKnownColor && ((((KnownColor)knownColor) <= KnownColor.WindowText) || (((KnownColor)knownColor) > KnownColor.YellowGreen));
// Not localized because it's only used for the DebuggerDisplayAttribute, and the values are
// programmatic items.
// Also, don't inline into the attribute for performance reasons. This way means the debugger
// does 1 func-eval instead of 5.
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")]
private string NameAndARGBValue => $"{{Name={Name}, ARGB=({A}, {R}, {G}, {B})}}";
public string Name
{
get
{
if ((state & s_stateNameValid) != 0)
{
return name;
}
if (IsKnownColor)
{
// first try the table so we can avoid the (slow!) .ToString()
string tablename = KnownColorTable.KnownColorToName((KnownColor)knownColor);
if (tablename != null)
return tablename;
Debug.Assert(false, "Could not find known color '" + ((KnownColor)knownColor) + "' in the KnownColorTable");
return ((KnownColor)knownColor).ToString();
}
// if we reached here, just encode the value
//
return Convert.ToString(value, 16);
}
}
private long Value
{
get
{
if ((state & s_stateValueMask) != 0)
{
return value;
}
if (IsKnownColor)
{
return unchecked((int)KnownColorTable.KnownColorToArgb((KnownColor)knownColor));
}
return s_notDefinedValue;
}
}
private static void CheckByte(int value, string name)
{
if (value < 0 || value > 255)
throw new ArgumentException(SR.Format(SR.InvalidEx2BoundArgument, name, value, 0, 255));
}
private static long MakeArgb(byte alpha, byte red, byte green, byte blue)
{
return (long)(unchecked((uint)(red << ARGBRedShift |
green << ARGBGreenShift |
blue << ARGBBlueShift |
alpha << ARGBAlphaShift))) & 0xffffffff;
}
public static Color FromArgb(int argb)
{
return new Color((long)argb & 0xffffffff, s_stateARGBValueValid, null, (KnownColor)0);
}
public static Color FromArgb(int alpha, int red, int green, int blue)
{
CheckByte(alpha, nameof(alpha));
CheckByte(red, nameof(red));
CheckByte(green, nameof(green));
CheckByte(blue, nameof(blue));
return new Color(MakeArgb((byte)alpha, (byte)red, (byte)green, (byte)blue), s_stateARGBValueValid, null, (KnownColor)0);
}
public static Color FromArgb(int alpha, Color baseColor)
{
CheckByte(alpha, nameof(alpha));
// unchecked - because we already checked that alpha is a byte in CheckByte above
return new Color(MakeArgb(unchecked((byte)alpha), baseColor.R, baseColor.G, baseColor.B), s_stateARGBValueValid, null, (KnownColor)0);
}
public static Color FromArgb(int red, int green, int blue)
{
return FromArgb(255, red, green, blue);
}
public static Color FromKnownColor(KnownColor color)
{
var value = (int)color;
if (value < (int)KnownColor.ActiveBorder || value > (int)KnownColor.MenuHighlight)
{
return Color.FromName(color.ToString());
}
return new Color(color);
}
public static Color FromName(string name)
{
// try to get a known color first
Color color;
if (ColorTable.TryGetNamedColor(name, out color))
{
return color;
}
// otherwise treat it as a named color
return new Color(s_notDefinedValue, s_stateNameValid, name, (KnownColor)0);
}
public float GetBrightness()
{
float r = (float)R / 255.0f;
float g = (float)G / 255.0f;
float b = (float)B / 255.0f;
float max, min;
max = r; min = r;
if (g > max) max = g;
if (b > max) max = b;
if (g < min) min = g;
if (b < min) min = b;
return (max + min) / 2;
}
public Single GetHue()
{
if (R == G && G == B)
return 0; // 0 makes as good an UNDEFINED value as any
float r = (float)R / 255.0f;
float g = (float)G / 255.0f;
float b = (float)B / 255.0f;
float max, min;
float delta;
float hue = 0.0f;
max = r; min = r;
if (g > max) max = g;
if (b > max) max = b;
if (g < min) min = g;
if (b < min) min = b;
delta = max - min;
if (r == max)
{
hue = (g - b) / delta;
}
else if (g == max)
{
hue = 2 + (b - r) / delta;
}
else if (b == max)
{
hue = 4 + (r - g) / delta;
}
hue *= 60;
if (hue < 0.0f)
{
hue += 360.0f;
}
return hue;
}
public float GetSaturation()
{
float r = (float)R / 255.0f;
float g = (float)G / 255.0f;
float b = (float)B / 255.0f;
float max, min;
float l, s = 0;
max = r; min = r;
if (g > max) max = g;
if (b > max) max = b;
if (g < min) min = g;
if (b < min) min = b;
// if max == min, then there is no color and
// the saturation is zero.
//
if (max != min)
{
l = (max + min) / 2;
if (l <= .5)
{
s = (max - min) / (max + min);
}
else
{
s = (max - min) / (2 - max - min);
}
}
return s;
}
public int ToArgb()
{
return unchecked((int)Value);
}
public KnownColor ToKnownColor()
{
return (KnownColor)knownColor;
}
public override string ToString()
{
if ((state & s_stateNameValid) != 0 || (state & s_stateKnownColorValid) != 0)
{
return nameof(Color) + " [" + Name + "]";
}
else if ((state & s_stateValueMask) != 0)
{
return nameof(Color) + " [A=" + A.ToString() + ", R=" + R.ToString() + ", G=" + G.ToString() + ", B=" + B.ToString() + "]";
}
else
{
return nameof(Color) + " [Empty]";
}
}
public static bool operator ==(Color left, Color right)
{
if (left.value == right.value
&& left.state == right.state
&& left.knownColor == right.knownColor)
{
if (left.name == right.name)
{
return true;
}
if (ReferenceEquals(left.name, null) || ReferenceEquals(right.name, null))
{
return false;
}
return left.name.Equals(right.name);
}
return false;
}
public static bool operator !=(Color left, Color right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return obj is Color && this == (Color)obj;
}
public override int GetHashCode()
{
return unchecked(value.GetHashCode() ^
state.GetHashCode() ^
knownColor.GetHashCode());
}
}
}
| 33.426606 | 162 | 0.588308 | [
"MIT"
] | slamj1/corefx | src/System.Drawing.Primitives/src/System/Drawing/Color.cs | 21,861 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.GameServices.v1
{
/// <summary>The GameServices Service.</summary>
public class GameServicesService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GameServicesService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GameServicesService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "gameservices";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://gameservices.googleapis.com/";
#else
"https://gameservices.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://gameservices.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Game Services API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Game Services API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for GameServices requests.</summary>
public abstract class GameServicesBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new GameServicesBaseServiceRequest instance.</summary>
protected GameServicesBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes GameServices parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
GameServerDeployments = new GameServerDeploymentsResource(service);
Operations = new OperationsResource(service);
Realms = new RealmsResource(service);
}
/// <summary>Gets the GameServerDeployments resource.</summary>
public virtual GameServerDeploymentsResource GameServerDeployments { get; }
/// <summary>The "gameServerDeployments" collection of methods.</summary>
public class GameServerDeploymentsResource
{
private const string Resource = "gameServerDeployments";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GameServerDeploymentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Configs = new ConfigsResource(service);
}
/// <summary>Gets the Configs resource.</summary>
public virtual ConfigsResource Configs { get; }
/// <summary>The "configs" collection of methods.</summary>
public class ConfigsResource
{
private const string Resource = "configs";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ConfigsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Creates a new game server config in a given project, location, and game server deployment. Game
/// server configs are immutable, and are not applied until referenced in the game server deployment
/// rollout resource.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GameServices.v1.Data.GameServerConfig body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Creates a new game server config in a given project, location, and game server deployment. Game
/// server configs are immutable, and are not applied until referenced in the game server deployment
/// rollout resource.
/// </summary>
public class CreateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerConfig body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. The ID of the game server config resource to be created.</summary>
[Google.Apis.Util.RequestParameterAttribute("configId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string ConfigId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerConfig Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/configs";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("configId", new Google.Apis.Discovery.Parameter
{
Name = "configId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Deletes a single game server config. The deletion will fail if the game server config is
/// referenced in a game server deployment rollout.
/// </summary>
/// <param name="name">
/// Required. The name of the game server config to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a single game server config. The deletion will fail if the game server config is
/// referenced in a game server deployment rollout.
/// </summary>
public class DeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server config to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+/configs/[^/]+$",
});
}
}
/// <summary>Gets details of a single game server config.</summary>
/// <param name="name">
/// Required. The name of the game server config to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single game server config.</summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.GameServerConfig>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server config to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+/configs/[^/]+$",
});
}
}
/// <summary>
/// Lists game server configs in a given project, location, and game server deployment.
/// </summary>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>
/// Lists game server configs in a given project, location, and game server deployment.
/// </summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListGameServerConfigsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The filter to apply to list results.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If unspecified, server will pick an
/// appropriate default. Server may return fewer items than requested. A caller should only rely
/// on response's next_page_token to determine if there are more GameServerConfigs left to be
/// queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous list request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/configs";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Creates a new game server deployment in a given project and location.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GameServices.v1.Data.GameServerDeployment body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new game server deployment in a given project and location.</summary>
public class CreateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerDeployment body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. The ID of the game server delpoyment resource to be created.</summary>
[Google.Apis.Util.RequestParameterAttribute("deploymentId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DeploymentId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerDeployment Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/gameServerDeployments";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("deploymentId", new Google.Apis.Discovery.Parameter
{
Name = "deploymentId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a single game server deployment.</summary>
/// <param name="name">
/// Required. The name of the game server delpoyment to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a single game server deployment.</summary>
public class DeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server delpoyment to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>
/// Retrieves information about the current state of the game server deployment. Gathers all the Agones
/// fleets and Agones autoscalers, including fleets running an older version of the game server
/// deployment.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The name of the game server delpoyment, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </param>
public virtual FetchDeploymentStateRequest FetchDeploymentState(Google.Apis.GameServices.v1.Data.FetchDeploymentStateRequest body, string name)
{
return new FetchDeploymentStateRequest(service, body, name);
}
/// <summary>
/// Retrieves information about the current state of the game server deployment. Gathers all the Agones
/// fleets and Agones autoscalers, including fleets running an older version of the game server
/// deployment.
/// </summary>
public class FetchDeploymentStateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.FetchDeploymentStateResponse>
{
/// <summary>Constructs a new FetchDeploymentState request.</summary>
public FetchDeploymentStateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.FetchDeploymentStateRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the game server delpoyment, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.FetchDeploymentStateRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "fetchDeploymentState";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:fetchDeploymentState";
/// <summary>Initializes FetchDeploymentState parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>Gets details of a single game server deployment.</summary>
/// <param name="name">
/// Required. The name of the game server delpoyment to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single game server deployment.</summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.GameServerDeployment>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server delpoyment to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests
/// specifying an invalid value will be rejected. Requests for policies with any conditional
/// bindings must specify version 3. Policies without any conditional bindings may specify any valid
/// value or leave the field unset. To learn which resources support conditions in their IAM
/// policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets details a single game server deployment rollout.</summary>
/// <param name="name">
/// Required. The name of the game server delpoyment to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`.
/// </param>
public virtual GetRolloutRequest GetRollout(string name)
{
return new GetRolloutRequest(service, name);
}
/// <summary>Gets details a single game server deployment rollout.</summary>
public class GetRolloutRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout>
{
/// <summary>Constructs a new GetRollout request.</summary>
public GetRolloutRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server delpoyment to retrieve, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getRollout";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/rollout";
/// <summary>Initializes GetRollout parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>Lists game server deployments in a given project and location.</summary>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists game server deployments in a given project and location.</summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListGameServerDeploymentsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The filter to apply to list results.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If unspecified, the server will pick an
/// appropriate default. The server may return fewer items than requested. A caller should only rely
/// on response's next_page_token to determine if there are more GameServerDeployments left to be
/// queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous List request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/gameServerDeployments";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Patches a game server deployment.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the game server deployment, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.GameServices.v1.Data.GameServerDeployment body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Patches a game server deployment.</summary>
public class PatchRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerDeployment body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the game server deployment, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. For the
/// `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerDeployment Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Previews the game server deployment rollout. This API does not mutate the rollout resource.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the game server deployment rollout, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout`.
/// </param>
public virtual PreviewRolloutRequest PreviewRollout(Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout body, string name)
{
return new PreviewRolloutRequest(service, body, name);
}
/// <summary>
/// Previews the game server deployment rollout. This API does not mutate the rollout resource.
/// </summary>
public class PreviewRolloutRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.PreviewGameServerDeploymentRolloutResponse>
{
/// <summary>Constructs a new PreviewRollout request.</summary>
public PreviewRolloutRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the game server deployment rollout, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`. For
/// example, `projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. The target timestamp to compute the preview. Defaults to the immediately after the
/// proposed rollout completes.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("previewTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object PreviewTime { get; set; }
/// <summary>
/// Optional. Mask of fields to update. At least one path must be supplied in this field. For the
/// `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "previewRollout";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/rollout:preview";
/// <summary>Initializes PreviewRollout parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("previewTime", new Google.Apis.Discovery.Parameter
{
Name = "previewTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.GameServices.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.GameServices.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
}
}
/// <summary>
/// Patches a single game server deployment rollout. The method will not return an error if the update
/// does not affect any existing realms. For example - if the default_game_server_config is changed but
/// all existing realms use the override, that is valid. Similarly, if a non existing realm is
/// explicitly called out in game_server_config_overrides field, that will also not result in an error.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the game server deployment rollout, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout`.
/// </param>
public virtual UpdateRolloutRequest UpdateRollout(Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout body, string name)
{
return new UpdateRolloutRequest(service, body, name);
}
/// <summary>
/// Patches a single game server deployment rollout. The method will not return an error if the update
/// does not affect any existing realms. For example - if the default_game_server_config is changed but
/// all existing realms use the override, that is valid. Similarly, if a non existing realm is
/// explicitly called out in game_server_config_overrides field, that will also not result in an error.
/// </summary>
public class UpdateRolloutRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new UpdateRollout request.</summary>
public UpdateRolloutRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the game server deployment rollout, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`. For
/// example, `projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. For the
/// `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerDeploymentRollout Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "updateRollout";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/rollout";
/// <summary>Initializes UpdateRollout parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/gameServerDeployments/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.GameServices.v1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
public class CancelRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/operations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Realms resource.</summary>
public virtual RealmsResource Realms { get; }
/// <summary>The "realms" collection of methods.</summary>
public class RealmsResource
{
private const string Resource = "realms";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public RealmsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
GameServerClusters = new GameServerClustersResource(service);
}
/// <summary>Gets the GameServerClusters resource.</summary>
public virtual GameServerClustersResource GameServerClusters { get; }
/// <summary>The "gameServerClusters" collection of methods.</summary>
public class GameServerClustersResource
{
private const string Resource = "gameServerClusters";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GameServerClustersResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a new game server cluster in a given project and location.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm-id}`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GameServices.v1.Data.GameServerCluster body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new game server cluster in a given project and location.</summary>
public class CreateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerCluster body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm-id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. The ID of the game server cluster resource to be created.</summary>
[Google.Apis.Util.RequestParameterAttribute("gameServerClusterId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GameServerClusterId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerCluster Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/gameServerClusters";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
RequestParameters.Add("gameServerClusterId", new Google.Apis.Discovery.Parameter
{
Name = "gameServerClusterId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a single game server cluster.</summary>
/// <param name="name">
/// Required. The name of the game server cluster to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerClusters/{cluster}`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a single game server cluster.</summary>
public class DeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server cluster to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerClusters/{cluster}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+/gameServerClusters/[^/]+$",
});
}
}
/// <summary>Gets details of a single game server cluster.</summary>
/// <param name="name">
/// Required. The name of the game server cluster to retrieve, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single game server cluster.</summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.GameServerCluster>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server cluster to retrieve, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. View for the returned GameServerCluster objects. When `FULL` is specified, the
/// `cluster_state` field is also returned in the GameServerCluster object, which includes the
/// state of the referenced Kubernetes cluster such as versions and provider info. The
/// default/unset value is GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED, same as BASIC, which does not
/// return the `cluster_state` field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>
/// Optional. View for the returned GameServerCluster objects. When `FULL` is specified, the
/// `cluster_state` field is also returned in the GameServerCluster object, which includes the
/// state of the referenced Kubernetes cluster such as versions and provider info. The
/// default/unset value is GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED, same as BASIC, which does not
/// return the `cluster_state` field.
/// </summary>
public enum ViewEnum
{
/// <summary>The default / unset value. The API will default to the BASIC view.</summary>
[Google.Apis.Util.StringValueAttribute("GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED")]
GAMESERVERCLUSTERVIEWUNSPECIFIED = 0,
/// <summary>
/// Include basic information of a GameServerCluster resource and omit `cluster_state`. This
/// is the default value (for ListGameServerClusters, GetGameServerCluster and
/// PreviewCreateGameServerCluster).
/// </summary>
[Google.Apis.Util.StringValueAttribute("BASIC")]
BASIC = 1,
/// <summary>Include everything.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL = 2,
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+/gameServerClusters/[^/]+$",
});
RequestParameters.Add("view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists game server clusters in a given project and location.</summary>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// "projects/{project}/locations/{location}/realms/{realm}".
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists game server clusters in a given project and location.</summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListGameServerClustersResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// "projects/{project}/locations/{location}/realms/{realm}".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The filter to apply to list results.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If unspecified, the server will pick an
/// appropriate default. The server may return fewer items than requested. A caller should only
/// rely on response's next_page_token to determine if there are more GameServerClusters left to
/// be queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous List request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>
/// Optional. View for the returned GameServerCluster objects. When `FULL` is specified, the
/// `cluster_state` field is also returned in the GameServerCluster object, which includes the
/// state of the referenced Kubernetes cluster such as versions and provider info. The
/// default/unset value is GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED, same as BASIC, which does not
/// return the `cluster_state` field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>
/// Optional. View for the returned GameServerCluster objects. When `FULL` is specified, the
/// `cluster_state` field is also returned in the GameServerCluster object, which includes the
/// state of the referenced Kubernetes cluster such as versions and provider info. The
/// default/unset value is GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED, same as BASIC, which does not
/// return the `cluster_state` field.
/// </summary>
public enum ViewEnum
{
/// <summary>The default / unset value. The API will default to the BASIC view.</summary>
[Google.Apis.Util.StringValueAttribute("GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED")]
GAMESERVERCLUSTERVIEWUNSPECIFIED = 0,
/// <summary>
/// Include basic information of a GameServerCluster resource and omit `cluster_state`. This
/// is the default value (for ListGameServerClusters, GetGameServerCluster and
/// PreviewCreateGameServerCluster).
/// </summary>
[Google.Apis.Util.StringValueAttribute("BASIC")]
BASIC = 1,
/// <summary>Include everything.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL = 2,
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/gameServerClusters";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Patches a single game server cluster.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name of the game server cluster, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`. For
/// example,
/// `projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.GameServices.v1.Data.GameServerCluster body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Patches a single game server cluster.</summary>
public class PatchRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerCluster body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the game server cluster, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`. For
/// example,
/// `projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. For
/// the `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerCluster Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+/gameServerClusters/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Previews creation of a new game server cluster in a given project and location.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
public virtual PreviewCreateRequest PreviewCreate(Google.Apis.GameServices.v1.Data.GameServerCluster body, string parent)
{
return new PreviewCreateRequest(service, body, parent);
}
/// <summary>
/// Previews creation of a new game server cluster in a given project and location.
/// </summary>
public class PreviewCreateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.PreviewCreateGameServerClusterResponse>
{
/// <summary>Constructs a new PreviewCreate request.</summary>
public PreviewCreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerCluster body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. The ID of the game server cluster resource to be created.</summary>
[Google.Apis.Util.RequestParameterAttribute("gameServerClusterId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GameServerClusterId { get; set; }
/// <summary>Optional. The target timestamp to compute the preview.</summary>
[Google.Apis.Util.RequestParameterAttribute("previewTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object PreviewTime { get; set; }
/// <summary>
/// Optional. This field is deprecated, preview will always return KubernetesClusterState.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<ViewEnum> View { get; set; }
/// <summary>
/// Optional. This field is deprecated, preview will always return KubernetesClusterState.
/// </summary>
public enum ViewEnum
{
/// <summary>The default / unset value. The API will default to the BASIC view.</summary>
[Google.Apis.Util.StringValueAttribute("GAME_SERVER_CLUSTER_VIEW_UNSPECIFIED")]
GAMESERVERCLUSTERVIEWUNSPECIFIED = 0,
/// <summary>
/// Include basic information of a GameServerCluster resource and omit `cluster_state`. This
/// is the default value (for ListGameServerClusters, GetGameServerCluster and
/// PreviewCreateGameServerCluster).
/// </summary>
[Google.Apis.Util.StringValueAttribute("BASIC")]
BASIC = 1,
/// <summary>Include everything.</summary>
[Google.Apis.Util.StringValueAttribute("FULL")]
FULL = 2,
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerCluster Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "previewCreate";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/gameServerClusters:previewCreate";
/// <summary>Initializes PreviewCreate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
RequestParameters.Add("gameServerClusterId", new Google.Apis.Discovery.Parameter
{
Name = "gameServerClusterId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("previewTime", new Google.Apis.Discovery.Parameter
{
Name = "previewTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("view", new Google.Apis.Discovery.Parameter
{
Name = "view",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Previews deletion of a single game server cluster.</summary>
/// <param name="name">
/// Required. The name of the game server cluster to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerClusters/{cluster}`.
/// </param>
public virtual PreviewDeleteRequest PreviewDelete(string name)
{
return new PreviewDeleteRequest(service, name);
}
/// <summary>Previews deletion of a single game server cluster.</summary>
public class PreviewDeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.PreviewDeleteGameServerClusterResponse>
{
/// <summary>Constructs a new PreviewDelete request.</summary>
public PreviewDeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the game server cluster to delete, in the following form:
/// `projects/{project}/locations/{location}/gameServerClusters/{cluster}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The target timestamp to compute the preview.</summary>
[Google.Apis.Util.RequestParameterAttribute("previewTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object PreviewTime { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "previewDelete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:previewDelete";
/// <summary>Initializes PreviewDelete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+/gameServerClusters/[^/]+$",
});
RequestParameters.Add("previewTime", new Google.Apis.Discovery.Parameter
{
Name = "previewTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Previews updating a GameServerCluster.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name of the game server cluster, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`. For
/// example,
/// `projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster`.
/// </param>
public virtual PreviewUpdateRequest PreviewUpdate(Google.Apis.GameServices.v1.Data.GameServerCluster body, string name)
{
return new PreviewUpdateRequest(service, body, name);
}
/// <summary>Previews updating a GameServerCluster.</summary>
public class PreviewUpdateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.PreviewUpdateGameServerClusterResponse>
{
/// <summary>Constructs a new PreviewUpdate request.</summary>
public PreviewUpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.GameServerCluster body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the game server cluster, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`. For
/// example,
/// `projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The target timestamp to compute the preview.</summary>
[Google.Apis.Util.RequestParameterAttribute("previewTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object PreviewTime { get; set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. For
/// the `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.GameServerCluster Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "previewUpdate";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:previewUpdate";
/// <summary>Initializes PreviewUpdate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+/gameServerClusters/[^/]+$",
});
RequestParameters.Add("previewTime", new Google.Apis.Discovery.Parameter
{
Name = "previewTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Creates a new realm in a given project and location.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GameServices.v1.Data.Realm body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new realm in a given project and location.</summary>
public class CreateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.Realm body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. The ID of the realm resource to be created.</summary>
[Google.Apis.Util.RequestParameterAttribute("realmId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RealmId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.Realm Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/realms";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("realmId", new Google.Apis.Discovery.Parameter
{
Name = "realmId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a single realm.</summary>
/// <param name="name">
/// Required. The name of the realm to delete, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a single realm.</summary>
public class DeleteRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the realm to delete, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
}
}
/// <summary>Gets details of a single realm.</summary>
/// <param name="name">
/// Required. The name of the realm to retrieve, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single realm.</summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Realm>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the realm to retrieve, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
}
}
/// <summary>Lists realms in a given project and location.</summary>
/// <param name="parent">
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists realms in a given project and location.</summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListRealmsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent resource name, in the following form:
/// `projects/{project}/locations/{location}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The filter to apply to list results.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If unspecified, server will pick an appropriate
/// default. Server may return fewer items than requested. A caller should only rely on response's
/// next_page_token to determine if there are more realms left to be queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous List request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/realms";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Patches a single realm.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the realm, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`. For example,
/// `projects/my-project/locations/{location}/realms/my-realm`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.GameServices.v1.Data.Realm body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Patches a single realm.</summary>
public class PatchRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.Realm body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the realm, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`. For example,
/// `projects/my-project/locations/{location}/realms/my-realm`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. The update mask applies to the resource. For the `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.Realm Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Previews patches to a single realm.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the realm, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`. For example,
/// `projects/my-project/locations/{location}/realms/my-realm`.
/// </param>
public virtual PreviewUpdateRequest PreviewUpdate(Google.Apis.GameServices.v1.Data.Realm body, string name)
{
return new PreviewUpdateRequest(service, body, name);
}
/// <summary>Previews patches to a single realm.</summary>
public class PreviewUpdateRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.PreviewRealmUpdateResponse>
{
/// <summary>Constructs a new PreviewUpdate request.</summary>
public PreviewUpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.GameServices.v1.Data.Realm body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the realm, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`. For example,
/// `projects/my-project/locations/{location}/realms/my-realm`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The target timestamp to compute the preview.</summary>
[Google.Apis.Util.RequestParameterAttribute("previewTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object PreviewTime { get; set; }
/// <summary>
/// Required. The update mask applies to the resource. For the `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GameServices.v1.Data.Realm Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "previewUpdate";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:previewUpdate";
/// <summary>Initializes PreviewUpdate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/realms/[^/]+$",
});
RequestParameters.Add("previewTime", new Google.Apis.Discovery.Parameter
{
Name = "previewTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets information about a location.</summary>
/// <param name="name">Resource name for the location.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a location.</summary>
public class GetRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.Location>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Resource name for the location.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Lists information about the supported locations for this service.</summary>
/// <param name="name">The resource that owns the locations collection, if applicable.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists information about the supported locations for this service.</summary>
public class ListRequest : GameServicesBaseServiceRequest<Google.Apis.GameServices.v1.Data.ListLocationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource that owns the locations collection, if applicable.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like
/// "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>If true, the returned list will include locations which are not yet revealed.</summary>
[Google.Apis.Util.RequestParameterAttribute("includeUnrevealedLocations", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> IncludeUnrevealedLocations { get; set; }
/// <summary>
/// The maximum number of results to return. If not set, the service selects a default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token received from the `next_page_token` field in the response. Send that page token to
/// receive the subsequent page.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/locations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("includeUnrevealedLocations", new Google.Apis.Discovery.Parameter
{
Name = "includeUnrevealedLocations",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.GameServices.v1.Data
{
/// <summary>
/// Specifies the audit configuration for a service. The configuration determines which permission types are logged,
/// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If
/// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used
/// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each
/// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service":
/// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ]
/// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com",
/// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [
/// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
/// logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging.
/// </summary>
public class AuditConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The configuration for logging of each type of permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")]
public virtual System.Collections.Generic.IList<AuditLogConfig> AuditLogConfigs { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
/// <summary>
/// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`,
/// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("service")]
public virtual string Service { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type":
/// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables
/// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging.
/// </summary>
public class AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Specifies the identities that do not cause logging for this type of permission. Follows the same format of
/// Binding.members.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("ignoreChildExemptions")]
public virtual System.Nullable<bool> IgnoreChildExemptions { get; set; }
/// <summary>The log type that this config enables.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logType")]
public virtual string LogType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Authorization-related information used by Cloud Audit Logging.</summary>
public class AuthorizationLoggingOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The type of the permission that was checked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissionType")]
public virtual string PermissionType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members` with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("bindingId")]
public virtual string BindingId { get; set; }
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>
/// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `admins@example.com`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Write a Cloud Audit log</summary>
public class CloudAuditOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Information used by the Cloud Audit Logging pipeline.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("authorizationLoggingOptions")]
public virtual AuthorizationLoggingOptions AuthorizationLoggingOptions { get; set; }
/// <summary>The log_name to populate in the Cloud Audit Record.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logName")]
public virtual string LogName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A condition to be met.</summary>
public class Condition : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Trusted attributes supplied by the IAM system.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("iam")]
public virtual string Iam { get; set; }
/// <summary>An operator to apply the subject with.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("op")]
public virtual string Op { get; set; }
/// <summary>Trusted attributes discharged by the service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("svc")]
public virtual string Svc { get; set; }
/// <summary>
/// Trusted attributes supplied by any service that owns resources and uses the IAM system for access control.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sys")]
public virtual string Sys { get; set; }
/// <summary>The objects of the condition.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("values")]
public virtual System.Collections.Generic.IList<string> Values { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Increment a streamz counter with the specified metric and field names. Metric names should start with a '/',
/// generally be lowercase-only, and end in "_count". Field names should not contain an initial slash. The actual
/// exported metric names will have "/iam/policy" prepended. Field names correspond to IAM request parameters and
/// field values are their respective values. Supported field names: - "authority", which is "[token]" if
/// IAMContext.token is present, otherwise the value of IAMContext.authority_selector if present, and otherwise a
/// representation of IAMContext.principal; or - "iam_principal", a representation of IAMContext.principal even if a
/// token or authority selector is present; or - "" (empty string), resulting in a counter with no fields. Examples:
/// counter { metric: "/debug_access_count" field: "iam_principal" } ==&gt; increment counter
/// /iam/policy/debug_access_count {iam_principal=[value of IAMContext.principal]}
/// </summary>
public class CounterOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Custom fields.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("customFields")]
public virtual System.Collections.Generic.IList<CustomField> CustomFields { get; set; }
/// <summary>The field value to attribute.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("field")]
public virtual string Field { get; set; }
/// <summary>The metric to update.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metric")]
public virtual string Metric { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Custom fields. These can be used to create a counter with arbitrary field/value pairs. See:
/// go/rpcsp-custom-fields.
/// </summary>
public class CustomField : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Name is the field name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Value is the field value. It is important that in contrast to the CounterOptions.field, the value here is a
/// constant that is not derived from the IAMContext.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Write a Data Access (Gin) log</summary>
public class DataAccessOptions : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("logMode")]
public virtual string LogMode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The game server cluster changes made by the game server deployment.</summary>
public class DeployedClusterState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("cluster")]
public virtual string Cluster { get; set; }
/// <summary>The details about the Agones fleets and autoscalers created in the game server cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetDetails")]
public virtual System.Collections.Generic.IList<DeployedFleetDetails> FleetDetails { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Agones fleet specification and details.</summary>
public class DeployedFleet : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the Agones fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleet")]
public virtual string Fleet { get; set; }
/// <summary>The fleet spec retrieved from the Agones fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetSpec")]
public virtual string FleetSpec { get; set; }
/// <summary>
/// The source spec that is used to create the Agones fleet. The GameServerConfig resource may no longer exist
/// in the system.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("specSource")]
public virtual SpecSource SpecSource { get; set; }
/// <summary>The current status of the Agones fleet. Includes count of game servers in various states.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual DeployedFleetStatus Status { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details about the Agones autoscaler.</summary>
public class DeployedFleetAutoscaler : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the Agones autoscaler.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("autoscaler")]
public virtual string Autoscaler { get; set; }
/// <summary>The autoscaler spec retrieved from Agones.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetAutoscalerSpec")]
public virtual string FleetAutoscalerSpec { get; set; }
/// <summary>
/// The source spec that is used to create the autoscaler. The GameServerConfig resource may no longer exist in
/// the system.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("specSource")]
public virtual SpecSource SpecSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details of the deployed Agones fleet.</summary>
public class DeployedFleetDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Information about the Agones autoscaler for that fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deployedAutoscaler")]
public virtual DeployedFleetAutoscaler DeployedAutoscaler { get; set; }
/// <summary>Information about the Agones fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deployedFleet")]
public virtual DeployedFleet DeployedFleet { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// DeployedFleetStatus has details about the Agones fleets such as how many are running, how many allocated, and so
/// on.
/// </summary>
public class DeployedFleetStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of GameServer replicas in the ALLOCATED state in this fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allocatedReplicas")]
public virtual System.Nullable<long> AllocatedReplicas { get; set; }
/// <summary>The number of GameServer replicas in the READY state in this fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("readyReplicas")]
public virtual System.Nullable<long> ReadyReplicas { get; set; }
/// <summary>The total number of current GameServer replicas in this fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("replicas")]
public virtual System.Nullable<long> Replicas { get; set; }
/// <summary>
/// The number of GameServer replicas in the RESERVED state in this fleet. Reserved instances won't be deleted
/// on scale down, but won't cause an autoscaler to scale up.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reservedReplicas")]
public virtual System.Nullable<long> ReservedReplicas { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for GameServerDeploymentsService.FetchDeploymentState.</summary>
public class FetchDeploymentStateRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for GameServerDeploymentsService.FetchDeploymentState.</summary>
public class FetchDeploymentStateResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The state of the game server deployment in each game server cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterState")]
public virtual System.Collections.Generic.IList<DeployedClusterState> ClusterState { get; set; }
/// <summary>List of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unavailable")]
public virtual System.Collections.Generic.IList<string> Unavailable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Fleet configs for Agones.</summary>
public class FleetConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Agones fleet spec. Example spec: `https://agones.dev/site/docs/reference/fleet/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetSpec")]
public virtual string FleetSpec { get; set; }
/// <summary>The name of the FleetConfig.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A game server cluster resource.</summary>
public class GameServerCluster : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The state of the Kubernetes cluster, this will be available if 'view' is set to `FULL` in the
/// relevant List/Get/Preview request.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterState")]
public virtual KubernetesClusterState ClusterState { get; set; }
/// <summary>
/// The game server cluster connection information. This information is used to manage game server clusters.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("connectionInfo")]
public virtual GameServerClusterConnectionInfo ConnectionInfo { get; set; }
/// <summary>Output only. The creation time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Human readable description of the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The labels associated with this game server cluster. Each label is a key-value pair.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Required. The resource name of the game server cluster, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`. For example,
/// `projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The last-modified time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
}
/// <summary>The game server cluster connection information.</summary>
public class GameServerClusterConnectionInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Reference to the GKE cluster where the game servers are installed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gkeClusterReference")]
public virtual GkeClusterReference GkeClusterReference { get; set; }
/// <summary>
/// Namespace designated on the game server cluster where the Agones game server instances will be created.
/// Existence of the namespace will be validated during creation.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("namespace")]
public virtual string Namespace__ { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A game server config resource.</summary>
public class GameServerConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The creation time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>The description of the game server config.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>FleetConfig contains a list of Agones fleet specs. Only one FleetConfig is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetConfigs")]
public virtual System.Collections.Generic.IList<FleetConfig> FleetConfigs { get; set; }
/// <summary>The labels associated with this game server config. Each label is a key-value pair.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// The resource name of the game server config, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-game/configs/my-config`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The autoscaling settings.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scalingConfigs")]
public virtual System.Collections.Generic.IList<ScalingConfig> ScalingConfigs { get; set; }
/// <summary>Output only. The last-modified time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A game server config override.</summary>
public class GameServerConfigOverride : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The game server config for this override.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("configVersion")]
public virtual string ConfigVersion { get; set; }
/// <summary>Selector for choosing applicable realms.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("realmsSelector")]
public virtual RealmSelector RealmsSelector { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A game server deployment resource.</summary>
public class GameServerDeployment : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The creation time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Human readable description of the game server delpoyment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The labels associated with this game server deployment. Each label is a key-value pair.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// The resource name of the game server deployment, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The last-modified time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
}
/// <summary>The game server deployment rollout which represents the desired rollout state.</summary>
public class GameServerDeploymentRollout : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The creation time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// The default game server config is applied to all realms unless overridden in the rollout. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-game/configs/my-config`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultGameServerConfig")]
public virtual string DefaultGameServerConfig { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Contains the game server config rollout overrides. Overrides are processed in the order they are listed.
/// Once a match is found for a realm, the rest of the list is not processed.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerConfigOverrides")]
public virtual System.Collections.Generic.IList<GameServerConfigOverride> GameServerConfigOverrides { get; set; }
/// <summary>
/// The resource name of the game server deployment rollout, in the following form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout`. For example,
/// `projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The last-modified time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
}
/// <summary>A reference to a GKE cluster.</summary>
public class GkeClusterReference : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The full or partial name of a GKE cluster, using one of the following forms: *
/// `projects/{project}/locations/{location}/clusters/{cluster}` * `locations/{location}/clusters/{cluster}` *
/// `{cluster}` If project and location are not specified, the project and location of the GameServerCluster
/// resource are used to generate the full name of the GKE cluster.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cluster")]
public virtual string Cluster { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The state of the Kubernetes cluster.</summary>
public class KubernetesClusterState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The version of Agones currently installed in the registered Kubernetes cluster.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("agonesVersionInstalled")]
public virtual string AgonesVersionInstalled { get; set; }
/// <summary>Output only. The version of Agones that is targeted to be installed in the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agonesVersionTargeted")]
public virtual string AgonesVersionTargeted { get; set; }
/// <summary>Output only. The state for the installed versions of Agones/Kubernetes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("installationState")]
public virtual string InstallationState { get; set; }
/// <summary>
/// Output only. The version of Kubernetes that is currently used in the registered Kubernetes cluster (as
/// detected by the Cloud Game Servers service).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("kubernetesVersionInstalled")]
public virtual string KubernetesVersionInstalled { get; set; }
/// <summary>
/// Output only. The cloud provider type reported by the first node's providerID in the list of nodes on the
/// Kubernetes endpoint. On Kubernetes platforms that support zero-node clusters (like GKE-on-GCP), the provider
/// type will be empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("provider")]
public virtual string Provider { get; set; }
/// <summary>Output only. The detailed error message for the installed versions of Agones/Kubernetes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("versionInstalledErrorMessage")]
public virtual string VersionInstalledErrorMessage { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The label selector, used to group labels on the resources.</summary>
public class LabelSelector : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Resource labels for this selector.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for GameServerClustersService.ListGameServerClusters.</summary>
public class ListGameServerClustersResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of game server clusters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerClusters")]
public virtual System.Collections.Generic.IList<GameServerCluster> GameServerClusters { get; set; }
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>List of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for GameServerConfigsService.ListGameServerConfigs.</summary>
public class ListGameServerConfigsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of game server configs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerConfigs")]
public virtual System.Collections.Generic.IList<GameServerConfig> GameServerConfigs { get; set; }
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>List of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for GameServerDeploymentsService.ListGameServerDeployments.</summary>
public class ListGameServerDeploymentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of game server deployments.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerDeployments")]
public virtual System.Collections.Generic.IList<GameServerDeployment> GameServerDeployments { get; set; }
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>List of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Locations.ListLocations.</summary>
public class ListLocationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of locations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<Location> Locations { get; set; }
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for RealmsService.ListRealms.</summary>
public class ListRealmsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of realms.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("realms")]
public virtual System.Collections.Generic.IList<Realm> Realms { get; set; }
/// <summary>List of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A resource that represents Google Cloud Platform location.</summary>
public class Location : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The friendly name for this location, typically a nearby city name. For example, "Tokyo".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The canonical id for this location. For example: `"us-east1"`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locationId")]
public virtual string LocationId { get; set; }
/// <summary>Service-specific metadata. For example the available capacity at the given location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// Resource name for the location, which may vary between implementations. For example:
/// `"projects/example-project/locations/us-east1"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Specifies what kind of log the caller must write</summary>
public class LogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Cloud audit options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("cloudAudit")]
public virtual CloudAuditOptions CloudAudit { get; set; }
/// <summary>Counter options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("counter")]
public virtual CounterOptions Counter { get; set; }
/// <summary>Data access options.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataAccess")]
public virtual DataAccessOptions DataAccess { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class OperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. Operation status for Game Services API operations. Operation status is in the form of key-value
/// pairs where keys are resource IDs and the values show the status of the operation. In case of failures, the
/// value includes an error code and error message.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("operationStatus")]
public virtual System.Collections.Generic.IDictionary<string, OperationStatus> OperationStatus { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedCancellation")]
public virtual System.Nullable<bool> RequestedCancellation { get; set; }
/// <summary>Output only. Human-readable status of the operation, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusMessage")]
public virtual string StatusMessage { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. List of Locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class OperationStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Whether the operation is done or still in progress.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error code in case of failures.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual string ErrorCode { get; set; }
/// <summary>The human-readable error message.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can
/// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of
/// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google
/// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to
/// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of
/// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the
/// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** {
/// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com -
/// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin -
/// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features,
/// see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies cloud audit logging configuration for this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")]
public virtual System.Collections.Generic.IList<AuditConfig> AuditConfigs { get; set; }
/// <summary>
/// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and
/// when the `bindings` are applied. Each of the `bindings` must contain at least one member.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("iamOwned")]
public virtual System.Nullable<bool> IamOwned { get; set; }
/// <summary>
/// If more than one rule is specified, the rules are applied in the following manner: - All matching LOG rules
/// are always applied. - If any DENY/DENY_WITH_LOG rule matches, permission is denied. Logging will be applied
/// if one or more matching rule requires logging. - Otherwise, if any ALLOW/ALLOW_WITH_LOG rule matches,
/// permission is granted. Logging will be applied if one or more matching rule requires logging. - Otherwise,
/// if no rule applies, permission is denied.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("rules")]
public virtual System.Collections.Generic.IList<Rule> Rules { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>Response message for GameServerClustersService.PreviewCreateGameServerCluster.</summary>
public class PreviewCreateGameServerClusterResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The state of the Kubernetes cluster in preview, this will be available if 'view' is set to
/// `FULL` in the relevant List/Get/Preview request.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterState")]
public virtual KubernetesClusterState ClusterState { get; set; }
/// <summary>The ETag of the game server cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The target state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetState")]
public virtual TargetState TargetState { get; set; }
}
/// <summary>Response message for GameServerClustersService.PreviewDeleteGameServerCluster.</summary>
public class PreviewDeleteGameServerClusterResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the game server cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The target state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetState")]
public virtual TargetState TargetState { get; set; }
}
/// <summary>
/// Response message for PreviewGameServerDeploymentRollout. This has details about the Agones fleet and autoscaler
/// to be actuated.
/// </summary>
public class PreviewGameServerDeploymentRolloutResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the game server deployment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The target state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetState")]
public virtual TargetState TargetState { get; set; }
/// <summary>Locations that could not be reached on this request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unavailable")]
public virtual System.Collections.Generic.IList<string> Unavailable { get; set; }
}
/// <summary>Response message for RealmsService.PreviewRealmUpdate.</summary>
public class PreviewRealmUpdateResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the realm.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The target state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetState")]
public virtual TargetState TargetState { get; set; }
}
/// <summary>Response message for GameServerClustersService.PreviewUpdateGameServerCluster</summary>
public class PreviewUpdateGameServerClusterResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the game server cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The target state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetState")]
public virtual TargetState TargetState { get; set; }
}
/// <summary>A realm resource.</summary>
public class Realm : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The creation time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Human readable description of the realm.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The labels associated with this realm. Each label is a key-value pair.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// The resource name of the realm, in the following form:
/// `projects/{project}/locations/{location}/realms/{realm}`. For example,
/// `projects/my-project/locations/{location}/realms/my-realm`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Required. Time zone where all policies targeting this realm are evaluated. The value of this field must be
/// from the IANA time zone database: https://www.iana.org/time-zones.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeZone")]
public virtual string TimeZone { get; set; }
/// <summary>Output only. The last-modified time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
}
/// <summary>The realm selector, used to match realm resources.</summary>
public class RealmSelector : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of realms to match.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("realms")]
public virtual System.Collections.Generic.IList<string> Realms { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A rule to be applied in a Policy.</summary>
public class Rule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required</summary>
[Newtonsoft.Json.JsonPropertyAttribute("action")]
public virtual string Action { get; set; }
/// <summary>Additional restrictions that must be met. All conditions must pass for the rule to match.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("conditions")]
public virtual System.Collections.Generic.IList<Condition> Conditions { get; set; }
/// <summary>Human-readable description of the rule.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>
/// If one or more 'in' clauses are specified, the rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in at
/// least one of these entries.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("in")]
public virtual System.Collections.Generic.IList<string> In__ { get; set; }
/// <summary>The config returned to callers of CheckPolicy for any entries that match the LOG action.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logConfig")]
public virtual System.Collections.Generic.IList<LogConfig> LogConfig { get; set; }
/// <summary>
/// If one or more 'not_in' clauses are specified, the rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in
/// none of the entries. The format for in and not_in entries can be found at in the Local IAM documentation
/// (see go/local-iam#features).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notIn")]
public virtual System.Collections.Generic.IList<string> NotIn { get; set; }
/// <summary>
/// A permission is a string of form '..' (e.g., 'storage.buckets.list'). A value of '*' matches all
/// permissions, and a verb part of '*' (e.g., 'storage.buckets.*') matches all verbs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Autoscaling config for an Agones fleet.</summary>
public class ScalingConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. Agones fleet autoscaler spec. Example spec:
/// https://agones.dev/site/docs/reference/fleetautoscaler/
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetAutoscalerSpec")]
public virtual string FleetAutoscalerSpec { get; set; }
/// <summary>Required. The name of the Scaling Config</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The schedules to which this Scaling Config applies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("schedules")]
public virtual System.Collections.Generic.IList<Schedule> Schedules { get; set; }
/// <summary>
/// Labels used to identify the game server clusters to which this Agones scaling config applies. A game server
/// cluster is subject to this Agones scaling config if its labels match any of the selector entries.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("selectors")]
public virtual System.Collections.Generic.IList<LabelSelector> Selectors { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The schedule of a recurring or one time event. The event's time span is specified by start_time and end_time. If
/// the scheduled event's timespan is larger than the cron_spec + cron_job_duration, the event will be recurring. If
/// only cron_spec + cron_job_duration are specified, the event is effective starting at the local time specified by
/// cron_spec, and is recurring. start_time|-------[cron job]-------[cron job]-------[cron job]---|end_time cron
/// job: cron spec start time + duration
/// </summary>
public class Schedule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The duration for the cron job event. The duration of the event is effective after the cron job's start time.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cronJobDuration")]
public virtual object CronJobDuration { get; set; }
/// <summary>
/// The cron definition of the scheduled event. See https://en.wikipedia.org/wiki/Cron. Cron spec specifies the
/// local time as defined by the realm.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cronSpec")]
public virtual string CronSpec { get; set; }
/// <summary>The end time of the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>The start time of the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few
/// 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might
/// reject them.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>
/// OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be
/// modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulates Agones fleet spec and Agones autoscaler spec sources.</summary>
public class SpecSource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The game server config resource. Uses the form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}/configs/{config_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerConfigName")]
public virtual string GameServerConfigName { get; set; }
/// <summary>
/// The name of the Agones leet config or Agones scaling config used to derive the Agones fleet or Agones
/// autoscaler spec.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details about the Agones resources.</summary>
public class TargetDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Agones fleet details for game server clusters and game server deployments.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetDetails")]
public virtual System.Collections.Generic.IList<TargetFleetDetails> FleetDetails { get; set; }
/// <summary>
/// The game server cluster name. Uses the form:
/// `projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerClusterName")]
public virtual string GameServerClusterName { get; set; }
/// <summary>
/// The game server deployment name. Uses the form:
/// `projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gameServerDeploymentName")]
public virtual string GameServerDeploymentName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Target Agones fleet specification.</summary>
public class TargetFleet : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the Agones fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Encapsulates the source of the Agones fleet spec. The Agones fleet spec source.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("specSource")]
public virtual SpecSource SpecSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Target Agones autoscaler policy reference.</summary>
public class TargetFleetAutoscaler : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the Agones autoscaler.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Encapsulates the source of the Agones fleet spec. Details about the Agones autoscaler spec.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("specSource")]
public virtual SpecSource SpecSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details of the target Agones fleet.</summary>
public class TargetFleetDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Reference to target Agones fleet autoscaling policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("autoscaler")]
public virtual TargetFleetAutoscaler Autoscaler { get; set; }
/// <summary>Reference to target Agones fleet.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleet")]
public virtual TargetFleet Fleet { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulates the Target state.</summary>
public class TargetState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Details about Agones fleets.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<TargetDetails> Details { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*')
/// are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 53.454407 | 195 | 0.551129 | [
"Apache-2.0"
] | jskeet/google-api-dotnet-client | Src/Generated/Google.Apis.GameServices.v1/Google.Apis.GameServices.v1.cs | 246,211 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Autofac;
using Autofac.Core;
using Module = Autofac.Module;
namespace Orchard.Environment {
/// <summary>
/// Alter components instantiations by setting property values defined in a configuration file
/// </summary>
public class HostComponentsConfigModule : Module {
public static class XNames {
public const string Xmlns = "";
public static readonly XName HostComponents = XName.Get("HostComponents", Xmlns);
public static readonly XName Components = XName.Get("Components", Xmlns);
public static readonly XName Component = XName.Get("Component", Xmlns);
public static readonly XName Properties = XName.Get("Properties", Xmlns);
public static readonly XName Property = XName.Get("Property", Xmlns);
public static readonly XName Type = XName.Get("Type");
public static readonly XName Name = XName.Get("Name");
public static readonly XName Value = XName.Get("Value");
}
// component type name => list of [property name, property value]
public class PropertyEntry {
public string Name { get; set; }
public string Value { get; set; }
}
public readonly IDictionary<string, IEnumerable<PropertyEntry>> _config = new Dictionary<string, IEnumerable<PropertyEntry>>();
public HostComponentsConfigModule() {
// Called by the framework, as this class is a "Module"
}
public HostComponentsConfigModule(string fileName) {
var doc = XDocument.Load(fileName);
foreach (var component in doc.Elements(XNames.HostComponents).Elements(XNames.Components).Elements(XNames.Component)) {
var componentType = Attr(component, XNames.Type);
if (componentType == null)
continue;
var properties = component
.Elements(XNames.Properties)
.Elements(XNames.Property)
.Select(property => new PropertyEntry { Name = Attr(property, XNames.Name), Value = Attr(property, XNames.Value) })
.Where(t => !string.IsNullOrEmpty(t.Name) && !string.IsNullOrEmpty(t.Value))
.ToList();
if (!properties.Any())
continue;
_config.Add(componentType, properties);
}
}
private string Attr(XElement component, XName name) {
var attr = component.Attribute(name);
if (attr == null)
return null;
return attr.Value;
}
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) {
var implementationType = registration.Activator.LimitType;
IEnumerable<PropertyEntry> properties;
if (!_config.TryGetValue(implementationType.FullName, out properties))
return;
// build an array of actions on this type to assign loggers to member properties
var injectors = BuildPropertiesInjectors(implementationType, properties).ToArray();
// if there are no logger properties, there's no reason to hook the activated event
if (!injectors.Any())
return;
// otherwise, whan an instance of this component is activated, inject the loggers on the instance
registration.Activated += (s, e) => {
foreach (var injector in injectors)
injector(e.Context, e.Instance);
};
}
private IEnumerable<Action<IComponentContext, object>> BuildPropertiesInjectors(Type componentType, IEnumerable<PropertyEntry> properties) {
// Look for settable properties with name in "properties"
var settableProperties = componentType
.GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
.Select(p => new {
PropertyInfo = p,
IndexParameters = p.GetIndexParameters(),
Accessors = p.GetAccessors(false),
PropertyEntry = properties.Where(t => t.Name == p.Name).FirstOrDefault()
})
.Where(x => x.PropertyEntry != null) // Must be present in "properties"
.Where(x => x.IndexParameters.Count() == 0) // must not be an indexer
.Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); //must have get/set, or only set
// Return an array of actions that assign the property value
foreach (var entry in settableProperties) {
var propertyInfo = entry.PropertyInfo;
var propertyEntry = entry.PropertyEntry;
yield return (ctx, instance) => {
object value;
if (ChangeToCompatibleType(propertyEntry.Value, propertyInfo.PropertyType, out value))
propertyInfo.SetValue(instance, value, null);
};
}
}
public static bool ChangeToCompatibleType(string value, Type destinationType, out object result) {
if (string.IsNullOrEmpty(value)) {
result = null;
return false;
}
if (destinationType.IsInstanceOfType(value)) {
result = value;
return true;
}
try {
result = TypeDescriptor.GetConverter(destinationType).ConvertFrom(value);
return true;
}
catch {
result = null;
return false;
}
}
}
} | 44.79562 | 149 | 0.572918 | [
"BSD-3-Clause"
] | akovsh/Orchard | src/Orchard/Environment/HostComponentsConfigModule.cs | 6,139 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using ESRI.ArcGIS.Geometry;
using ProSuite.Commons.Essentials.Assertions;
using ProSuite.Commons.Essentials.CodeAnnotations;
namespace ProSuite.QA.Container.PolygonGrower
{
public class RingGrower<TDirectedRow> where TDirectedRow : class, ILineDirectedRow
{
private readonly Func<TDirectedRow, TDirectedRow> _revertFunc;
public event GeometryCompletedEventHandler<TDirectedRow> GeometryCompleted;
private const double _tolerance = 1e-5;
private readonly PathRowComparer _pathRowComparer;
private readonly DirectedRowComparer _directedPartComparer;
private readonly SortedDictionary<IDirectedRow, LineList<TDirectedRow>> _endRows;
private readonly SortedDictionary<IDirectedRow, LineList<TDirectedRow>> _startRows;
public RingGrower([NotNull] Func<TDirectedRow, TDirectedRow> revertFunc)
{
_revertFunc = revertFunc;
_pathRowComparer = new PathRowComparer(new TableIndexRowComparer());
_directedPartComparer = new DirectedRowComparer(_pathRowComparer.RowComparer);
_startRows =
new SortedDictionary<IDirectedRow, LineList<TDirectedRow>>(_directedPartComparer);
_endRows =
new SortedDictionary<IDirectedRow, LineList<TDirectedRow>>(_directedPartComparer);
}
public IEnumerable<LineList<TDirectedRow>> GetLineLists()
{
foreach (LineList<TDirectedRow> lines in _endRows.Values)
{
yield return lines;
}
}
[NotNull]
public LineList<TDirectedRow> Add([NotNull] TDirectedRow row0,
[NotNull] TDirectedRow row1)
{
try
{
LineList<TDirectedRow> pre;
LineList<TDirectedRow> post;
if (_endRows.TryGetValue(row0, out pre))
{
_endRows.Remove(row0);
}
if (_startRows.TryGetValue(row1, out post))
{
_startRows.Remove(row1);
}
if (pre == null && post == null)
{
if (_directedPartComparer.Equals(row0, row1))
//if (row0.TopoLine == row1.TopoLine && row0.IsBackward == row1.IsBackward)
{
pre = new LineList<TDirectedRow>(row0, _pathRowComparer);
pre.Completed();
OnClosing(pre);
return pre;
}
pre = new LineList<TDirectedRow>(row0, row1, _pathRowComparer);
_startRows.Add(row0, pre);
_endRows.Add(row1, pre);
return pre;
}
if (pre == null)
{
post.AddRow(row0, true);
_startRows.Add(row0, post);
return post;
}
if (post == null)
{
pre.AddRow(row1, false);
_endRows.Add(row1, pre);
return pre;
}
if (pre == post) // Polygon completed
{
pre.Completed();
OnClosing(pre);
return pre;
}
pre.AddCollection(post);
IDirectedRow z = pre.DirectedRows.Last.Value;
// updating _endRows,
Assert.True(z == post.DirectedRows.Last.Value, "unexpected directed row");
Assert.True(_endRows[z] == post, "unexpected end rows");
_endRows[z] = pre;
return pre;
}
catch (Exception exception)
{
throw new InvalidOperationException(
$"Error adding pair 0(uniqueOID:{row0.Row.RowOID}, {row0.Row}); 1(uniqueOID:'{row1.Row.RowOID}', {row1.Row})",
exception);
}
}
private void OnClosing(LineList<TDirectedRow> closedPolygon)
{
if (GeometryCompleted != null)
{
GeometryCompleted(this, closedPolygon);
}
}
public void ResolvePoint(IPoint point,
[NotNull] List<TDirectedRow> intersectList,
TDirectedRow row)
{
if (intersectList.Count > 1)
{
var comparer = (IComparer<TDirectedRow>) new DirectedRow.RowByLineAngleComparer();
intersectList.Sort(comparer);
int index = intersectList.BinarySearch(row);
ResolvePoint(point, intersectList, index);
}
else if (intersectList.Count != 0)
{
ResolvePoint(point, intersectList, 0);
}
}
/// <summary>
///
/// </summary>
/// <param name="point"> the point to be resolved</param>
/// <param name="intersectList"> an array listing the lines to the point in counterclockwise order. first line appears twice</param>
/// <param name="index"> the index of the current row in the array</param>
private void ResolvePoint(IPoint point,
[NotNull] IList<TDirectedRow> intersectList,
int index)
{
if (intersectList.Count < 2)
{
Add(_revertFunc(intersectList[0]), intersectList[0]);
return;
}
TDirectedRow middleRow = intersectList[index];
TDirectedRow rightRow = index < intersectList.Count - 1
? intersectList[index + 1]
: intersectList[0];
TDirectedRow leftRow = index == 0
? intersectList[intersectList.Count - 1]
: intersectList[index - 1];
if (_pathRowComparer.Compare(middleRow, rightRow) < 0)
{
Add(_revertFunc(middleRow), rightRow);
}
if (_pathRowComparer.Compare(middleRow, leftRow) < 0)
{
Add(_revertFunc(leftRow), middleRow);
}
}
[NotNull]
public List<LineList<TDirectedRow>> GetAndRemoveCollectionsInside(
[CanBeNull] IEnvelope envelope)
{
var insideList = new List<LineList<TDirectedRow>>();
if (envelope == null || envelope.IsEmpty)
{
insideList.AddRange(_startRows.Select(pair => pair.Value));
}
else
{
double envXMin;
double envYMin;
double envXMax;
double envYMax;
envelope.QueryCoords(out envXMin, out envYMin,
out envXMax, out envYMax);
foreach (KeyValuePair<IDirectedRow, LineList<TDirectedRow>> pair in _startRows)
{
IEnvelope polyEnvelope = pair.Value.Envelope();
Assert.NotNull(polyEnvelope, "polygon envelope is null");
double polyXMin;
double polyYMin;
double polyXMax;
double polyYMax;
polyEnvelope.QueryCoords(out polyXMin, out polyYMin,
out polyXMax, out polyYMax);
if (polyXMin + _tolerance >= envXMin &&
polyYMin + _tolerance >= envYMin &&
polyXMax - _tolerance <= envXMax &&
polyYMax - _tolerance <= envYMax)
{
insideList.Add(pair.Value);
}
}
}
foreach (LineList<TDirectedRow> poly in insideList)
{
_startRows.Remove(poly.DirectedRows.First.Value);
_endRows.Remove(poly.DirectedRows.Last.Value);
}
return insideList;
}
}
}
| 27.131915 | 134 | 0.654015 | [
"MIT"
] | ProSuite/ProSuite | src/ProSuite.QA.Container/PolygonGrower/RingGrower.cs | 6,376 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace TextOverflow
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 38.851485 | 99 | 0.614424 | [
"MIT"
] | Bazzaware/ProfessionalCSharp7 | AdvancedWindows/TextOverflow/TextOverflow/App.xaml.cs | 3,926 | C# |
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TagCanvas.Extensions
{
public static class ContainerExtensions
{
public static ContainerBuilder Register<I, Impl>(this ContainerBuilder builder, bool singleInstance = false) where Impl : I
{
var intermediate = builder.RegisterType<Impl>();
if (singleInstance)
{
intermediate = intermediate.SingleInstance();
}
intermediate.As<I>();
return builder;
}
}
}
| 23.961538 | 131 | 0.629213 | [
"MIT"
] | ddadaal/TagCanvas | TagCanvas/Extensions/ContainerExtensions.cs | 625 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Bot.Schema
{
using System;
using Newtonsoft.Json;
/// <summary>
/// Indicates what the payment request is for and the value asked for.
/// </summary>
[Obsolete("Bot Framework no longer supports payments.")]
public partial class PaymentItem
{
/// <summary>
/// Initializes a new instance of the <see cref="PaymentItem"/> class.
/// </summary>
public PaymentItem()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the <see cref="PaymentItem"/> class.
/// </summary>
/// <param name="label">Human-readable description of the item.</param>
/// <param name="amount">Monetary amount for the item.</param>
/// <param name="pending">When set to true this flag means that the
/// amount field is not final.</param>
public PaymentItem(string label = default(string), PaymentCurrencyAmount amount = default(PaymentCurrencyAmount), bool? pending = default(bool?))
{
Label = label;
Amount = amount;
Pending = pending;
CustomInit();
}
/// <summary>
/// Gets or sets human-readable description of the item.
/// </summary>
/// <value>The human-readable label of the item.</value>
[JsonProperty(PropertyName = "label")]
public string Label { get; set; }
/// <summary>
/// Gets or sets monetary amount for the item.
/// </summary>
/// <value>The amount for the item.</value>
[JsonProperty(PropertyName = "amount")]
public PaymentCurrencyAmount Amount { get; set; }
/// <summary>
/// Gets or sets when set to true this flag means that the amount field
/// is not final.
/// </summary>
/// <value>A boolean indicating that amount in field is pending (i.e. not final).</value>
[JsonProperty(PropertyName = "pending")]
public bool? Pending { get; set; }
/// <summary>
/// An initialization method that performs custom operations like setting defaults.
/// </summary>
partial void CustomInit();
}
}
| 35.227273 | 153 | 0.584086 | [
"MIT"
] | Alpharceus/botbuilder-dotnet | libraries/Microsoft.Bot.Schema/PaymentItem.cs | 2,327 | C# |
// PennyLogger: Log event aggregation and filtering library
// See LICENSE in the project root for license information.
using Xunit;
namespace PennyLogger.Internals.Estimator.Cuckoo.UnitTests
{
/// <summary>
/// Tests the various classes derived from <see cref="ICuckooBucket"/>
/// </summary>
public class CuckooBucketTest
{
private static void Test(ICuckooBucket bucket, int expectedSize, bool counting)
{
// The default value should be empty
Assert.True(bucket.IsEmpty);
// The size is the expected value
Assert.Equal(expectedSize, bucket.SizeOf);
// Read and write max values
bucket.Fingerprint = bucket.MaxFingerprint;
bucket.Count = bucket.MaxCount;
Assert.Equal(bucket.MaxFingerprint, bucket.Fingerprint);
Assert.Equal(bucket.MaxCount, bucket.Count);
// Read and write zeroes
bucket.Fingerprint = 0UL;
Assert.Equal(0UL, bucket.Fingerprint);
Assert.Equal(bucket.MaxCount, bucket.Count);
if (counting)
{
bucket.Count = 0UL;
Assert.Equal(0UL, bucket.Fingerprint);
Assert.Equal(0UL, bucket.Count);
}
}
/// <summary>
/// Test <see cref="CuckooBucket8"/>
/// </summary>
[Fact]
public void CuckooBucket8()
{
Test(new CuckooBucket8(), 1, false);
}
/// <summary>
/// Test <see cref="CuckooBucket16Counting"/>
/// </summary>
[Fact]
public void CuckooBucket16Counting()
{
Test(new CuckooBucket16Counting(), 2, true);
}
/// <summary>
/// Test <see cref="CuckooBucket64Counting"/>
/// </summary>
[Fact]
public void CuckooBucket64Counting()
{
Test(new CuckooBucket64Counting(), 8, true);
}
}
}
| 29.25 | 87 | 0.557064 | [
"MIT"
] | leosingleton/pennylogger | src/PennyLogger.UnitTests/Internals/Estimator/Cuckoo/CuckooBucketTest.cs | 1,991 | C# |
// Decompiled with JetBrains decompiler
// Type: Diga.WebView2.Interop.ICoreWebView2WebResourceResponseReceivedEventHandler
// Assembly: Diga.WebView2.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: AAF9543A-0FE1-46E7-BB2C-D24EA0535C0F
// Assembly location: O:\webview2\v1077444\Diga.WebView2.Interop.dll
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Diga.WebView2.Interop
{
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("7DE9898A-24F5-40C3-A2DE-D4F458E69828")]
[ComImport]
public interface ICoreWebView2WebResourceResponseReceivedEventHandler
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Invoke(
[MarshalAs(UnmanagedType.Interface), In] ICoreWebView2 sender,
[MarshalAs(UnmanagedType.Interface), In] ICoreWebView2WebResourceResponseReceivedEventArgs args);
}
}
| 40.173913 | 103 | 0.807359 | [
"MIT"
] | ITAgnesmeyer/Diga.WebView2 | Archive/V1077444/Diga.WebView2.Interop.V1077444/ICoreWebView2WebResourceResponseReceivedEventHandl.cs | 926 | C# |
using FluentAssertions;
using Xunit;
namespace NRamdaLib.Tests
{
public class AddTests
{
[Fact]
public void CanAddTwoInts()
{
NRamda.Add(2, 5).Should().Be(2 + 5);
}
[Fact]
public void CanAddTwoFloats()
{
NRamda.Add(3.345f, 243.342f).Should().Be(3.345f + 243.342f);
}
[Fact]
public void CanAddTwoDoubles()
{
NRamda.Add(3.345d, 243.342d).Should().Be(3.345d + 243.342d);
}
[Fact]
public void CanAddTwoDecimals()
{
NRamda.Add(50.45m, 243.42m).Should().Be(50.45m + 243.42m);
}
[Fact]
public void CanAddTwoIntsWithPartialApplication()
{
NRamda.Add(2)(5).Should().Be(2 + 5);
}
[Fact]
public void CanAddTwoFloatsWithPartialApplication()
{
NRamda.Add(3.345f)(243.342f).Should().Be(3.345f + 243.342f);
}
[Fact]
public void CanAddTwoDoublesWithPartialApplication()
{
NRamda.Add(3.345d)(243.342d).Should().Be(3.345d + 243.342d);
}
[Fact]
public void CanAddTwoDecimalsWithPartialApplication()
{
NRamda.Add(50.45m)(243.42m).Should().Be(50.45m + 243.42m);
}
}
}
| 23.157895 | 72 | 0.514394 | [
"MIT"
] | GrahamClark/NRamda | src/NRamdaLib.Tests/AddTests.cs | 1,322 | C# |
/*
Copyright 2007-2017 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the MIT License. You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at https://opensource.org/licenses/MIT.
*/
using System;
using NGenerics.DataStructures.Mathematical;
using NUnit.Framework;
namespace NGenerics.Tests.DataStructures.Mathematical.Vector3DTests
{
[TestFixture]
public class LessThanOperator
{
[Test]
public void Simple()
{
var vector1 = new Vector3D(1, 1, 1);
var vector2 = new Vector3D(2, 2, 2);
var vector3 = new Vector3D(2, 2, 2);
Assert.IsTrue(vector1 < vector2);
Assert.IsFalse(vector2 < vector1);
Assert.IsFalse(vector2 < vector3);
}
[Test]
public void ExceptionLeftNull()
{
const Vector3D vector1 = null;
var vector2 = new Vector3D(2, 2, 2);
bool condition;
Assert.Throws<ArgumentNullException>(() => condition = vector1 < vector2);
}
[Test]
public void ExceptionRightNull()
{
var vector1 = new Vector3D(2, 2, 2);
const Vector3D vector2 = null;
bool condition;
Assert.Throws<ArgumentNullException>(() => condition = vector1 < vector2);
}
}
} | 28.666667 | 88 | 0.602599 | [
"MIT"
] | ngenerics/ngenerics | src/NGenerics.Tests/DataStructures/Mathematical/Vector3DTests/LessThanOperator.cs | 1,462 | 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("File Searcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("File Searcher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("1769c2da-55f7-441a-9094-fa4251c439cf")]
// 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.783784 | 85 | 0.725436 | [
"MIT"
] | Retrobyte/File-Searcher | File Searcher/Properties/AssemblyInfo.cs | 1,438 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Roslynator.CSharp.Helpers;
namespace Roslynator.CSharp.Refactorings
{
internal static class CommentTriviaRefactoring
{
public static void ComputeRefactorings(RefactoringContext context, SyntaxTrivia trivia)
{
SyntaxKind kind = trivia.Kind();
if (context.IsRootCompilationUnit
&& trivia.FullSpan.Contains(context.Span)
&& CSharpFacts.IsCommentTrivia(kind))
{
if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveComment))
{
context.RegisterRefactoring(
"Remove comment",
cancellationToken =>
{
SyntaxToken newToken = RemoveCommentHelper.GetReplacementToken(trivia).WithFormatterAnnotation();
return context.Document.ReplaceTokenAsync(trivia.Token, newToken, cancellationToken);
},
RefactoringIdentifiers.RemoveComment);
}
if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllComments))
{
context.RegisterRefactoring(
"Remove all comments",
cancellationToken => context.Document.RemoveCommentsAsync(CommentKinds.All, cancellationToken),
RefactoringIdentifiers.RemoveAllComments);
}
if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllCommentsExceptDocumentationComments)
&& kind.Is(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia))
{
context.RegisterRefactoring(
"Remove all comments (except documentation comments)",
cancellationToken => context.Document.RemoveCommentsAsync(CommentKinds.NonDocumentation, cancellationToken),
RefactoringIdentifiers.RemoveAllCommentsExceptDocumentationComments);
}
if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllDocumentationComments)
&& SyntaxFacts.IsDocumentationCommentTrivia(kind))
{
context.RegisterRefactoring(
"Remove all documentation comments",
cancellationToken => context.Document.RemoveCommentsAsync(CommentKinds.Documentation, cancellationToken),
RefactoringIdentifiers.RemoveAllDocumentationComments);
}
}
}
public static void ComputeRefactorings(RefactoringContext context, SyntaxNode node)
{
if (context.IsAnyRefactoringEnabled(
RefactoringIdentifiers.RemoveAllComments,
RefactoringIdentifiers.RemoveAllCommentsExceptDocumentationComments,
RefactoringIdentifiers.RemoveAllDocumentationComments))
{
bool fComment = false;
bool fDocComment = false;
foreach (SyntaxTrivia trivia in node.DescendantTrivia(context.Span, descendIntoTrivia: true))
{
if (fComment && fDocComment)
break;
if (context.Span.Contains(trivia.Span))
{
switch (trivia.Kind())
{
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
{
fComment = true;
break;
}
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.MultiLineDocumentationCommentTrivia:
{
fDocComment = true;
break;
}
}
}
}
if (fComment
&& context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllComments))
{
context.RegisterRefactoring(
"Remove comments",
cancellationToken => context.Document.RemoveCommentsAsync(context.Span, CommentKinds.All, cancellationToken),
RefactoringIdentifiers.RemoveAllComments);
}
if (fComment
&& fDocComment
&& context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllCommentsExceptDocumentationComments))
{
context.RegisterRefactoring(
"Remove comments (except documentation comments)",
cancellationToken => context.Document.RemoveCommentsAsync(context.Span, CommentKinds.NonDocumentation, cancellationToken),
RefactoringIdentifiers.RemoveAllCommentsExceptDocumentationComments);
}
if (fDocComment
&& context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllDocumentationComments))
{
context.RegisterRefactoring(
"Remove documentation comments",
c => context.Document.RemoveCommentsAsync(context.Span, CommentKinds.Documentation, c),
RefactoringIdentifiers.RemoveAllDocumentationComments);
}
}
}
}
} | 47.656 | 160 | 0.552291 | [
"Apache-2.0"
] | IanKemp/Roslynator | src/Refactorings/CSharp/Refactorings/CommentTriviaRefactoring.cs | 5,959 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trollkit_Library
{
public static class SharedProperties
{
public const int BroadcastPort = 9696;
public const int MainPort = 6969;
public const int DataSize = 1048576; //524288; //2048;
public const int TypeByte = 0;
public const int LengthByte1 = 1;
public const int LengthByte2 = 2;
public const int SeriesByte1 = 3;
public const int SeriesByte2 = 4;
public const int GuidStartByte = 5; // 16 bytes long
public const int HeaderByteSize = 21; //top results into 21
public static int DataLength { get { return DataSize - HeaderByteSize; } }
}
}
| 26.923077 | 76 | 0.738571 | [
"MIT"
] | brann0n/Remote-Access-Trollkit | Trollkit Library/SharedProperties.cs | 702 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using Tardigrade.Framework.EntityFrameworkCore.Data;
namespace Tardigrade.Framework.EntityFrameworkCore.Configurations
{
/// <summary>
/// ConfigurationProvider that reads application settings from a database.
/// <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0#custom-configuration-provider">Custom configuration provider</a>
/// </summary>
public class AppSettingsConfigurationProvider : ConfigurationProvider
{
private Action<DbContextOptionsBuilder> OptionsAction { get; }
/// <summary>
/// Create an instance of this class.
/// </summary>
/// <param name="optionsAction">Options associated with the database context.</param>
public AppSettingsConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
{
OptionsAction = optionsAction;
}
/// <inheritdoc/>
public override void Load()
{
var builder = new DbContextOptionsBuilder<AppSettingsDbContext>();
OptionsAction(builder);
using var dbContext = new AppSettingsDbContext(builder.Options);
Data = dbContext.AppSettings.ToDictionary(a => a.Id, a => a.Value);
}
}
} | 39.514286 | 174 | 0.689805 | [
"Apache-2.0"
] | CaptainMesomorph/tardigrade-framework | Code/Tardigrade.Framework/Tardigrade.Framework.EntityFrameworkCore/Configurations/AppSettingsConfigurationProvider.cs | 1,385 | C# |
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseController : MyBehaviour,
IEventReceiver<OnPlayerDeath>,
IEventReceiver<OnPlayerRespawned>,
IEventReceiver<OnLevelBeganSwitching>,
IEventReceiver<OnLevelFinishedSwitching>
{
public bool isPaused { get; private set; }
private float initialTimeScale = 1f;
void Update()
{
if (!Input.GetButtonDown("Pause")) return;
if (isPaused) Unpause();
else Pause();
}
public void On(OnPlayerDeath message) => enabled = false;
public void On(OnPlayerRespawned message) => enabled = true;
public void On(OnLevelBeganSwitching message) => enabled = false;
public void On(OnLevelFinishedSwitching message) => enabled = true;
protected override void OnDestroy()
{
base.OnDestroy();
Unpause();
}
public void Pause()
{
if (isPaused) return;
initialTimeScale = Time.timeScale;
Time.timeScale = 0f;
isPaused = true;
new OnPause().SetDeliveryType(MessageDeliveryType.Immediate).PostEvent();
}
public void Unpause()
{
if (!isPaused) return;
Time.timeScale = initialTimeScale;
isPaused = false;
new OnUnpause().SetDeliveryType(MessageDeliveryType.Immediate).PostEvent();
}
} | 26.053571 | 84 | 0.601782 | [
"MIT"
] | maksmaisak/Saxion_Y2Q1_Project_Clients_Call | Assets/_Own/Scripts/PauseController.cs | 1,459 | C# |
using System;
using System.Drawing;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Attributes;
using DotNet.Highcharts.Helpers;
namespace DotNet.Highcharts.Options
{
/// <summary>
/// The appearance of the point marker when selected. In order to allow a point to be selected, set the <code>series.allowPointSelect</code> option to true.
/// </summary>
public class PlotOptionsAreaMarkerStatesSelect
{
/// <summary>
/// Enable or disable visible feedback for selection.
/// Default: true
/// </summary>
public bool? Enabled { get; set; }
/// <summary>
/// The fill color of the point marker.
/// </summary>
public Color? FillColor { get; set; }
/// <summary>
/// The color of the point marker's outline. When <code>null</code>, the series' or point's color is used.
/// Default: #000000
/// </summary>
public Color? LineColor { get; set; }
/// <summary>
/// The width of the point marker's outline.
/// Default: 0
/// </summary>
public Number? LineWidth { get; set; }
/// <summary>
/// The radius of the point marker. In hover state, it defaults to the normal state's radius + 2.
/// </summary>
public Number? Radius { get; set; }
}
} | 27.295455 | 158 | 0.667777 | [
"MIT"
] | juniorgasparotto/SpentBook | samples/dotnethighcharts-28017/DotNet.Highcharts/DotNet.Highcharts/Options/PlotOptionsAreaMarkerStatesSelect.cs | 1,201 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Rendering;
using InputCustom;
namespace GameLogic
{
public enum EChessBoardSlot
{
E_OutOfRange = 0,
E_Empty = 1,
E_Full = 2,
}
public class ChessBoard
{
public bool[,] slotStateArray;
private BlockBase curBlock;
private List<BlockPos> stableBlockList = new List<BlockPos>();
private List<int> reduceLines = new List<int>();
private ChessBoardRender mChessBoardRender;
public ChessBoard()
{
int width = GameConfig.Instance.Width;
int height = GameConfig.Instance.Height;
slotStateArray = new bool[height, width];
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
slotStateArray[y, x] = false;
}
}
mChessBoardRender = ChessBoardRender.Instance;
}
public EChessBoardSlot GetSlotState(int x, int y)
{
if (x < 0 || x >= GameConfig.Instance.Width ||
y < 0 || y >= GameConfig.Instance.Height)
{
return EChessBoardSlot.E_OutOfRange;
}
if (slotStateArray [y, x])
{
return EChessBoardSlot.E_Full;
}
else
{
return EChessBoardSlot.E_Empty;
}
}
public void SetCurFallBlock(BlockBase newBlock)
{
curBlock = newBlock;
SetBoardSlotState(curBlock.GetPointList(), true);
}
public void SetBoardSlotState(List<BlockPos> posList, bool isOccupy)
{
bool value = isOccupy ? true : false;
for (int i = 0; i < posList.Count; ++i)
{
slotStateArray[posList[i].y, posList[i].x] = value;
}
}
public void UpdateBoard()
{
mChessBoardRender.Rendering(curBlock.GetPointList(), stableBlockList);
}
public void RotateBlock()
{
SetBoardSlotState(curBlock.GetPointList(), false);
curBlock.RotBlock();
SetBoardSlotState(curBlock.GetPointList(), true);
LogDebug.Log("RotateBlock");
}
public void HorizonMoveBlock(ESlideDirection direction)
{
List<BlockPos> posList = curBlock.GetPointList();
SetBoardSlotState(posList, false);
int offset = direction == ESlideDirection.E_Left ? -1 : 1;
for (int i = 0; i < posList.Count; ++i)
{
posList[i].x += offset;
}
curBlock.GetAncholBlockPos().x += offset;
SetBoardSlotState(posList, true);
}
public bool FallBlock()
{
List<BlockPos> posList = curBlock.GetPointList();
bool rlt = false ;
stableBlockList.Clear();
SetBoardSlotState(posList, false);
if (CanVerticalFall(posList))
{
for (int i = 0; i < posList.Count; ++i)
{
--posList[i].y;
}
curBlock.GetAncholBlockPos().y -= 1;
}
else
{
rlt = true;
stableBlockList.AddRange(posList);
}
SetBoardSlotState(posList, true);
return rlt;
}
public bool ReduceLine()
{
reduceLines.Clear();
for (int y = 0; y < GameConfig.Instance.Height; ++y)
{
bool bCanReduce = true;
for (int x = 0; x < GameConfig.Instance.Width; ++x)
{
if (slotStateArray[y, x] == false)
{
bCanReduce = false;
break;
}
}
if (bCanReduce)
{
reduceLines.Add(y);
}
}
if (reduceLines.Count > 0)
{
for (int i = 0; i < reduceLines.Count; ++i)
{
for (int y = reduceLines[i]; y < GameConfig.Instance.Height - 1; ++y)
{
for (int x = 0; x < GameConfig.Instance.Width; ++x)
{
slotStateArray[y, x] = slotStateArray[y + 1, x];
}
}
}
stableBlockList.Clear();
for (int y = 0; y < GameConfig.Instance.Height; ++y)
{
for (int x = 0; x < GameConfig.Instance.Width; ++x)
{
if (slotStateArray[y, x])
{
stableBlockList.Add(new BlockPos(x, y));
}
}
}
return true;
}
return false;
}
public void UpdateReduce()
{
mChessBoardRender.RenderingForReduce(reduceLines);
}
public List<int> GetReduceLine()
{
return reduceLines;
}
private bool CanVerticalFall(List<BlockPos> posList)
{
for (int k = 0; k < posList.Count; ++k)
{
if (posList[k].y == 0)
{
return false;
}
if (slotStateArray[posList[k].y - 1, posList[k].x])
{
return false;
}
}
return true;
}
public int GetHeight()
{
int maxHeight = 0;
for (int y = 0; y <GameConfig.Instance.Height; ++y)
{
for (int x = 0; x < GameConfig.Instance.Width; ++x)
{
if (slotStateArray[y, x] && y > maxHeight)
{
maxHeight = y;
}
}
}
return maxHeight;
}
}
}
| 27.600877 | 89 | 0.426823 | [
"MIT"
] | 954818696/Game-Kaleidoscope | Game/Tetris/Assets/Resources/Script/GameLogic/ChessBoard.cs | 6,295 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("TestAppHSP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestAppHSP")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("00922359-2925-458b-92e2-b2640add5a6c")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// indem Sie "*" wie unten gezeigt eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.648649 | 106 | 0.763963 | [
"MIT"
] | MarvinTjarksJadeHS/Hello_World | TestAppHSP/TestAppHSP/Properties/AssemblyInfo.cs | 1,519 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace DCL_Core.CORE
{
// Implements https://en.bitcoin.it/wiki/Base58Check_encoding
// Ipmlementation of https://gist.github.com/CodesInChaos/3175971
public static class Base58Encoding
{
public const int CheckSumSizeInBytes = 4;
public static byte[] AddCheckSum(byte[] data)
{
//Contract.Requires<ArgumentNullException>(data != null);
//Contract.Ensures(Contract.Result<byte[]>().Length == data.Length + CheckSumSizeInBytes);
byte[] checkSum = GetCheckSum(data);
byte[] dataWithCheckSum = ArrayHelpers.ConcatArrays(data, checkSum);
return dataWithCheckSum;
}
//Returns null if the checksum is invalid
public static byte[] VerifyAndRemoveCheckSum(byte[] data)
{
//Contract.Requires<ArgumentNullException>(data != null);
//Contract.Ensures(Contract.Result<byte[]>() == null || Contract.Result<byte[]>().Length + CheckSumSizeInBytes == data.Length);
byte[] result = ArrayHelpers.SubArray(data, 0, data.Length - CheckSumSizeInBytes);
byte[] givenCheckSum = ArrayHelpers.SubArray(data, data.Length - CheckSumSizeInBytes);
byte[] correctCheckSum = GetCheckSum(result);
if (givenCheckSum.SequenceEqual(correctCheckSum))
return result;
else
return null;
}
private const string Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
public static string Encode(byte[] data)
{
//Contract.Requires<ArgumentNullException>(data != null);
//Contract.Ensures(Contract.Result<string>() != null);
// Decode byte[] to BigInteger
BigInteger intData = 0;
for (int i = 0; i < data.Length; i++)
{
intData = intData * 256 + data[i];
}
// Encode BigInteger to Base58 string
string result = "";
while (intData > 0)
{
int remainder = (int)(intData % 58);
intData /= 58;
result = Digits[remainder] + result;
}
// Append `1` for each leading 0 byte
for (int i = 0; i < data.Length && data[i] == 0; i++)
{
result = '1' + result;
}
return result;
}
public static string EncodeWithCheckSum(byte[] data)
{
//Contract.Requires<ArgumentNullException>(data != null);
//Contract.Ensures(Contract.Result<string>() != null);
return Encode(AddCheckSum(data));
}
public static byte[] Decode(string s)
{
//Contract.Requires<ArgumentNullException>(s != null);
//Contract.Ensures(Contract.Result<byte[]>() != null);
// Decode Base58 string to BigInteger
BigInteger intData = 0;
for (int i = 0; i < s.Length; i++)
{
int digit = Digits.IndexOf(s[i]); //Slow
if (digit < 0)
throw new FormatException(string.Format("Invalid Base58 character `{0}` at position {1}", s[i], i));
intData = intData * 58 + digit;
}
// Encode BigInteger to byte[]
// Leading zero bytes get encoded as leading `1` characters
int leadingZeroCount = s.TakeWhile(c => c == '1').Count();
var leadingZeros = Enumerable.Repeat((byte)0, leadingZeroCount);
var bytesWithoutLeadingZeros =
intData.ToByteArray()
.Reverse()// to big endian
.SkipWhile(b => b == 0);//strip sign byte
var result = leadingZeros.Concat(bytesWithoutLeadingZeros).ToArray();
return result;
}
// Throws `FormatException` if s is not a valid Base58 string, or the checksum is invalid
public static byte[] DecodeWithCheckSum(string s)
{
//Contract.Requires<ArgumentNullException>(s != null);
//Contract.Ensures(Contract.Result<byte[]>() != null);
var dataWithCheckSum = Decode(s);
var dataWithoutCheckSum = VerifyAndRemoveCheckSum(dataWithCheckSum);
if (dataWithoutCheckSum == null)
throw new FormatException("Base58 checksum is invalid");
return dataWithoutCheckSum;
}
private static byte[] GetCheckSum(byte[] data)
{
//Contract.Requires<ArgumentNullException>(data != null);
//Contract.Ensures(Contract.Result<byte[]>() != null);
SHA256 sha256 = new SHA256Managed();
byte[] hash1 = sha256.ComputeHash(data);
byte[] hash2 = sha256.ComputeHash(hash1);
var result = new byte[CheckSumSizeInBytes];
Buffer.BlockCopy(hash2, 0, result, 0, result.Length);
return result;
}
}
} | 39.067669 | 139 | 0.573711 | [
"MIT"
] | JohnJohnssonnl/DCL | DCL_Core/CORE/Base58Encoding.cs | 5,198 | C# |
namespace WeatherApiInteraction.DarkSkyWeatherMining
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class DarkSkyWeatherResultsList
{
public double latitude { get; set; }
public double longitude { get; set; }
public string timezone { get; set; }
public Hourly hourly { get; set; }
public Daily daily { get; set; }
public Flags flags { get; set; }
public int offset { get; set; }
}
public class HourlyDatum
{
public int time { get; set; }
public DateTime dateTime { get; set; }
public string summary { get; set; }
public string icon { get; set; }
public string precipType { get; set; }
public double temperature { get; set; }
public double apparentTemperature { get; set; }
public double dewPoint { get; set; }
public double humidity { get; set; }
public double windSpeed { get; set; }
public double windBearing { get; set; }
public double visibility { get; set; }
public double? pressure { get; set; }
public double? cloudCover { get; set; }
}
public class Hourly
{
public string summary { get; set; }
public string icon { get; set; }
public IList<HourlyDatum> data { get; set; }
}
public class Datum
{
public int time { get; set; }
public DateTime dateTime { get; set; }
public string summary { get; set; }
public string icon { get; set; }
public int sunriseTime { get; set; }
public DateTime sunriseTimeDateTime { get; set; }
public int sunsetTime { get; set; }
public DateTime sunsetTimeDateTime { get; set; }
public double moonPhase { get; set; }
public double precipAccumulation { get; set; }
public string precipType { get; set; }
public double temperatureHigh { get; set; }
public double temperatureHighTime { get; set; }
public DateTime temperatureHighTimeDateTime { get; set; }
public double temperatureLow { get; set; }
public double temperatureLowTime { get; set; }
public DateTime temperatureLowTimeDateTime { get; set; }
public double apparentTemperatureHigh { get; set; }
public double apparentTemperatureHighTime { get; set; }
public DateTime apparentTemperatureHighTimeDateTime { get; set; }
public double apparentTemperatureLow { get; set; }
public double apparentTemperatureLowTime { get; set; }
public DateTime apparentTemperatureLowTimeDateTime { get; set; }
public double dewPoint { get; set; }
public double humidity { get; set; }
public double pressure { get; set; }
public double windSpeed { get; set; }
public double windBearing { get; set; }
public double cloudCover { get; set; }
public double visibility { get; set; }
public double temperatureMin { get; set; }
public double temperatureMinTime { get; set; }
public DateTime temperatureMinTimeDateTime { get; set; }
public double temperatureMax { get; set; }
public double temperatureMaxTime { get; set; }
public DateTime temperatureMaxTimeDateTime { get; set; }
public double apparentTemperatureMin { get; set; }
public double apparentTemperatureMinTime { get; set; }
public DateTime apparentTemperatureMinTimeDateTime { get; set; }
public double apparentTemperatureMax { get; set; }
public double apparentTemperatureMaxTime { get; set; }
public DateTime apparentTemperatureMaxTimeDateTime { get; set; }
}
public class Daily
{
public IList<Datum> data { get; set; }
}
public class Flags
{
public IList<string> sources { get; set; }
[JsonProperty("isd-stations")]
public IList<string> isdstations { get; set; }
public string units { get; set; }
}
}
| 32.328 | 73 | 0.621133 | [
"MIT"
] | Bhaskers-Blu-Org2/Smart-Energy-Foundation-Demo-Stack | SmartEnergyAzureDemo/WeatherDataMining/WeatherApiInteraction/DarkSkyWeatherMining/DarkSkyWeatherDataQueryClasses.cs | 4,043 | C# |
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace MsgPackBlazor.Server.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.892857 | 88 | 0.664828 | [
"MIT"
] | lolochristen/MessagePack.WebApi.Client | samples/MsgPackBlazor/MsgPackBlazor/Server/Pages/Error.cshtml.cs | 727 | 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("BabaTincheAirlines")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BabaTincheAirlines")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("ba906658-65ec-4653-a263-5c9ba247b93b")]
// 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.081081 | 84 | 0.747339 | [
"MIT"
] | PAFICH/cSHARP | Exam-Preparation-1st-Problems/BabaTincheAirlines/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Parking
{
public class Parking
{
private List<Car> data;
public Parking(string type, int capacity)
{
data = new List<Car>(Capacity);
Type = type;
Capacity = capacity;
}
public string Type { get; set; }
public int Capacity { get; set; }
public int Count { get => data.Count; }
public void Add(Car car)
{
if (data.Count < this.Capacity)
{
data.Add(car);
}
}
public bool Remove(string manufacturer, string model)
{
var currCar = data.FirstOrDefault(c => c.Manufacturer == manufacturer && c.Model == model);
if (data.Contains(currCar))
{
data.Remove(currCar);
return true;
}
return false;
}
public Car GetLatestCar()
{
if (data.Count > 0)
{
return data.OrderByDescending(c => c.Year).First();
}
return null;
}
public Car GetCar(string manufacturer, string model)
{
var currCar = data.FirstOrDefault(c => c.Manufacturer == manufacturer && c.Model == model);
if (data.Contains(currCar))
{
return currCar;
}
return null;
}
public string GetStatistics()
{
var sb = new StringBuilder();
sb.AppendLine($"The cars are parked in {this.Type}:");
foreach (var car in this.data)
{
sb.AppendLine(car.ToString());
}
return sb.ToString().Trim();
}
}
}
| 20.152174 | 103 | 0.473571 | [
"MIT"
] | Mithras11/C_Sharp-Advanced-SoftUni | Exams/28.06.2020/Parking/Parking/Parking.cs | 1,856 | C# |
using System.Collections.Generic;
using System.Text.Json;
using System.IO;
using System.Linq;
// Determines the availablity of a domain
namespace OpenSRSLib
{
public class Register<T> : Request<T>
{
protected string domain;
protected ContactSet owner; // required
protected ContactSet admin;
protected ContactSet billing;
protected ContactSet tech;
// protected short customTechContact; // required 0 = use reseller tech contact, 1 = use tech contact provided
protected string handle = "process"; // required "save" - pend order for later, "process" proceed with order immediately
protected ushort period = 1; // required for new domain reg.: 1-10
protected static User userInfo = GetUserDetails();
// protected string regUsername; // required
// protected string regPassword; // required
// protected string regType; // required for domain reg. [new, transfer, landrush, premium, sunrise]
// protected short customNameservers; // optional 0 = user reseller default NS, 1 = use nameserverList
protected List<string> nameserverList; // conditional requirement
protected string affiliateId; // optional
protected string authInfo; // optional
protected ushort autoRenew = 1; // optional 0 = do not auto-renew, 1 = do auto-renew
protected ushort changeContact; // optional
protected string comments; // optional
protected ushort customTransferNameservers; // optional
protected string dnsTemplate; // optional
protected string encodingType; // optional
protected ushort fLockDomain = 1; // optional 0 = do not lock, 1 = do lock
protected char fParkp; // optional Y or N
protected string fWhoisPrivacy; // optional
protected string legalType; // conditional requirement for .ca
protected ushort linkDomains; // optional
protected string masterOrderId; // conditional requirement
protected string premiumPriceToVerify; // optional
protected string regDomain; // optional
protected string tldData; // conditional requirement for certain TLDs
protected string tradeMarkSMD; // conditional requirement for Sunrise orders
// get reseller username and password from userinfo.json
protected static User GetUserDetails()
{
var userOptions = GetUserInfo();
if (isInTestMode)
{
return userOptions.First(x => x.Id == "test");
}
else
{
return userOptions.First(x => x.Id == "live"); // IP must be white listed
}
}
protected static IEnumerable<User> GetUserInfo(){
using (var jsonFileReader = File.OpenText("OpenSRSLib/AccountInformation/userinfo.json"))
{
return JsonSerializer.Deserialize<User[]>(jsonFileReader.ReadToEnd(),
new JsonSerializerOptions
{ // these settings are optional
PropertyNameCaseInsensitive = true
});
}
}
}
} | 44.864865 | 132 | 0.613855 | [
"BSD-3-Clause"
] | fuzzyLojic/opensrsApi | OpenSRSLib/Registration/Register.cs | 3,320 | C# |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Csharp_Parse_Benchmark.Helpers.StringRandom;
namespace Csharp_Parse_Benchmark
{
public class ParseVsTryParseVsConvert
{
private StringRandom myString = new StringRandom();
private readonly string data;
public ParseVsTryParseVsConvert()
{
data = myString.generateNumber(10);
}
[Benchmark]
public long BParse()
{
long number;
number = long.Parse(data);
return number;
}
[Benchmark]
public long BTryParse()
{
long number;
long.TryParse(data, out number);
return number;
}
[Benchmark]
public long BConvert()
{
long number;
number = Convert.ToInt64(data);
return number;
}
}
public class Program
{
public static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<ParseVsTryParseVsConvert>();
Console.ReadLine();
}
}
} | 22.56 | 74 | 0.552305 | [
"MIT"
] | Evanna456/Csharp-Parse-Benchmark | Program.cs | 1,130 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileAndFolderDialog.Wpf.Samples.ViewModels
{
public class SelectFileDialogExampleViewModel : NinjaMvvm.Wpf.WpfViewModelBase
{
private readonly Abstractions.IFileDialogService _fileDialogService;
public SelectFileDialogExampleViewModel() { }//design time only
public SelectFileDialogExampleViewModel(FileAndFolderDialog.Abstractions.IFileDialogService fileDialogService)
{
this._fileDialogService = fileDialogService;
//set defaults
var options = new FileAndFolderDialog.Abstractions.OpenFileOptions();
this.AddExtension = options.AddExtension;
this.CheckFileExists = options.CheckFileExists;
this.CheckPathExists = options.CheckPathExists;
this.DefaultExt = options.DefaultExt;
this.DereferenceLinks = options.DereferenceLinks;
this.Filter = options.Filter;
this.FilterIndex = options.FilterIndex;
this.InitialDirectory = options.InitialDirectory;
this.Multiselect = options.Multiselect;
this.ReadOnlyChecked = options.ReadOnlyChecked;
this.RestoreDirectory = options.RestoreDirectory;
this.ShowReadOnly = options.ShowReadOnly;
this.Title = options.Title;
this.ValidateNames = options.ValidateNames;
this.DefaultFileName = options.DefaultFileName;
this.CustomPlaces = new ObservableCollection<string>();
}
public string DefaultFileName
{
get { return GetField<string>(); }
set { SetField(value); }
}
public bool Multiselect
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public bool ReadOnlyChecked
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public bool ShowReadOnly
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public ObservableCollection<string> CustomPlaces
{
get { return GetField<ObservableCollection<string>>(); }
set { SetField(value); }
}
public bool ValidateNames
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public string Title
{
get { return GetField<string>(); }
set { SetField(value); }
}
public bool RestoreDirectory
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public string InitialDirectory
{
get { return GetField<string>(); }
set { SetField(value); }
}
public int FilterIndex
{
get { return GetField<int>(); }
set { SetField(value); }
}
public string Filter
{
get { return GetField<string>(); }
set { SetField(value); }
}
public bool DereferenceLinks
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public string DefaultExt
{
get { return GetField<string>(); }
set { SetField(value); }
}
public bool CheckPathExists
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public bool CheckFileExists
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public bool AddExtension
{
get { return GetField<bool>(); }
set { SetField(value); }
}
public string SelectionResults
{
get { return GetField<string>(); }
set { SetField(value); }
}
#region ChooseFile Command
private NinjaMvvm.Wpf.RelayCommand _chooseFileCommand;
public NinjaMvvm.Wpf.RelayCommand ChooseFileCommand
{
get
{
if (_chooseFileCommand == null)
_chooseFileCommand = new NinjaMvvm.Wpf.RelayCommand((param) => this.ChooseFile(), (param) => this.CanChooseFile());
return _chooseFileCommand;
}
}
public bool CanChooseFile()
{
return true;
}
/// <summary>
/// Executes the ChooseFile command
/// </summary>
public void ChooseFile()
{
try
{
var options = new FileAndFolderDialog.Abstractions.OpenFileOptions()
{
AddExtension = this.AddExtension,
CheckFileExists = this.CheckFileExists,
CheckPathExists = this.CheckPathExists,
DefaultExt = this.DefaultExt,
DereferenceLinks = this.DereferenceLinks,
Filter = this.Filter,
FilterIndex = this.FilterIndex,
InitialDirectory = this.InitialDirectory,
Multiselect = this.Multiselect,
ReadOnlyChecked = this.ReadOnlyChecked,
RestoreDirectory = this.RestoreDirectory,
ShowReadOnly = this.ShowReadOnly,
Title = this.Title,
ValidateNames = this.ValidateNames,
DefaultFileName = this.DefaultFileName,
};
this.CustomPlaces
.ToList()
.ForEach(p => options.CustomPlaces.Add(p));
var results = _fileDialogService.ShowSelectFileDialog(options);
if (results == null || !results.Any())
this.SelectionResults = null;
else
this.SelectionResults = string.Join(Environment.NewLine, results);
}
catch (Exception ex)
{
this.SelectionResults = ex.Message;
}
}
#endregion
}
}
| 32.14359 | 135 | 0.535897 | [
"MIT"
] | DumpsterNinja/FileAndFolderDialogMvvm | src/Samples/FileAndFolderDialog.Wpf.Samples/ViewModels/SelectFileDialogExampleViewModel.cs | 6,270 | C# |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.Threading;
namespace Alachisoft.NCache.Common.Monitoring
{
[Serializable]
public class ClientMonitor: Runtime.Serialization.ICompactSerializable
{
private string _clientID;
private string _address;
private ArrayList _activities = new ArrayList();
private Hashtable _currentActivities = Hashtable.Synchronized(new Hashtable());
public ClientMonitor(string id, string address)
{
_clientID = id;
_address = address;
}
public string ID
{
get { return _clientID; }
}
public string Address
{
get { return _address; }
}
public ClienfInfo Info
{
get { return new ClienfInfo(_clientID, _address); }
}
public void StartActivity()
{
ClientActivity acitvity = new ClientActivity();
acitvity._thread = Thread.CurrentThread;
int tId = Thread.CurrentThread.ManagedThreadId;
lock (_currentActivities.SyncRoot)
{
if(!_currentActivities.ContainsKey(tId))
_currentActivities.Add(tId, acitvity);
}
}
public void StopActivity()
{
int tId = Thread.CurrentThread.ManagedThreadId;
ClientActivity activity = null;
lock (_currentActivities.SyncRoot)
{
activity = _currentActivities[tId] as ClientActivity;
_currentActivities.Remove(tId);
}
if (activity != null)
{
activity.StopActivity();
lock (_activities.SyncRoot)
{
_activities.Add(activity);
}
}
}
public void LogActivity(string method, string log)
{
ClientActivity activity = _currentActivities[Thread.CurrentThread.ManagedThreadId] as ClientActivity;
if (activity != null)
{
activity.LogActivity(method, log);
}
}
public void Clear()
{
lock (_activities.SyncRoot)
{
_activities.Clear();
}
lock (_currentActivities.SyncRoot)
{
_currentActivities.Clear();
}
}
public ArrayList GetCompletedClientActivities()
{
ArrayList completedActivities = null;
lock (_activities.SyncRoot)
{
completedActivities = _activities.Clone() as ArrayList;
}
return completedActivities;
}
public ArrayList GetCurrentClientActivities()
{
ArrayList completedActivities = new ArrayList();
lock (_currentActivities.SyncRoot)
{
IDictionaryEnumerator ide = _currentActivities.GetEnumerator();
while (ide.MoveNext())
{
if (ide.Value != null)
completedActivities.Add(((ICloneable)ide.Value).Clone());
}
}
return completedActivities;
}
#region ICompact Serializable Members
public void Deserialize(Runtime.Serialization.IO.CompactReader reader)
{
_clientID = (string)reader.ReadObject();
_address = (string)reader.ReadObject();
_activities = (ArrayList)reader.ReadObject();
_currentActivities = (Hashtable)reader.ReadObject();
}
public void Serialize(Runtime.Serialization.IO.CompactWriter writer)
{
writer.WriteObject(_clientID);
writer.WriteObject(_address);
writer.WriteObject(_activities);
writer.WriteObject(_currentActivities);
}
#endregion
}
} | 32.119718 | 113 | 0.5672 | [
"Apache-2.0"
] | Alachisoft/NCache | Src/NCCommon/Monitoring/ClientMonitor.cs | 4,561 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Physics;
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Collections;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Base Pointer class for pointers that exist in the scene as GameObjects.
/// </summary>
[DisallowMultipleComponent]
public abstract class BaseControllerPointer : ControllerPoseSynchronizer, IMixedRealityPointer
{
[SerializeField]
private GameObject cursorPrefab = null;
[SerializeField]
private bool disableCursorOnStart = false;
protected bool DisableCursorOnStart => disableCursorOnStart;
[SerializeField]
private bool setCursorVisibilityOnSourceDetected = false;
private GameObject cursorInstance = null;
[SerializeField]
[Tooltip("Source transform for raycast origin - leave null to use default transform")]
protected Transform raycastOrigin = null;
[SerializeField]
[Tooltip("The hold action that will enable the raise the input event for this pointer.")]
private MixedRealityInputAction activeHoldAction = MixedRealityInputAction.None;
[SerializeField]
[Tooltip("The action that will enable the raise the input event for this pointer.")]
protected MixedRealityInputAction pointerAction = MixedRealityInputAction.None;
[SerializeField]
[Tooltip("Does the interaction require hold?")]
private bool requiresHoldAction = false;
[SerializeField]
[Tooltip("Does the interaction require the action to occur at least once first?")]
private bool requiresActionBeforeEnabling = true;
/// <summary>
/// True if select is pressed right now
/// </summary>
protected bool IsSelectPressed = false;
/// <summary>
/// True if select has been pressed once since this component was enabled
/// </summary>
protected bool HasSelectPressedOnce = false;
protected bool IsHoldPressed = false;
/// <summary>
/// Set a new cursor for this <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityPointer"/>
/// </summary>
/// <remarks>This <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> must have a <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityCursor"/> attached to it.</remarks>
/// <param name="newCursor">The new cursor</param>
public virtual void SetCursor(GameObject newCursor = null)
{
if (cursorInstance != null)
{
if (Application.isEditor)
{
DestroyImmediate(cursorInstance);
}
else
{
Destroy(cursorInstance);
}
cursorInstance = newCursor;
}
if (cursorInstance == null && cursorPrefab != null)
{
cursorInstance = Instantiate(cursorPrefab, transform);
}
if (cursorInstance != null)
{
cursorInstance.name = $"{Handedness}_{name}_Cursor";
BaseCursor = cursorInstance.GetComponent<IMixedRealityCursor>();
if (BaseCursor != null)
{
BaseCursor.DefaultCursorDistance = DefaultPointerExtent;
BaseCursor.Pointer = this;
BaseCursor.SetVisibilityOnSourceDetected = setCursorVisibilityOnSourceDetected;
if (disableCursorOnStart)
{
BaseCursor.SetVisibility(false);
}
}
else
{
Debug.LogError($"No IMixedRealityCursor component found on {cursorInstance.name}");
}
}
}
#region MonoBehaviour Implementation
protected override void OnEnable()
{
base.OnEnable();
// Disable renderers so that they don't display before having been processed (which manifests as a flash at the origin).
var renderers = GetComponentsInChildren<Renderer>();
if (renderers != null)
{
foreach (var renderer in renderers)
{
renderer.enabled = false;
}
}
}
protected override async void Start()
{
base.Start();
await EnsureInputSystemValid();
// We've been destroyed during the await.
if (this == null)
{
return;
}
// The pointer's input source was lost during the await.
if (Controller == null)
{
Destroy(gameObject);
return;
}
SetCursor();
}
protected override void OnDisable()
{
if (IsSelectPressed && InputSystem != null)
{
InputSystem.RaisePointerUp(this, pointerAction, Handedness);
}
base.OnDisable();
IsHoldPressed = false;
IsSelectPressed = false;
HasSelectPressedOnce = false;
BaseCursor?.SetVisibility(false);
}
#endregion MonoBehaviour Implementation
#region IMixedRealityPointer Implementation
/// <inheritdoc />
public override IMixedRealityController Controller
{
get { return base.Controller; }
set
{
base.Controller = value;
if (base.Controller != null && this != null)
{
pointerName = gameObject.name;
InputSourceParent = base.Controller.InputSource;
}
}
}
private uint pointerId;
/// <inheritdoc />
public uint PointerId
{
get
{
if (pointerId == 0)
{
pointerId = InputSystem.FocusProvider.GenerateNewPointerId();
}
return pointerId;
}
}
private string pointerName = string.Empty;
/// <inheritdoc />
public string PointerName
{
get { return pointerName; }
set
{
pointerName = value;
if (this != null)
{
gameObject.name = value;
}
}
}
/// <inheritdoc />
public IMixedRealityInputSource InputSourceParent { get; protected set; }
/// <inheritdoc />
public IMixedRealityCursor BaseCursor { get; set; }
/// <inheritdoc />
public ICursorModifier CursorModifier { get; set; }
/// <inheritdoc />
public virtual bool IsInteractionEnabled
{
get
{
if (IsFocusLocked)
{
return true;
}
if (!IsActive)
{
return false;
}
if (requiresHoldAction && IsHoldPressed)
{
return true;
}
if (IsSelectPressed)
{
return true;
}
return HasSelectPressedOnce || !requiresActionBeforeEnabling;
}
}
public virtual bool IsActive { get; set; }
/// <inheritdoc />
public bool IsFocusLocked { get; set; }
/// <inheritdoc />
public bool IsTargetPositionLockedOnFocusLock { get; set; }
[SerializeField]
private bool overrideGlobalPointerExtent = false;
[SerializeField]
private float pointerExtent = 10f;
/// <inheritdoc />
public float PointerExtent
{
get
{
if (overrideGlobalPointerExtent)
{
if (InputSystem?.FocusProvider != null)
{
return InputSystem.FocusProvider.GlobalPointingExtent;
}
}
return pointerExtent;
}
set
{
pointerExtent = value;
overrideGlobalPointerExtent = false;
}
}
[SerializeField]
private float defaultPointerExtent = 10f;
/// <summary>
/// The length of the pointer when nothing is hit.
/// </summary>
public float DefaultPointerExtent
{
get { return Mathf.Min(defaultPointerExtent, PointerExtent); }
set { defaultPointerExtent = value; }
}
/// <inheritdoc />
public RayStep[] Rays { get; protected set; } = { new RayStep(Vector3.zero, Vector3.forward) };
/// <inheritdoc />
public LayerMask[] PrioritizedLayerMasksOverride { get; set; }
/// <inheritdoc />
public IMixedRealityFocusHandler FocusTarget { get; set; }
/// <inheritdoc />
public IPointerResult Result { get; set; }
/// <summary>
/// Ray stabilizer used when calculating position of pointer end point.
/// </summary>
public IBaseRayStabilizer RayStabilizer { get; set; }
/// <inheritdoc />
public virtual SceneQueryType SceneQueryType { get; set; } = SceneQueryType.SimpleRaycast;
[SerializeField]
[Tooltip("The radius to use when SceneQueryType is set to Sphere or SphereColliders.")]
private float sphereCastRadius = 0.1f;
/// <inheritdoc />
public float SphereCastRadius
{
get { return sphereCastRadius; }
set { sphereCastRadius = value; }
}
/// <inheritdoc />
public virtual Vector3 Position => raycastOrigin != null ? raycastOrigin.position : transform.position;
/// <inheritdoc />
public virtual Quaternion Rotation => raycastOrigin != null ? raycastOrigin.rotation : transform.rotation;
/// <inheritdoc />
public virtual void OnPreSceneQuery() { }
/// <inheritdoc />
public virtual void OnPostSceneQuery()
{
if (IsSelectPressed)
{
InputSystem.RaisePointerDragged(this, MixedRealityInputAction.None, Handedness);
}
}
/// <inheritdoc />
public virtual void OnPreCurrentPointerTargetChange() { }
#endregion IMixedRealityPointer Implementation
#region IEquality Implementation
private static bool Equals(IMixedRealityPointer left, IMixedRealityPointer right)
{
return left.Equals(right);
}
/// <inheritdoc />
bool IEqualityComparer.Equals(object left, object right)
{
return left != null && left.Equals(right);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((IMixedRealityPointer)obj);
}
private bool Equals(IMixedRealityPointer other)
{
return other != null && PointerId == other.PointerId && string.Equals(PointerName, other.PointerName);
}
/// <inheritdoc />
int IEqualityComparer.GetHashCode(object obj)
{
return obj.GetHashCode();
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = 0;
hashCode = (hashCode * 397) ^ (int)PointerId;
hashCode = (hashCode * 397) ^ (PointerName != null ? PointerName.GetHashCode() : 0);
return hashCode;
}
}
#endregion IEquality Implementation
#region IMixedRealitySourcePoseHandler Implementation
/// <inheritdoc />
public override void OnSourceLost(SourceStateEventData eventData)
{
base.OnSourceLost(eventData);
if (eventData.SourceId == InputSourceParent.SourceId)
{
if (requiresHoldAction)
{
IsHoldPressed = false;
}
if (IsSelectPressed)
{
InputSystem.RaisePointerUp(this, pointerAction, Handedness);
}
IsSelectPressed = false;
}
}
#endregion IMixedRealitySourcePoseHandler Implementation
#region IMixedRealityInputHandler Implementation
/// <inheritdoc />
public override void OnInputUp(InputEventData eventData)
{
base.OnInputUp(eventData);
if (eventData.SourceId == InputSourceParent.SourceId)
{
if (requiresHoldAction && eventData.MixedRealityInputAction == activeHoldAction)
{
IsHoldPressed = false;
}
if (eventData.MixedRealityInputAction == pointerAction)
{
IsSelectPressed = false;
InputSystem.RaisePointerClicked(this, pointerAction, 0, Handedness);
InputSystem.RaisePointerUp(this, pointerAction, Handedness);
}
}
}
/// <inheritdoc />
public override void OnInputDown(InputEventData eventData)
{
base.OnInputDown(eventData);
if (eventData.SourceId == InputSourceParent.SourceId)
{
if (requiresHoldAction && eventData.MixedRealityInputAction == activeHoldAction)
{
IsHoldPressed = true;
}
if (eventData.MixedRealityInputAction == pointerAction)
{
IsSelectPressed = true;
HasSelectPressedOnce = true;
if (IsInteractionEnabled)
{
InputSystem.RaisePointerDown(this, pointerAction, Handedness);
}
}
}
}
#endregion IMixedRealityInputHandler Implementation
}
}
| 30.503106 | 220 | 0.535668 | [
"MIT"
] | AdamMitchell-ms/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/Pointers/BaseControllerPointer.cs | 14,735 | C# |
using Pekka.ClashRoyaleApi.Client.Contracts;
using Pekka.ClashRoyaleApi.Client.Models.CardModels;
using Pekka.Core;
using Pekka.Core.Contracts;
using Pekka.Core.Responses;
using System.Collections.Generic;
using System.Threading.Tasks;
using Pekka.ClashRoyaleApi.Client.Models.GlobalTournamentModels;
namespace Pekka.ClashRoyaleApi.Client.Clients
{
public class GlobalTournamentClient : BaseClient, IGlobalTournamentClient
{
public GlobalTournamentClient(IRestApiClient restApiClient) : base(restApiClient)
{
}
public async Task<IApiResponse<PagedGlobalTournaments>> GetGlobalTournamentsResponseAsync()
{
IApiResponse<PagedGlobalTournaments> apiResponse = await RestApiClient.GetApiResponseAsync<PagedGlobalTournaments>(UrlPathBuilder.GlobalTournaments);
return apiResponse;
}
public async Task<PagedGlobalTournaments> GetGlobalTournamentsAsync()
{
IApiResponse<PagedGlobalTournaments> apiResponse = await GetGlobalTournamentsResponseAsync();
return apiResponse.Model;
}
}
} | 32.764706 | 161 | 0.751346 | [
"MIT"
] | Blind-Striker/clash-royale-client-dotnet | src/Pekka.ClashRoyaleApi.Client/Clients/GlobalTournamentClient.cs | 1,116 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls;
using Avalonia.Native.Interop;
using Avalonia.Platform;
using Avalonia.Platform.Interop;
namespace Avalonia.Native
{
public class WindowImpl : WindowBaseImpl, IWindowImpl
{
private readonly IAvaloniaNativeFactory _factory;
private readonly AvaloniaNativePlatformOptions _opts;
IAvnWindow _native;
public WindowImpl(IAvaloniaNativeFactory factory, AvaloniaNativePlatformOptions opts) : base(opts)
{
_factory = factory;
_opts = opts;
using (var e = new WindowEvents(this))
{
Init(_native = factory.CreateWindow(e), factory.CreateScreens());
}
}
class WindowEvents : WindowBaseEvents, IAvnWindowEvents
{
readonly WindowImpl _parent;
public WindowEvents(WindowImpl parent) : base(parent)
{
_parent = parent;
}
bool IAvnWindowEvents.Closing()
{
if(_parent.Closing != null)
{
return _parent.Closing();
}
return true;
}
void IAvnWindowEvents.WindowStateChanged(AvnWindowState state)
{
_parent.WindowStateChanged?.Invoke((WindowState)state);
}
}
public IAvnWindow Native => _native;
public void ShowDialog(IWindowImpl window)
{
_native.ShowDialog(((WindowImpl)window).Native);
}
public void CanResize(bool value)
{
_native.CanResize = value;
}
public void SetSystemDecorations(bool enabled)
{
_native.HasDecorations = enabled;
}
public void SetTitleBarColor (Avalonia.Media.Color color)
{
_native.SetTitleBarColor(new AvnColor { Alpha = color.A, Red = color.R, Green = color.G, Blue = color.B });
}
public void SetTitle(string title)
{
using (var buffer = new Utf8Buffer(title))
{
_native.SetTitle(buffer.DangerousGetHandle());
}
}
public WindowState WindowState
{
get
{
return (WindowState)_native.GetWindowState();
}
set
{
_native.SetWindowState((AvnWindowState)value);
}
}
public Action<WindowState> WindowStateChanged { get; set; }
public void ShowTaskbarIcon(bool value)
{
// NO OP On OSX
}
public void SetIcon(IWindowIconImpl icon)
{
// NO OP on OSX
}
public Func<bool> Closing { get; set; }
public void Move(PixelPoint point) => Position = point;
public override IPopupImpl CreatePopup() =>
_opts.OverlayPopups ? null : new PopupImpl(_factory, _opts, this);
}
}
| 27.902655 | 119 | 0.559784 | [
"MIT"
] | Karnah/Avalonia | src/Avalonia.Native/WindowImpl.cs | 3,155 | C# |
using MicroOrm.Dapper.Repositories;
using MicroOrm.Dapper.Repositories.DbContext;
using System;
using System.Collections.Generic;
using System.Data;
using Crystal.Shared;
using System.Threading.Tasks;
using AutoMapper;
namespace Crystal.Dapper
{
/// <summary>
/// Base unit of work repository
/// </summary>
public class BaseUowRepository : DapperDbContext, IBaseUowRepository
{
private readonly IDictionary<Type, object> _repositoryInstances;
private IDbTransaction _dbTransaction;
private readonly IMapper _mapper;
/// <summary>
/// Base unit of work constructor
/// </summary>
/// <param name="connection"></param>
/// <param name="mapper"></param>
public BaseUowRepository(IDbConnection connection, IMapper mapper = default)
: base(connection)
{
_mapper = mapper;
_repositoryInstances = new Dictionary<Type, object>();
}
/// <summary>
/// Returns IBaseRepository instance of the entity
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <returns></returns>
public virtual IBaseRepository<TEntity> Repository<TEntity>() where TEntity : class
{
return this.Repository<TEntity>(this.Connection);
}
/// <summary>
/// Returns IBaseRepository instance of the entity
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connection"></param>
/// <returns></returns>
public virtual IBaseRepository<TEntity> Repository<TEntity>(IDbConnection connection) where TEntity : class
{
//***
//*** Check if the instance is already created
//***
if (_repositoryInstances.ContainsKey(typeof(TEntity)))
{
//***
//*** Instance already created, return the instance from the dictionary
//***
return (IBaseRepository<TEntity>)_repositoryInstances[typeof(TEntity)];
}
else
{
//***
//*** Create a new instance of base repository
//*** Save it to the dictionary
//*** Return the instance
//***
var repo = new BaseRepository<TEntity>(connection, _mapper, _dbTransaction);
_repositoryInstances.Add(typeof(TEntity), repo);
return repo;
}
}
/// <summary>
/// Dispose all open connections and repositories
/// </summary>
public new void Dispose()
{
//***
//*** Dispose all base repository instances
//***
foreach (var item in _repositoryInstances)
{
item.Value.TryDispose();
}
//***
//*** Clear all repository instances
//***
_repositoryInstances.Clear();
//***
//*** Dispose dB context
//***
this.Connection?.Close();
this.Connection?.Dispose();
base.Dispose();
}
/// <summary>
/// Commit changes to database
/// </summary>
public virtual Task CommitAsync()
{
//***
//*** rollback the changes
//***
if (_dbTransaction == null)
{
throw new Exception("Transaction not initialized");
}
_dbTransaction.Commit();
return Task.CompletedTask;
}
/// <summary>
/// Starts a transaction which can be used across multiple data change requests
/// </summary>
/// <param name="isolationLevel">Set isolation level on the transaction. Isolation level will not be set when using sqlite connection</param>
/// <returns></returns>
public virtual Task BeginTransactionAsync(IsolationLevel isolationLevel = default)
{
if (this.Connection == null)
{
throw new NullReferenceException("Database connection is not initialized");
}
else
{
switch (this.Connection.GetType().Name.ToLower())
{
case "sqliteconnection":
//***
//*** No isolation level when using sqlite
//***
_dbTransaction = this.Connection.BeginTransaction();
break;
default:
//***
//*** Create transaction with isolation level for all other database providers
//***
_dbTransaction = this.Connection.BeginTransaction(isolationLevel);
break;
}
}
return Task.CompletedTask;
}
/// <summary>
/// Rollback any uncommitted changes
/// </summary>
/// <returns></returns>
public virtual Task RollbackAsync()
{
//***
//*** rollback the changes
//***
if (_dbTransaction == null)
{
throw new Exception("Transaction not initialized");
}
_dbTransaction.Rollback();
return Task.CompletedTask;
}
}
}
| 33.4 | 149 | 0.506442 | [
"MIT"
] | harshitgindra/Crystal.Shared | Crystal.Dapper/Repository/BaseUowRepository.cs | 5,513 | C# |
using Countdown_ASP.NET.Models;
using Countdown_ASP.NET.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System;
using System.Text;
namespace Countdown_ASP.NET.Services
{
public class TokenService : ITokenService
{
private readonly SymmetricSecurityKey _key;
public TokenService(IConfiguration config)
{
_key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"]));
}
public string CreateToken(User user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.NameId, user.Email)
};
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(7),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
| 30.577778 | 94 | 0.624273 | [
"MIT"
] | LaunchCodeLiftoffProjects/CountDown | countDownBackEnd/Countdown ASP.NET/Services/TokenService.cs | 1,376 | C# |
namespace RemotePlanning.Ui.StorycardsUi
{
public class StorycardBatchLoader
{
}
} | 15.666667 | 40 | 0.723404 | [
"Apache-2.0"
] | Omnicrola/remote-planning | RemotePlanning/RemotePlanning/Ui/StorycardsUi/StorycardBatchLoader.cs | 94 | 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("11_Raincast")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("11_Raincast")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c87deb8-7fda-4c4c-b44f-a315f8faadcf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568 | 84 | 0.747482 | [
"MIT"
] | dimitarminchev/ITCareer | 02. Programming/2019/2019.03.10/11_Raincast/Properties/AssemblyInfo.cs | 1,393 | 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.CCC.Transform;
using Aliyun.Acs.CCC.Transform.V20200701;
namespace Aliyun.Acs.CCC.Model.V20200701
{
public class SubmitCampaignRequest : RpcAcsRequest<SubmitCampaignResponse>
{
public SubmitCampaignRequest()
: base("CCC", "2020-07-01", "SubmitCampaign", "CCC", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.CCC.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.CCC.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string instanceId;
private string campaignId;
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
DictionaryUtil.Add(QueryParameters, "InstanceId", value);
}
}
public string CampaignId
{
get
{
return campaignId;
}
set
{
campaignId = value;
DictionaryUtil.Add(QueryParameters, "CampaignId", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override SubmitCampaignResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return SubmitCampaignResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 29.654762 | 134 | 0.687274 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Model/V20200701/SubmitCampaignRequest.cs | 2,491 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using VideoKategoriseringsApi.Models;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Linq;
namespace VideoKategoriseringsApi.Controllers
{
[Route("api")]
[EnableCors("AllowAll")]
public class MainController : Controller
{
private readonly Settings Settings;
public MainController(IOptions<Settings> settingsOptions)
{
Settings = settingsOptions.Value;
}
[HttpPost("save")]
public IActionResult SaveJson([FromBody]VideoFile video)
{
Console.WriteLine("saving file" + video.url);
if (video == null)
return BadRequest("Nu gjorde du fel. Ogiltig JSON.");
SaveOrUpdateJSONFile(video);
return Ok("Success");
}
[HttpPost("tagSuggestions/{type}/save")]
public IActionResult SaveTagSuggestions(string type, [FromBody]Tag[] suggestions)
{
Console.WriteLine("saving suggestions to file");
if (suggestions == null)
return BadRequest("Nu gjorde du fel. Ogiltig JSON.");
var filePath = Path.Combine(Settings.DataPath, type + "_suggestions.json");
var data = JsonConvert.SerializeObject(suggestions);
SaveJSONFile(filePath, data);
return Ok(new Tag());
}
[HttpGet("tagSuggestions/{type}")]
public IActionResult GetAllTagSuggestions(string type)
{
var filePath = Path.Combine(Settings.DataPath, type + "_suggestions.json");
var data = new Tag[0];
if (System.IO.File.Exists(filePath)){
data = ReadJSONFile<Tag[]>(filePath);
}
return Ok(data);
}
[HttpPost("searchIndex/save")]
public IActionResult SavePregeneratedIndex([FromBody]JObject index)
{
Console.WriteLine("saving index to file");
if (index == null)
return BadRequest("Nu gjorde du fel. Ogiltig JSON.");
var filePath = Path.Combine(Settings.DataPath, "search_index.json");
var data = JsonConvert.SerializeObject(index);
SaveJSONFile(filePath, data);
return Ok(new Tag());
}
[HttpGet("searchIndex")]
public IActionResult GetPregeneratedIndex()
{
var filePath = Path.Combine(Settings.DataPath, "search_index.json");
var data = new JObject();
if (System.IO.File.Exists(filePath)){
data = ReadJSONFile<JObject>(filePath);
}
return Ok(data);
}
[HttpGet("statistics")]
public IActionResult GetStatistics()
{
var statistics = new Dictionary<String, int>();
statistics.Add("totalNrOfFiles", 0);
statistics.Add("nrOfDeletedFiles", 0);
statistics.Add("nrOfCategorizedFiles", 0);
statistics.Add("nrOfFilesToCategorize", 0);
statistics.Add("nrOfProcessedFiles", 0);
foreach(var folder in Directory.EnumerateDirectories(Settings.DataPath))
{
var dir = folder.Substring(folder.LastIndexOf(Path.DirectorySeparatorChar) + 1);
foreach(var file in GetAllVideoFilesInDirectory(dir))
{
statistics["totalNrOfFiles"]++;
if(file.status.ToLowerInvariant().Trim() == "categorized")
{
statistics["nrOfCategorizedFiles"]++;
}
if(file.status.ToLowerInvariant().Trim() == "sequences_has_been_processed")
{
statistics["nrOfProcessedFiles"]++;
}
if(file.markedAsDeleted)
{
statistics["nrOfDeletedFiles"]++;
}
}
}
statistics["nrOfFilesToCategorize"] = statistics["totalNrOfFiles"] - statistics["nrOfDeletedFiles"] - statistics["nrOfCategorizedFiles"];
return Ok(statistics);
}
[HttpGet("folders")]
public IActionResult GetAllFolders()
{
List<string> result = new List<string>();
foreach(var folder in Directory.EnumerateDirectories(Settings.DataPath))
{
result.Add(folder.Substring(folder.LastIndexOf(Path.DirectorySeparatorChar) + 1));
}
return Ok(result);
}
[HttpGet("files/{folderName?}")]
public IActionResult GetAllFiles(string folderName)
{
// bool showAll = string.IsNullOrEmpty(status);
List<VideoFile> files = GetAllVideoFilesInDirectory(folderName);
return Ok(files);
}
private List<VideoFile> GetAllVideoFilesInDirectory(String folderName){
var allJSONFiles = Directory.EnumerateFiles(Settings.DataPath + "/" + folderName)
.Where(x => x.EndsWith(".json"))
.Select(filename => new FileInfo(filename));
var data = new List<VideoFile>(allJSONFiles.Count());
foreach (var json in allJSONFiles)
{
var videoFile = ReadJSONFile<VideoFile>(json.FullName);
// if (showAll || videoFile.status.ToLowerInvariant().Trim() == status.ToLowerInvariant().Trim())
// {
videoFile.url = getUrl(videoFile);
data.Add(videoFile);
// }
}
return data;
}
[HttpGet("process")]
public IActionResult ProcessMemoryCard()
{
Console.WriteLine("Processing memorycard");
foreach (var filePath in Directory.EnumerateFiles(Settings.MemoryCardPath))
{
var fileName = Path.GetFileName(filePath);
Console.WriteLine(" Processing " + fileName);
DateTime created = System.IO.File.GetLastWriteTime(filePath); //this is apparenly the only(?) way for us to get original created time...
string dateTimeFileWasCaptured = created.ToString("yyyy-MM-dd_HH-mm-ss");
string dateFileWasCaptured = created.ToString("yyyy-MM-dd");
var destinationFolder = dateFileWasCaptured; //2018-02-14
var destinationFileName = dateTimeFileWasCaptured + "_" + fileName; // 2018-02-14_17-22-02_DJI_0639.mov
var destinationFolderPath = Path.Combine(Settings.DataPath, destinationFolder); // c:\....\storage\2018-02-14\
var destinationFullFilePath = Path.Combine(destinationFolderPath, destinationFileName); // c:\....\storage\2018-02-02\2018-02-14_17-22-02_DJI_0639.mov
if (!System.IO.File.Exists(destinationFolderPath)){
System.IO.Directory.CreateDirectory(destinationFolderPath);
}
if (System.IO.File.Exists(destinationFullFilePath))
{
Console.WriteLine(" File already processed, ignoring.");
continue;
}
Console.WriteLine(" Copying file to " + destinationFullFilePath);
System.IO.File.Copy(filePath, destinationFullFilePath, false);
Console.WriteLine(" Extracting first frame from video as thumbnail");
var thumbNailImageUrl = ExtractFirstFrameAsBase64(destinationFullFilePath);
// TODO: Read video file properties.
Console.WriteLine(" Creating metadatafile");
SaveOrUpdateJSONFile(new VideoFile(
destinationFolder,
destinationFileName,
thumbNailImageUrl,
"video/mp4", //TODO: remove hardcoded value
0,
null
));
}
Console.WriteLine("Processing memorycard has completed.");
return Ok();
}
[HttpGet("purge")]
public IActionResult Purge()
{
var allJSONFilePaths = Directory.EnumerateFiles(Settings.DataPath)
.Where(x => x.EndsWith(".json"));
foreach (var jsonPath in allJSONFilePaths)
{
var videoFile = ReadJSONFile<VideoFile>(jsonPath);
if (videoFile.status.ToLowerInvariant().Trim() == "deleted")
{
System.IO.File.Delete(jsonPath);
System.IO.File.Delete(new string(jsonPath.SkipLast(5).ToArray()));
}
}
return Ok();
}
private T ReadJSONFile<T>(string filename)
{
using (var filestream = new FileStream(filename, FileMode.Open))
{
using (var reader = new StreamReader(filestream))
{
var line = reader.ReadLine();
return JsonConvert.DeserializeObject<T>(line);
}
}
}
private void SaveJSONFile(string filepath, string data){
var filestream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (var writer = new StreamWriter(filestream))
{
writer.Write(data);
writer.Flush();
filestream.SetLength(filestream.Position);
}
}
private void SaveOrUpdateJSONFile(VideoFile video)
{
string data;
var filepath = getFilePath(video);
if (System.IO.File.Exists(filepath)){
var existingObject = ReadJSONFile<VideoFile>(filepath);
existingObject.comment = video.comment;
existingObject.exposureRequiresAdjustment = video.exposureRequiresAdjustment;
existingObject.rotationRequiresAdjustment = video.rotationRequiresAdjustment;
existingObject.status = video.status;
existingObject.sequences = video.sequences;
existingObject.markedAsDeleted = video.markedAsDeleted;
data = JsonConvert.SerializeObject(existingObject);
}
else
{
data = JsonConvert.SerializeObject(video);
}
this.SaveJSONFile(filepath, data);
}
private string ExtractFirstFrameAsBase64(string videoFilePath)
{
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = $"-i \"" + videoFilePath + "\" -nostats -loglevel 0 -vframes 1 -f image2 screendump.jpg",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
var screendumpPath = Path.Combine(Directory.GetCurrentDirectory(), "screendump.jpg");
var imageContent = ImageToBase64(screendumpPath);
System.IO.File.Delete(screendumpPath);
return imageContent;
}
public string getUrl(VideoFile video)
{
return Settings.VideoLocationBase + video.folder + "/" + video.fileName;
}
public string getFilePath(VideoFile video)
{
return Path.Combine(Settings.DataPath, video.folder, video.fileName + ".json");
}
public string ImageToBase64(string imagePath)
{
byte[] b = System.IO.File.ReadAllBytes(imagePath);
return "data:image/jpeg;base64," + Convert.ToBase64String(b);
}
}
}
| 39.951299 | 166 | 0.553027 | [
"Apache-2.0"
] | Urbaino/VideoMateApi | Controllers/MainController.cs | 12,307 | C# |
/*
* Arranges nodes based on relationships. Contains a series or rows (DiagramRow),
* each row contains a series of groups (DiagramGroup), and each group contains a
* series of nodes (DiagramNode).
*
* Contains a list of connections. Each connection describes where the node
* is located in the diagram and type of connection. The lines are draw
* during OnRender.
*
* Diagram is responsible for managing the rows. The logic that populates the rows
* and understand all of the relationships is contained in DiagramLogic.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Microsoft.FamilyShowLib;
namespace Microsoft.FamilyShow.Controls.Diagram;
/// <summary>
/// Diagram that lays out and displays the nodes.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
internal class Diagram : FrameworkElement
{
public Diagram()
{
// Init the diagram logic, which handles all of the layout logic.
logic = new DiagramLogic
{
NodeClickHandler = OnNodeClick
};
// Can have an empty People collection when in design tools such as Blend.
if (logic.Family != null)
{
logic.Family.ContentChanged += OnFamilyContentChanged;
logic.Family.CurrentChanged += OnFamilyCurrentChanged;
}
}
/// <summary>
/// Draw the connector lines at a lower level (OnRender) instead
/// of creating visual tree objects.
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
#if DEBUG
if (displayBorder)
// Draws borders around the rows and groups.
foreach (var row in rows)
{
// Display row border.
var bounds = new Rect(row.Location, row.DesiredSize);
drawingContext.DrawRectangle(null, new Pen(Brushes.DarkKhaki, 1), bounds);
foreach (var group in row.Groups)
{
// Display group border.
bounds = new Rect(@group.Location, @group.DesiredSize);
bounds.Offset(row.Location.X, row.Location.Y);
bounds.Inflate(-1, -1);
drawingContext.DrawRectangle(null, new Pen(Brushes.Gray, 1), bounds);
}
}
#endif
// Draw child connectors first, so marriage information appears on top.
foreach (var connector in logic.Connections)
if (connector.IsChildConnector)
connector.Draw(drawingContext);
// Draw all other non-child connectors.
foreach (var connector in logic.Connections)
if (!connector.IsChildConnector)
connector.Draw(drawingContext);
}
/// <summary>
/// Animate the new person that was added to the diagram.
/// </summary>
private void AnimateNewPerson()
{
// The new person is optional, can be null.
if (newPerson == null) return;
// Get the UI element to animate.
var node = logic.GetDiagramNode(newPerson);
if (node != null)
{
// Create the new person animation.
var anim = new DoubleAnimation(0, 1, App.GetAnimationDuration(Const.NewPersonAnimationDuration));
// Animate the node.
var transform = new ScaleTransform();
transform.BeginAnimation(ScaleTransform.ScaleXProperty, anim);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, anim);
node.RenderTransform = transform;
}
newPerson = null;
}
/// <summary>
/// Called when data changed in the main People collection. This can be
/// a new node added to the collection, updated Person details, and
/// updated relationship data.
/// </summary>
private void OnFamilyContentChanged(object sender, ContentChangedEventArgs e)
{
// Ignore if currently repopulating the diagram.
if (populating) return;
// Save the person that is being added to the diagram.
// This is optional and can be null.
newPerson = e.NewPerson;
// Redraw the diagram.
UpdateDiagram();
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
}
/// <summary>
/// Called when the current person in the main People collection changes.
/// This means the diagram should be updated based on the new selected person.
/// </summary>
private void OnFamilyCurrentChanged(object sender, EventArgs e)
{
// Save the bounds for the current primary person, this
// is required later when animating the diagram.
SelectedNodeBounds = logic.GetNodeBounds(logic.Family.Current);
// Repopulate the diagram.
Populate();
}
/// <summary>
/// A node was clicked, make that node the primary node.
/// </summary>
private void OnNodeClick(object sender, RoutedEventArgs e)
{
// Get the node that was clicked.
if (sender is DiagramNode node)
// Make it the primary node. This raises the CurrentChanged
// event, which repopulates the diagram.
logic.Family.Current = node.Person;
}
#if DEBUG
private void OnToggleBorderClick(object sender, RoutedEventArgs e)
{
// Display or hide the row and group borders.
displayBorder = !displayBorder;
// Update check on menu.
var menuItem = ContextMenu.Items[0] as MenuItem;
menuItem.IsChecked = displayBorder;
InvalidateVisual();
}
#endif
#region fields
private static class Const
{
// Duration to pause before displaying new nodes.
public static readonly double AnimationPauseDuration = 600;
// Duration for nodes to fade in when the diagram is repopulated.
public static readonly double NodeFadeInDuration = 500;
// Duration for the new person animation.
public static readonly double NewPersonAnimationDuration = 250;
// Stop adding new rows when the number of nodes exceeds the max node limit.
public static readonly int MaximumNodes = 50;
// Group space.
public static readonly double PrimaryRowGroupSpace = 20;
public static readonly double ChildRowGroupSpace = 20;
public static readonly double ParentRowGroupSpace = 40;
// Amount of space between each row.
public static readonly double RowSpace = 40;
// Scale multiplier for spouse and siblings.
public static readonly double RelatedMultiplier = 0.8;
// Scale multiplier for each future generation row.
public static readonly double GenerationMultiplier = 0.9;
}
// List of rows in the diagram. Each row contains groups, and each group contains nodes.
private readonly List<DiagramRow> rows = new();
// Populates the rows with nodes.
private readonly DiagramLogic logic;
// Size of the diagram. Used to layout all of the nodes before the
// control gets an actual size.
private Size totalSize = new(0, 0);
// Zoom level of the diagram.
private double scale = 1.0;
// Bounding area of the selected node, the selected node is the
// non-primary node that is selected, and will become the primary node.
// Flag if currently populating or not. Necessary since diagram populate
// contains several parts and animations, request to update the diagram
// are ignored when this flag is set.
private bool populating;
// The person that has been added to the diagram.
private Person newPerson;
// Timer used with the repopulating animation.
private readonly DispatcherTimer animationTimer = new();
#if DEBUG
// Flag if the row and group borders should be drawn.
private bool displayBorder;
#endif
#endregion
#region events
public event EventHandler DiagramUpdated;
private void OnDiagramUpdated()
{
if (DiagramUpdated != null) DiagramUpdated(this, EventArgs.Empty);
}
public event EventHandler DiagramPopulated;
private void OnDiagramPopulated()
{
if (DiagramPopulated != null) DiagramPopulated(this, EventArgs.Empty);
}
#endregion
#region properties
/// <summary>
/// Gets or sets the zoom level of the diagram.
/// </summary>
public double Scale
{
get => scale;
set
{
if (scale != value)
{
scale = value;
LayoutTransform = new ScaleTransform(scale, scale);
}
}
}
/// <summary>
/// Sets the display year filter.
/// </summary>
public double DisplayYear
{
set
{
// Filter nodes and connections based on the year.
logic.DisplayYear = value;
InvalidateVisual();
}
}
/// <summary>
/// Gets the minimum year specified in the nodes and connections.
/// </summary>
public double MinimumYear => logic.MinimumYear;
/// <summary>
/// Gets the bounding area (relative to the diagram) of the primary node.
/// </summary>
public Rect PrimaryNodeBounds => logic.GetNodeBounds(logic.Family.Current);
/// <summary>
/// Gets the bounding area (relative to the diagram) of the selected node.
/// The selected node is the non-primary node that was previously selected
/// to be the primary node.
/// </summary>
public Rect SelectedNodeBounds { get; private set; } = Rect.Empty;
/// <summary>
/// Gets the number of nodes in the diagram.
/// </summary>
public int NodeCount => logic.PersonLookup.Count;
#endregion
#region layout
protected override void OnInitialized(EventArgs e)
{
#if DEBUG
// Context menu so can display row and group borders.
ContextMenu = new ContextMenu();
var item = new MenuItem();
ContextMenu.Items.Add(item);
item.Header = "Show Diagram Outline";
item.Click += OnToggleBorderClick;
item.Foreground = SystemColors.MenuTextBrush;
item.Background = SystemColors.MenuBrush;
#endif
UpdateDiagram();
base.OnInitialized(e);
}
protected override int VisualChildrenCount =>
// Return the number of rows.
rows.Count;
protected override Visual GetVisualChild(int index)
{
// Return the requested row.
return rows[index];
}
protected override Size MeasureOverride(Size availableSize)
{
// Let each row determine how large they want to be.
var size = new Size(double.PositiveInfinity, double.PositiveInfinity);
foreach (var row in rows) row.Measure(size);
// Return the total size of the diagram.
return ArrangeRows(false);
}
protected override Size ArrangeOverride(Size finalSize)
{
// Arrange the rows in the diagram, return the total size.
return ArrangeRows(true);
}
/// <summary>
/// Arrange the rows in the diagram, return the total size.
/// </summary>
private Size ArrangeRows(bool arrange)
{
// Location of the row.
double pos = 0;
// Bounding area of the row.
var bounds = new Rect();
// Total size of the diagram.
var size = new Size(0, 0);
foreach (var row in rows)
{
// Row location, center the row horizontaly.
bounds.Y = pos;
bounds.X = totalSize.Width == 0 ? 0 : bounds.X = (totalSize.Width - row.DesiredSize.Width) / 2;
// Row Size.
bounds.Width = row.DesiredSize.Width;
bounds.Height = row.DesiredSize.Height;
// Arrange the row, save the location.
if (arrange)
{
row.Arrange(bounds);
row.Location = bounds.TopLeft;
}
// Update the size of the diagram.
size.Width = Math.Max(size.Width, bounds.Width);
size.Height = pos + row.DesiredSize.Height;
pos += bounds.Height;
}
// Store the size, this is necessary so the diagram
// can be laid out without a valid Width property.
totalSize = size;
return size;
}
#endregion
#region diagram updates
/// <summary>
/// Reset all of the data associated with the diagram.
/// </summary>
public void Clear()
{
foreach (var row in rows)
{
row.Clear();
RemoveVisualChild(row);
}
rows.Clear();
logic.Clear();
}
/// <summary>
/// Populate the diagram. Update the diagram and hide all non-primary nodes.
/// Then pause, and finish the populate by fading in the new nodes.
/// </summary>
private void Populate()
{
// Set flag to ignore future updates until complete.
populating = true;
// Update the nodes in the diagram.
UpdateDiagram();
// First hide all of the nodes except the primary node.
foreach (var connector in logic.PersonLookup.Values)
if (connector.Node.Person != logic.Family.Current)
connector.Node.Visibility = Visibility.Hidden;
// Required to update (hide) the connector lines.
InvalidateVisual();
InvalidateArrange();
InvalidateMeasure();
// Pause before displaying the new nodes.
animationTimer.Interval = App.GetAnimationDuration(Const.AnimationPauseDuration);
animationTimer.Tick += OnAnimationTimer;
animationTimer.IsEnabled = true;
// Let other controls know the diagram has been repopulated.
OnDiagramPopulated();
}
/// <summary>
/// The animation pause timer is complete, finish populating the diagram.
/// </summary>
private void OnAnimationTimer(object sender, EventArgs e)
{
// Turn off the timer.
animationTimer.IsEnabled = false;
// Fade each node into view.
foreach (var connector in logic.PersonLookup.Values)
if (connector.Node.Visibility != Visibility.Visible)
{
connector.Node.Visibility = Visibility.Visible;
connector.Node.BeginAnimation(OpacityProperty,
new DoubleAnimation(0, 1,
App.GetAnimationDuration(Const.NodeFadeInDuration)));
}
// Redraw connector lines.
InvalidateVisual();
populating = false;
}
/// <summary>
/// Reset the diagram with the nodes. This is accomplished by creating a series of rows.
/// Each row contains a series of groups, and each group contains the nodes. The elements
/// are not laid out at this time. Also creates the connections between the nodes.
/// </summary>
private void UpdateDiagram()
{
// Necessary for Blend.
if (logic.Family == null)
return;
// First reset everything.
Clear();
// Nothing to draw if there is not a primary person.
if (logic.Family.Current == null)
return;
// Primary row.
var primaryPerson = logic.Family.Current;
var primaryRow = logic.CreatePrimaryRow(primaryPerson, 1.0, Const.RelatedMultiplier);
primaryRow.GroupSpace = Const.PrimaryRowGroupSpace;
AddRow(primaryRow);
// Create as many rows as possible until exceed the max node limit.
// Switch between child and parent rows to prevent only creating
// child or parents rows (want to create as many of each as possible).
var nodeCount = NodeCount;
// The scale values of future generations, this makes the nodes
// in each row slightly smaller.
var nodeScale = 1.0;
var childRow = primaryRow;
var parentRow = primaryRow;
while (nodeCount < Const.MaximumNodes && (childRow != null || parentRow != null))
{
// Child Row.
if (childRow != null) childRow = AddChildRow(childRow);
// Parent row.
if (parentRow != null)
{
nodeScale *= Const.GenerationMultiplier;
parentRow = AddParentRow(parentRow, nodeScale);
}
// See if reached node limit yet.
nodeCount = NodeCount;
}
// Raise event so others know the diagram was updated.
OnDiagramUpdated();
// Animate the new person (optional, might not be any new people).
AnimateNewPerson();
}
/// <summary>
/// Add a child row to the diagram.
/// </summary>
private DiagramRow AddChildRow(DiagramRow row)
{
// Get list of children for the current row.
var children = DiagramLogic.GetChildren(row);
if (children.Count == 0) return null;
// Add bottom space to existing row.
row.Margin = new Thickness(0, 0, 0, Const.RowSpace);
// Add another row.
var childRow = logic.CreateChildrenRow(children, 1.0, Const.RelatedMultiplier);
childRow.GroupSpace = Const.ChildRowGroupSpace;
AddRow(childRow);
return childRow;
}
/// <summary>
/// Add a parent row to the diagram.
/// </summary>
private DiagramRow AddParentRow(DiagramRow row, double nodeScale)
{
// Get list of parents for the current row.
var parents = DiagramLogic.GetParents(row);
if (parents.Count == 0) return null;
// Add another row.
var parentRow = logic.CreateParentRow(parents, nodeScale, nodeScale * Const.RelatedMultiplier);
parentRow.Margin = new Thickness(0, 0, 0, Const.RowSpace);
parentRow.GroupSpace = Const.ParentRowGroupSpace;
InsertRow(parentRow);
return parentRow;
}
/// <summary>
/// Add a row to the visual tree.
/// </summary>
private void AddRow(DiagramRow row)
{
if (row != null && row.NodeCount > 0)
{
AddVisualChild(row);
rows.Add(row);
}
}
/// <summary>
/// Insert a row in the visual tree.
/// </summary>
private void InsertRow(DiagramRow row)
{
if (row != null && row.NodeCount > 0)
{
AddVisualChild(row);
rows.Insert(0, row);
}
}
#endregion
} | 31.698653 | 109 | 0.610335 | [
"MIT"
] | VincentH-Net/FamilyShow2022 | src/Microsoft.FamilyShow/Controls/Diagram/Diagram.cs | 18,829 | C# |
namespace Apex.ConnectApi
{
using ApexSharp;
using ApexSharp.ApexAttributes;
using ApexSharp.Implementation;
using global::Apex.System;
/// <summary>
///
/// </summary>
public class ApprovalPostTemplateField
{
// infrastructure
public ApprovalPostTemplateField(dynamic self)
{
Self = self;
}
dynamic Self { get; set; }
static dynamic Implementation
{
get
{
return Implementor.GetImplementation(typeof(ApprovalPostTemplateField));
}
}
// API
object displayName
{
get
{
return Self.displayName;
}
set
{
Self.displayName = value;
}
}
object displayValue
{
get
{
return Self.displayValue;
}
set
{
Self.displayValue = value;
}
}
object record
{
get
{
return Self.record;
}
set
{
Self.record = value;
}
}
public ApprovalPostTemplateField()
{
Self = Implementation.Constructor();
}
public object clone()
{
return Self.clone();
}
public bool equals(object obj)
{
return Self.equals(obj);
}
public double getBuildVersion()
{
return Self.getBuildVersion();
}
public int hashCode()
{
return Self.hashCode();
}
public string toString()
{
return Self.toString();
}
}
}
| 19.010309 | 88 | 0.425163 | [
"MIT"
] | apexsharp/apexsharp | Apex/ConnectApi/ApprovalPostTemplateField.cs | 1,844 | C# |
using AbstractSyntax.SpecialSymbol;
using AbstractSyntax.Symbol;
using AbstractSyntax.Visualizer;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace AbstractSyntax
{
[DebuggerVisualizer(typeof(SyntaxVisualizer), typeof(SyntaxVisualizerSource))]
[Serializable]
public abstract class Element : IReadOnlyTree<Element>
{
private Root _Root;
private Scope _CurrentScope;
private List<Element> Child;
public Element Parent { get; private set; }
public TextPosition Position { get; private set; }
protected Element()
{
Child = new List<Element>();
var root = this as Root;
if (root != null)
{
_Root = root;
}
}
protected Element(TextPosition tp)
{
Child = new List<Element>();
Position = tp;
}
public virtual TypeSymbol ReturnType
{
get { return Root.Void; }
}
public virtual OverLoad OverLoad
{
get { return Root.SimplexManager.Issue(this); }
}
internal virtual IEnumerable<OverLoadCallMatch> GetTypeMatch(IReadOnlyList<GenericsInstance> inst, IReadOnlyList<TypeSymbol> pars, IReadOnlyList<TypeSymbol> args)
{
foreach (var v in ReturnType.GetInstanceMatch(inst, pars, args))
{
yield return v;
}
}
public virtual dynamic GenerateConstantValue()
{
return null;
}
public virtual bool IsConstant
{
get { return false; }
}
public bool IsVoidReturn
{
get { return ReturnType is VoidSymbol; }
}
public Root Root
{
get
{
if (_Root == null)
{
if (Parent != null)
{
_Root = Parent.Root;
}
}
return _Root;
}
}
public Scope CurrentScope
{
get
{
if(_CurrentScope == null)
{
var c = Parent as Scope;
if (c != null)
{
_CurrentScope = c;
}
else if (Parent != null)
{
_CurrentScope = Parent.CurrentScope;
}
}
return _CurrentScope;
}
}
internal void AppendChild(IEnumerable<Element> childs)
{
if(childs == null)
{
return;
}
foreach(var v in childs)
{
AppendChild(v);
}
}
internal void AppendChild(Element child)
{
if (child == null)
{
return;
}
Child.Add(child);
child.RegisterParent(this);
var s = this as Scope;
if(s == null)
{
return;
}
s.SpreadChildScope(child);
}
private void RegisterParent(Element parent)
{
if(Parent != null)
{
throw new InvalidOperationException();
}
Parent = parent;
var s = this as Scope;
if(s == null)
{
return;
}
var cs = CurrentScope;
if(cs == null)
{
return;
}
cs.AppendChildScope(s);
}
internal virtual void Prepare()
{
return;
}
internal virtual void CheckSemantic(CompileMessageManager cmm)
{
return;
}
internal bool HasCurrentAccess(Scope other)
{
var c = CurrentScope;
while (c != null)
{
if (c == other)
{
return true;
}
c = c.CurrentScope;
}
return false;
}
internal T GetParent<T>() where T : Scope
{
var current = CurrentScope;
while (current != null)
{
if (current is T)
{
break;
}
current = current.CurrentScope;
}
return current as T;
}
protected virtual string ElementInfo
{
get { return string.Format("Child = {0}", Count); }
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(Position).Append(" ").Append(this.GetType().Name);
var add = ElementInfo;
if (add != null)
{
builder.Append(": ").Append(add);
}
return builder.ToString();
}
public int Count
{
get { return Child.Count; }
}
public Element this[int index]
{
get { return Child[index]; }
}
public IEnumerator<Element> GetEnumerator()
{
return Child.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
Element IReadOnlyTree<Element>.Root
{
get { return Root; }
}
}
}
| 24.370213 | 170 | 0.440545 | [
"Apache-2.0"
] | B-head/Dreit-prototype | AbstractSyntax/Element.cs | 5,729 | C# |
using Newtonsoft.Json;
namespace SFA.DAS.EmployerDemand.Domain.Demand.Api.Responses
{
public class GetStartCourseDemandResponse
{
[JsonProperty("trainingCourse")]
public TrainingCourse Course { get; set; }
}
} | 23.8 | 60 | 0.710084 | [
"MIT"
] | SkillsFundingAgency/das-employerdemand-web | src/SFA.DAS.EmployerDemand.Domain/Demand/Api/Responses/GetStartCourseDemandResponse.cs | 238 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Outputs.ApiRegistration.V1
{
[OutputType]
public sealed class APIServiceStatus
{
/// <summary>
/// Current service state of apiService.
/// </summary>
public readonly ImmutableArray<Pulumi.Kubernetes.Types.Outputs.ApiRegistration.V1.APIServiceCondition> Conditions;
[OutputConstructor]
private APIServiceStatus(ImmutableArray<Pulumi.Kubernetes.Types.Outputs.ApiRegistration.V1.APIServiceCondition> conditions)
{
Conditions = conditions;
}
}
}
| 30.535714 | 131 | 0.707602 | [
"Apache-2.0"
] | Teshel/pulumi-kubernetes | sdk/dotnet/ApiRegistration/V1/Outputs/APIServiceStatus.cs | 855 | C# |
/*
* Copyright 2017 riddles.io (developers@riddles.io)
*
* 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.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GoladBot.Player
{
/**
* Stores all information about a player
*/
public class Player
{
public string Name { get; private set; }
public int LivingCells { get; set; }
public string previousMove { get; set; }
public Player(string playerName)
{
Name = playerName;
}
}
}
| 31.243243 | 79 | 0.653979 | [
"Apache-2.0"
] | riddlesio/golad-starterbot-cs | Player/Player.cs | 1,156 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sfa.Tl.Matching.Application.Interfaces;
using Sfa.Tl.Matching.Data.Interfaces;
using Sfa.Tl.Matching.Domain.Models;
using Sfa.Tl.Matching.Models.Command;
using Sfa.Tl.Matching.Models.Enums;
namespace Sfa.Tl.Matching.Application.Services
{
public class ReferralService : IReferralService
{
private readonly IMessageQueueService _messageQueueService;
private readonly IRepository<OpportunityItem> _opportunityItemRepository;
private readonly IRepository<BackgroundProcessHistory> _backgroundProcessHistoryRepository;
public ReferralService(
IMessageQueueService messageQueueService,
IRepository<OpportunityItem> opportunityItemRepository,
IRepository<BackgroundProcessHistory> backgroundProcessHistoryRepository)
{
_messageQueueService = messageQueueService;
_opportunityItemRepository = opportunityItemRepository;
_backgroundProcessHistoryRepository = backgroundProcessHistoryRepository;
}
public async Task ConfirmOpportunitiesAsync(int opportunityId, string username)
{
var itemIds = GetOpportunityItemIds(opportunityId);
await RequestReferralEmailsAsync(opportunityId, itemIds.ToList(), username);
}
private async Task RequestReferralEmailsAsync(int opportunityId, IList<int> itemIds, string username)
{
await _messageQueueService.PushEmployerReferralEmailMessageAsync(new SendEmployerReferralEmail
{
OpportunityId = opportunityId,
ItemIds = itemIds,
BackgroundProcessHistoryId = await CreateAndGetBackgroundProcessIdAsync(BackgroundProcessType.EmployerReferralEmail, username)
});
await _messageQueueService.PushProviderReferralEmailMessageAsync(new SendProviderReferralEmail
{
OpportunityId = opportunityId,
ItemIds = itemIds,
BackgroundProcessHistoryId = await CreateAndGetBackgroundProcessIdAsync(BackgroundProcessType.ProviderReferralEmail, username)
});
}
private async Task<int> CreateAndGetBackgroundProcessIdAsync(BackgroundProcessType processType, string username)
{
return await _backgroundProcessHistoryRepository.CreateAsync(
new BackgroundProcessHistory
{
ProcessType = processType.ToString(),
Status = BackgroundProcessHistoryStatus.Pending.ToString(),
CreatedBy = username
});
}
private IEnumerable<int> GetOpportunityItemIds(int opportunityId)
{
var itemIds = _opportunityItemRepository.GetManyAsync(oi => oi.Opportunity.Id == opportunityId
&& oi.IsSaved
&& oi.IsSelectedForReferral
&& !oi.IsCompleted)
.Select(oi => oi.Id).ToList();
return itemIds;
}
}
}
| 42.298701 | 142 | 0.649064 | [
"MIT"
] | uk-gov-mirror/SkillsFundingAgency.tl-matching | src/Sfa.Tl.Matching.Application/Services/ReferralService.cs | 3,259 | 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 Main.ExtensionViews {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("C:\\Users\\kcsorensen\\Documents\\GitHub\\MadplanVBK\\Madplan\\Main\\ExtensionViews\\DataE" +
"ntryCell.xaml")]
public partial class DataEntryCell : global::Xamarin.Forms.ViewCell {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(DataEntryCell));
}
}
}
| 40.166667 | 148 | 0.563278 | [
"MIT"
] | Kcsorensen/MadplanVBK | Madplan/Main/obj/Debug/netstandard1.4/Main.ExtensionViews.DataEntryCell.xaml.g.cs | 964 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslynator.CSharp.Syntax;
namespace Roslynator.CSharp.Analysis
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class UnnecessaryExplicitUseOfEnumeratorAnalyzer : BaseDiagnosticAnalyzer
{
private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
if (_supportedDiagnostics.IsDefault)
Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator);
return _supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterSyntaxNodeAction(f => AnalyzeUsingStatement(f), SyntaxKind.UsingStatement);
}
private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context)
{
var usingStatement = (UsingStatementSyntax)context.Node;
VariableDeclaratorSyntax declarator = usingStatement.Declaration?.Variables.SingleOrDefault(shouldThrow: false);
if (declarator == null)
return;
if (usingStatement.Statement?.SingleNonBlockStatementOrDefault() is not WhileStatementSyntax whileStatement)
return;
SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(whileStatement.Condition);
if (!invocationInfo.Success)
return;
if (invocationInfo.Arguments.Any())
return;
if (!string.Equals(invocationInfo.NameText, WellKnownMemberNames.MoveNextMethodName, StringComparison.Ordinal))
return;
if (!string.Equals((invocationInfo.Expression as IdentifierNameSyntax)?.Identifier.ValueText, declarator.Identifier.ValueText, StringComparison.Ordinal))
return;
SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(declarator.Initializer.Value);
if (!invocationInfo2.Success)
return;
if (invocationInfo2.Arguments.Any())
return;
if (!string.Equals(invocationInfo2.NameText, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.Ordinal))
return;
bool? isFixable;
UnnecessaryUsageOfEnumeratorWalker walker = null;
try
{
walker = UnnecessaryUsageOfEnumeratorWalker.GetInstance();
walker.SetValues(declarator, context.SemanticModel, context.CancellationToken);
walker.Visit(whileStatement.Statement);
isFixable = walker.IsFixable;
}
finally
{
if (walker != null)
UnnecessaryUsageOfEnumeratorWalker.Free(walker);
}
if (isFixable == true)
{
DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator, usingStatement.UsingKeyword);
}
}
}
}
| 36.575758 | 165 | 0.667495 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Analyzers/CSharp/Analysis/UnnecessaryExplicitUseOfEnumeratorAnalyzer.cs | 3,623 | C# |
public interface IPoolObject
{
void OnSpawn();
}
| 10.8 | 29 | 0.685185 | [
"MIT"
] | jotask/AsteroidsClone | Assets/Scripts/IPoolObject.cs | 56 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NTRCheck.Views
{
/// <summary>
/// Logique d'interaction pour Test.xaml
/// </summary>
public partial class Test : UserControl
{
public Test()
{
InitializeComponent();
}
}
}
| 20.103448 | 41 | 0.763293 | [
"MIT"
] | dfgs/NTRCheck | NTRCheck/Views/Test.xaml.cs | 585 | C# |
using System;
namespace ALE.ETLBox.DataFlow
{
public interface IDataFlowTransformation<TInput, TOutput> : IDataFlowLinkSource<TOutput>, IDataFlowLinkTarget<TInput>
{
}
}
| 18.5 | 121 | 0.751351 | [
"MIT"
] | SipanOhanyan/etlbox | ETLBox/src/Definitions/DataFlow/IDataFlowTransformation.cs | 187 | C# |
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Web.Administration
{
public sealed class ApplicationPoolDefaults : ConfigurationElement
{
private ApplicationPoolRecycling _recycling;
private ApplicationPoolProcessModel _model;
private ApplicationPoolFailure _failure;
private ApplicationPoolCpu _cpu;
internal ApplicationPoolDefaults(ConfigurationElement element, ConfigurationElement parent)
: base(element, "applicationPoolDefaults", null, parent, null, null)
{
}
public bool AutoStart
{
get { return (bool)this["autoStart"]; }
set { this["autoStart"] = value; }
}
public ApplicationPoolCpu Cpu
{
get { return _cpu ?? (_cpu = new ApplicationPoolCpu(ChildElements["cpu"], this)); }
}
public bool Enable32BitAppOnWin64
{
get { return (bool)this["enable32BitAppOnWin64"]; }
set { this["enable32BitAppOnWin64"] = value; }
}
public ApplicationPoolFailure Failure
{
get { return _failure ?? (_failure = new ApplicationPoolFailure(ChildElements["failure"], this)); }
}
public ManagedPipelineMode ManagedPipelineMode
{
get { return (ManagedPipelineMode)Enum.ToObject(typeof(ManagedPipelineMode), this["managedPipelineMode"]); }
set { this["managedPipelineMode"] = (long)value; }
}
public string ManagedRuntimeVersion
{
get { return this["managedRuntimeVersion"].ToString(); }
set { this["managedRuntimeVersion"] = value; }
}
public ApplicationPoolProcessModel ProcessModel
{
get { return _model ?? (_model = new ApplicationPoolProcessModel(ChildElements["processModel"], this)); }
}
public long QueueLength
{
get { return Convert.ToInt64(this["queueLength"]); }
set { this["queueLength"] = Convert.ToUInt32(value); }
}
public ApplicationPoolRecycling Recycling
{
get { return _recycling ?? (_recycling = new ApplicationPoolRecycling(ChildElements["recycling"], this)); }
}
public StartMode StartMode
{
get { return (StartMode)Enum.ToObject(typeof(StartMode), this["startMode"]); }
set { this["startMode"] = (long)value; }
}
}
}
| 33.153846 | 120 | 0.614462 | [
"MIT"
] | 68681395/JexusManager | Microsoft.Web.Administration/ApplicationPoolDefaults.cs | 2,588 | C# |
using System;
using Custom.Algebra.QrCode.Encoding.Terminate;
using com.google.zxing.qrcode.encoder;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Custom.Algebra.QrCode.Encoding.Tests.PerformanceTest
{
using Assert = NUnit.Framework.Assert;
using CollectionAssert = NUnit.Framework.CollectionAssert;
using TestAttribute = NUnit.Framework.TestAttribute;
using TestCaseAttribute = NUnit.Framework.TestCaseAttribute;
using TestFixtureAttribute = NUnit.Framework.TestFixtureAttribute;
[TestClass, TestFixture]
public class TerminatorPTest
{
[Test, TestMethod]
public void PerformanceTest()
{
Stopwatch sw = new Stopwatch();
int timesofTest = 1000;
string[] timeElapsed = new string[2];
sw.Start();
for(int i = 0; i < timesofTest; i++)
{
BitList list = new BitList();
list.TerminateBites(0, 400);
}
sw.Stop();
timeElapsed[0] = sw.ElapsedMilliseconds.ToString();
sw.Reset();
sw.Start();
for(int i = 0; i < timesofTest; i++)
{
BitVector headerAndDataBits = new BitVector();
//headerAndDataBits.Append(1, 1);
EncoderInternal.terminateBits(400, headerAndDataBits);
}
sw.Stop();
timeElapsed[1] = sw.ElapsedMilliseconds.ToString();
Assert.Pass("Terminator performance {0} Tests~ QrCode.Net: {1} ZXing: {2}", timesofTest, timeElapsed[0], timeElapsed[1]);
}
}
}
| 25.896552 | 125 | 0.665113 | [
"Apache-2.0"
] | InnPad/Formall.NET | Formall.MySql/branches/WebSiteWithPresentation/QrCode.Tests/PerformanceTest/TerminatorPTest.cs | 1,504 | C# |
namespace NServiceBus.AcceptanceTests.Basic
{
using System.Threading.Tasks;
using AcceptanceTesting;
using EndpointTemplates;
using Features;
using NUnit.Framework;
public class When_depending_on_untyped_feature : NServiceBusAcceptanceTest
{
[Test]
public async Task Should_enable_when_untyped_dependency_enabled()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<EndpointWithFeatures>(b => b.CustomConfig(c =>
{
c.EnableFeature<UntypedDependentFeature>();
c.EnableFeature<DependencyFeature>();
}))
.Done(c => c.EndpointsStarted)
.Run();
Assert.That(context.UntypedDependencyFeatureSetUp, Is.True);
}
[Test]
public async Task Should_disable_when_untyped_dependency_disabled()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<EndpointWithFeatures>(b => b.CustomConfig(c =>
{
c.DisableFeature<UntypedDependentFeature>();
c.EnableFeature<DependencyFeature>();
}))
.Done(c => c.EndpointsStarted)
.Run();
Assert.That(context.UntypedDependencyFeatureSetUp, Is.False);
}
class Context : ScenarioContext
{
public bool UntypedDependencyFeatureSetUp { get; set; }
}
public class EndpointWithFeatures : EndpointConfigurationBuilder
{
public EndpointWithFeatures()
{
EndpointSetup<DefaultServer>();
}
}
public class UntypedDependentFeature : Feature
{
public UntypedDependentFeature()
{
var featureTypeFullName = typeof(DependencyFeature).FullName;
DependsOn(featureTypeFullName);
}
protected override void Setup(FeatureConfigurationContext context)
{
var testContext = (Context) context.Settings.Get<ScenarioContext>();
testContext.UntypedDependencyFeatureSetUp = true;
}
}
public class DependencyFeature : Feature
{
protected override void Setup(FeatureConfigurationContext context)
{
}
}
}
} | 33.026316 | 85 | 0.551793 | [
"MIT"
] | JTOne123/NServiceBus.MongoDB | src/NServiceBus.MongoDB.Acceptance.Tests/App_Packages/NSB.AcceptanceTests.6.0.0/Basic/When_depending_on_untyped_feature.cs | 2,510 | C# |
using System;
using System.Windows.Forms;
namespace DemoFramework
{
public partial class LibrarySelection : Form
{
public LibrarySelection()
{
InitializeComponent();
AcceptButton = runButton;
CancelButton = cancelButton;
string[] supportedLibraries = LibraryManager.GetSupportedLibraries();
int selectLibrary = 0;
foreach (string library in supportedLibraries)
{
if (LibraryManager.IsLibraryAvailable(library))
{
int index = libraryList.Items.Add(library);
logText.Text += library + " OK\r\n";
if (library.Equals(LibraryManager.GraphicsLibraryName))
{
selectLibrary = index;
}
}
else
{
logText.Text += library + " not loaded\r\n";
}
}
if (libraryList.Items.Count != 0)
{
runButton.Enabled = true;
libraryList.SelectedIndex = selectLibrary;
}
LibraryManager.GraphicsLibraryName = null;
libraryList.DoubleClick += new EventHandler(libraryList_DoubleClick);
}
void libraryList_DoubleClick(object sender, EventArgs e)
{
LibraryManager.GraphicsLibraryName = libraryList.SelectedItem as string;
Close();
}
private void runButton_Click(object sender, EventArgs e)
{
LibraryManager.GraphicsLibraryName = libraryList.SelectedItem as string;
Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
}
}
| 30.419355 | 85 | 0.509544 | [
"MIT"
] | yoshinoToylogic/bulletsharp | demos/Generic/DemoFramework/Graphics/LibrarySelection.cs | 1,888 | C# |
using SharpShoppingList.Models;
namespace SharpShoppingList.ViewModels
{
public class ShoppingListViewModel
{
public ShoppingList ShoppingList { get; set; }
public bool Selected { get; set; }
}
} | 20.454545 | 54 | 0.693333 | [
"MIT"
] | benfo/SharpShoppingList | SharpShoppingList.Shared/ViewModels/ShoppingListViewModel.cs | 225 | C# |
namespace MassTransit.Tests.Pipeline
{
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GreenPipes;
using NUnit.Framework;
using TestFramework;
using Util;
[TestFixture]
public class Partitioning_a_consumer_by_key :
InMemoryTestFixture
{
[Test]
public async Task Should_use_a_partitioner_for_consistency()
{
await Task.WhenAll(Enumerable.Range(0, Limit).Select(index => Bus.Publish(new PartitionedMessage {CorrelationId = NewId.NextGuid()})));
var count = await _completed.Task;
Assert.AreEqual(Limit, count);
Console.WriteLine("Processed: {0}", count);
//Console.WriteLine(Bus.GetProbeResult().ToJsonString());
}
TaskCompletionSource<int> _completed;
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
_completed = GetTask<int>();
configurator.Consumer(() => new PartitionedConsumer(_completed), x =>
{
x.Message<PartitionedMessage>(m =>
{
m.UsePartitioner(8, context => context.Message.CorrelationId);
});
});
}
const int Limit = 100;
class PartitionedConsumer :
IConsumer<PartitionedMessage>
{
static int _count;
readonly TaskCompletionSource<int> _completed;
public PartitionedConsumer(TaskCompletionSource<int> completed)
{
_completed = completed;
}
public Task Consume(ConsumeContext<PartitionedMessage> context)
{
if (Interlocked.Increment(ref _count) == Limit)
_completed.TrySetResult(Limit);
return TaskUtil.Completed;
}
}
class PartitionedMessage
{
public Guid CorrelationId { get; set; }
}
}
}
| 28.171053 | 148 | 0.562354 | [
"ECL-2.0",
"Apache-2.0"
] | AlexGoemanDigipolis/MassTransit | tests/MassTransit.Tests/Pipeline/PartitionByKey_Specs.cs | 2,143 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.ML.Core.Data;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.FastTree;
using Microsoft.ML.Runtime.FastTree.Internal;
using Microsoft.ML.Runtime.Internal.Internallearn;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using Microsoft.ML.Runtime.Training;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
// REVIEW: Do we really need all these names?
[assembly: LoadableClass(FastTreeRankingTrainer.Summary, typeof(FastTreeRankingTrainer), typeof(FastTreeRankingTrainer.Arguments),
new[] { typeof(SignatureRankerTrainer), typeof(SignatureTrainer), typeof(SignatureTreeEnsembleTrainer), typeof(SignatureFeatureScorerTrainer) },
FastTreeRankingTrainer.UserNameValue,
FastTreeRankingTrainer.LoadNameValue,
FastTreeRankingTrainer.ShortName,
// FastRank names
"FastRankRanking",
"FastRankRankingWrapper",
"rank",
"frrank",
"btrank")]
[assembly: LoadableClass(typeof(FastTreeRankingPredictor), null, typeof(SignatureLoadModel),
"FastTree Ranking Executor",
FastTreeRankingPredictor.LoaderSignature)]
[assembly: LoadableClass(typeof(void), typeof(FastTree), null, typeof(SignatureEntryPointModule), "FastTree")]
namespace Microsoft.ML.Runtime.FastTree
{
/// <include file='doc.xml' path='doc/members/member[@name="FastTree"]/*' />
public sealed partial class FastTreeRankingTrainer
: BoostingFastTreeTrainerBase<FastTreeRankingTrainer.Arguments, RankingPredictionTransformer<FastTreeRankingPredictor>, FastTreeRankingPredictor>,
IHasLabelGains
{
internal const string LoadNameValue = "FastTreeRanking";
internal const string UserNameValue = "FastTree (Boosted Trees) Ranking";
internal const string Summary = "Trains gradient boosted decision trees to the LambdaRank quasi-gradient.";
internal const string ShortName = "ftrank";
private IEnsembleCompressor<short> _ensembleCompressor;
private Test _specialTrainSetTest;
private TestHistory _firstTestSetHistory;
/// <summary>
/// The prediction kind for this trainer.
/// </summary>
public override PredictionKind PredictionKind => PredictionKind.Ranking;
/// <summary>
/// Initializes a new instance of <see cref="FastTreeRankingTrainer"/>
/// </summary>
/// <param name="env">The private instance of <see cref="IHostEnvironment"/>.</param>
/// <param name="labelColumn">The name of the label column.</param>
/// <param name="featureColumn">The name of the feature column.</param>
/// <param name="groupIdColumn">The name for the column containing the group ID. </param>
/// <param name="weightColumn">The name for the column containing the initial weight.</param>
/// <param name="advancedSettings">A delegate to apply all the advanced arguments to the algorithm.</param>
public FastTreeRankingTrainer(IHostEnvironment env, string labelColumn, string featureColumn, string groupIdColumn,
string weightColumn = null, Action<Arguments> advancedSettings = null)
: base(env, TrainerUtils.MakeR4ScalarLabel(labelColumn), featureColumn, weightColumn, groupIdColumn, advancedSettings: advancedSettings)
{
Host.CheckNonEmpty(labelColumn, nameof(labelColumn));
Host.CheckNonEmpty(featureColumn, nameof(featureColumn));
Host.CheckNonEmpty(groupIdColumn, nameof(groupIdColumn));
}
/// <summary>
/// Initializes a new instance of <see cref="FastTreeRankingTrainer"/> by using the legacy <see cref="Arguments"/> class.
/// </summary>
internal FastTreeRankingTrainer(IHostEnvironment env, Arguments args)
: base(env, args, TrainerUtils.MakeR4ScalarLabel(args.LabelColumn))
{
}
protected override float GetMaxLabel()
{
return GetLabelGains().Length - 1;
}
protected override FastTreeRankingPredictor TrainModelCore(TrainContext context)
{
Host.CheckValue(context, nameof(context));
var trainData = context.TrainingSet;
ValidData = context.ValidationSet;
using (var ch = Host.Start("Training"))
{
var maxLabel = GetLabelGains().Length - 1;
ConvertData(trainData);
TrainCore(ch);
FeatureCount = trainData.Schema.Feature.Type.ValueCount;
ch.Done();
}
return new FastTreeRankingPredictor(Host, TrainedEnsemble, FeatureCount, InnerArgs);
}
public Double[] GetLabelGains()
{
try
{
Host.AssertValue(Args.CustomGains);
return Args.CustomGains.Split(',').Select(k => Convert.ToDouble(k.Trim())).ToArray();
}
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
throw Host.Except(ex, "Error in the format of custom gains. Inner exception is {0}", ex.Message);
throw;
}
}
protected override void CheckArgs(IChannel ch)
{
if (!string.IsNullOrEmpty(Args.CustomGains))
{
var stringGain = Args.CustomGains.Split(',');
if (stringGain.Length < 5)
{
throw ch.ExceptUserArg(nameof(Args.CustomGains),
"{0} an invalid number of gain levels. We require at least 5. Make certain they're comma separated.",
stringGain.Length);
}
Double[] gain = new Double[stringGain.Length];
for (int i = 0; i < stringGain.Length; ++i)
{
if (!Double.TryParse(stringGain[i], out gain[i]))
{
throw ch.ExceptUserArg(nameof(Args.CustomGains),
"Could not parse '{0}' as a floating point number", stringGain[0]);
}
}
DcgCalculator.LabelGainMap = gain;
Dataset.DatasetSkeleton.LabelGainMap = gain;
}
ch.CheckUserArg((Args.EarlyStoppingRule == null && !Args.EnablePruning) || (Args.EarlyStoppingMetrics == 1 || Args.EarlyStoppingMetrics == 3), nameof(Args.EarlyStoppingMetrics),
"earlyStoppingMetrics should be 1 or 3.");
base.CheckArgs(ch);
}
protected override void Initialize(IChannel ch)
{
base.Initialize(ch);
if (Args.CompressEnsemble)
{
_ensembleCompressor = new LassoBasedEnsembleCompressor();
_ensembleCompressor.Initialize(Args.NumTrees, TrainSet, TrainSet.Ratings, Args.RngSeed);
}
}
protected override ObjectiveFunctionBase ConstructObjFunc(IChannel ch)
{
return new LambdaRankObjectiveFunction(TrainSet, TrainSet.Ratings, Args, ParallelTraining);
}
protected override OptimizationAlgorithm ConstructOptimizationAlgorithm(IChannel ch)
{
OptimizationAlgorithm optimizationAlgorithm = base.ConstructOptimizationAlgorithm(ch);
if (Args.UseLineSearch)
{
_specialTrainSetTest = new FastNdcgTest(optimizationAlgorithm.TrainingScores, TrainSet.Ratings, Args.SortingAlgorithm, Args.EarlyStoppingMetrics);
optimizationAlgorithm.AdjustTreeOutputsOverride = new LineSearch(_specialTrainSetTest, 0, Args.NumPostBracketSteps, Args.MinStepSize);
}
return optimizationAlgorithm;
}
protected override BaggingProvider CreateBaggingProvider()
{
Host.Assert(Args.BaggingSize > 0);
return new RankingBaggingProvider(TrainSet, Args.NumLeaves, Args.RngSeed, Args.BaggingTrainFraction);
}
protected override void PrepareLabels(IChannel ch)
{
}
protected override Test ConstructTestForTrainingData()
{
return new NdcgTest(ConstructScoreTracker(TrainSet), TrainSet.Ratings, Args.SortingAlgorithm);
}
protected override void InitializeTests()
{
if (Args.TestFrequency != int.MaxValue)
{
AddFullTests();
}
if (Args.PrintTestGraph)
{
// If FirstTestHistory is null (which means the tests were not intialized due to /tf==infinity)
// We need initialize first set for graph printing
// Adding to a tests would result in printing the results after final iteration
if (_firstTestSetHistory == null)
{
var firstTestSetTest = CreateFirstTestSetTest();
_firstTestSetHistory = new TestHistory(firstTestSetTest, 0);
}
}
// Tests for early stopping.
TrainTest = CreateSpecialTrainSetTest();
if (ValidSet != null)
ValidTest = CreateSpecialValidSetTest();
if (Args.PrintTrainValidGraph && Args.EnablePruning && _specialTrainSetTest == null)
{
_specialTrainSetTest = CreateSpecialTrainSetTest();
}
if (Args.EnablePruning && ValidTest != null)
{
if (!Args.UseTolerantPruning)
{
//use simple eraly stopping condition
PruningTest = new TestHistory(ValidTest, 0);
}
else
{
//use tolerant stopping condition
PruningTest = new TestWindowWithTolerance(ValidTest, 0, Args.PruningWindowSize, Args.PruningThreshold);
}
}
}
private void AddFullTests()
{
Tests.Add(CreateStandardTest(TrainSet));
if (ValidSet != null)
{
Test test = CreateStandardTest(ValidSet);
Tests.Add(test);
}
for (int t = 0; TestSets != null && t < TestSets.Length; ++t)
{
Test test = CreateStandardTest(TestSets[t]);
if (t == 0)
{
_firstTestSetHistory = new TestHistory(test, 0);
}
Tests.Add(test);
}
}
protected override void PrintIterationMessage(IChannel ch, IProgressChannel pch)
{
// REVIEW: Shift to using progress channels to report this information.
#if OLD_TRACE
// This needs to be executed every iteration.
if (PruningTest != null)
{
if (PruningTest is TestWindowWithTolerance)
{
if (PruningTest.BestIteration != -1)
ch.Info("Iteration {0} \t(Best tolerated validation moving average NDCG@{1} {2}:{3:00.00}~{4:00.00})",
Ensemble.NumTrees,
_args.earlyStoppingMetrics,
PruningTest.BestIteration,
100 * (PruningTest as TestWindowWithTolerance).BestAverageValue,
100 * (PruningTest as TestWindowWithTolerance).CurrentAverageValue);
else
ch.Info("Iteration {0}", Ensemble.NumTrees);
}
else
{
ch.Info("Iteration {0} \t(best validation NDCG@{1} {2}:{3:00.00}>{4:00.00})",
Ensemble.NumTrees,
_args.earlyStoppingMetrics,
PruningTest.BestIteration,
100 * PruningTest.BestResult.FinalValue,
100 * PruningTest.ComputeTests().First().FinalValue);
}
}
else
base.PrintIterationMessage(ch, pch);
#else
base.PrintIterationMessage(ch, pch);
#endif
}
protected override void ComputeTests()
{
if (_firstTestSetHistory != null)
_firstTestSetHistory.ComputeTests();
if (_specialTrainSetTest != null)
_specialTrainSetTest.ComputeTests();
if (PruningTest != null)
PruningTest.ComputeTests();
}
protected override string GetTestGraphLine()
{
StringBuilder lineBuilder = new StringBuilder();
lineBuilder.AppendFormat("Eval:\tnet.{0:D8}.ini", Ensemble.NumTrees - 1);
foreach (var r in _firstTestSetHistory.ComputeTests())
{
lineBuilder.AppendFormat("\t{0:0.0000}", r.FinalValue);
}
double trainTestResult = 0.0;
double validTestResult = 0.0;
// We only print non-zero train&valid graph if earlyStoppingTruncation!=0
// In case /es is not set, we print 0 for train and valid graph NDCG
// Let's keeping this behaviour for backward compatibility with previous FR version
// Ideally /graphtv should enforce non-zero /es in the commandline validation
if (_specialTrainSetTest != null)
{
trainTestResult = _specialTrainSetTest.ComputeTests().First().FinalValue;
}
if (PruningTest != null)
{
validTestResult = PruningTest.ComputeTests().First().FinalValue;
}
lineBuilder.AppendFormat("\t{0:0.0000}\t{1:0.0000}", trainTestResult, validTestResult);
return lineBuilder.ToString();
}
protected override void Train(IChannel ch)
{
base.Train(ch);
// Print final last iteration.
// Note that trainNDCG printed in graph will be from copy of a value from previous iteration
// and will diffre slightly from the proper final value computed by FullTest.
// We cannot compute the final NDCG here due to the fact we use FastNDCGTestForTrainSet computing NDCG based on label sort saved during gradient computation (and we don;t have gradients for n+1 iteration)
// Keeping it in sync with original FR code
PrintTestGraph(ch);
}
protected override void CustomizedTrainingIteration(RegressionTree tree)
{
Contracts.AssertValueOrNull(tree);
if (tree != null && Args.CompressEnsemble)
{
double[] trainOutputs = Ensemble.GetTreeAt(Ensemble.NumTrees - 1).GetOutputs(TrainSet);
_ensembleCompressor.SetTreeScores(Ensemble.NumTrees - 1, trainOutputs);
}
}
/// <summary>
/// Create standard test for dataset.
/// </summary>
/// <param name="dataset">dataset used for testing</param>
/// <returns>standard test for the dataset</returns>
private Test CreateStandardTest(Dataset dataset)
{
if (Utils.Size(dataset.MaxDcg) == 0)
dataset.Skeleton.RecomputeMaxDcg(10);
return new NdcgTest(
ConstructScoreTracker(dataset),
dataset.Ratings,
Args.SortingAlgorithm);
}
/// <summary>
/// Create the special test for train set.
/// </summary>
/// <returns>test for train set</returns>
private Test CreateSpecialTrainSetTest()
{
return new FastNdcgTestForTrainSet(
OptimizationAlgorithm.TrainingScores,
OptimizationAlgorithm.ObjectiveFunction as LambdaRankObjectiveFunction,
TrainSet.Ratings,
Args.SortingAlgorithm,
Args.EarlyStoppingMetrics);
}
/// <summary>
/// Create the special test for valid set.
/// </summary>
/// <returns>test for train set</returns>
private Test CreateSpecialValidSetTest()
{
return new FastNdcgTest(
ConstructScoreTracker(ValidSet),
ValidSet.Ratings,
Args.SortingAlgorithm,
Args.EarlyStoppingMetrics);
}
/// <summary>
/// Create the test for the first test set.
/// </summary>
/// <returns>test for the first test set</returns>
private Test CreateFirstTestSetTest()
{
return CreateStandardTest(TestSets[0]);
}
/// <summary>
/// Get the header of test graph
/// </summary>
/// <returns>Test graph header</returns>
protected override string GetTestGraphHeader()
{
StringBuilder headerBuilder = new StringBuilder("Eval:\tFileName\tNDCG@1\tNDCG@2\tNDCG@3\tNDCG@4\tNDCG@5\tNDCG@6\tNDCG@7\tNDCG@8\tNDCG@9\tNDCG@10");
if (Args.PrintTrainValidGraph)
{
headerBuilder.Append("\tNDCG@20\tNDCG@40");
headerBuilder.AppendFormat(
"\nNote: Printing train NDCG@{0} as NDCG@20 and validation NDCG@{0} as NDCG@40..\n",
Args.EarlyStoppingMetrics);
}
return headerBuilder.ToString();
}
protected override RankingPredictionTransformer<FastTreeRankingPredictor> MakeTransformer(FastTreeRankingPredictor model, ISchema trainSchema)
=> new RankingPredictionTransformer<FastTreeRankingPredictor>(Host, model, trainSchema, FeatureColumn.Name);
protected override SchemaShape.Column[] GetOutputColumnsCore(SchemaShape inputSchema)
{
return new[]
{
new SchemaShape.Column(DefaultColumnNames.Score, SchemaShape.Column.VectorKind.Scalar, NumberType.R4, false, new SchemaShape(MetadataUtils.GetTrainerOutputMetadata()))
};
}
public sealed class LambdaRankObjectiveFunction : ObjectiveFunctionBase, IStepSearch
{
private readonly short[] _labels;
private enum DupeIdInfo
{
NoInformation = 0,
Unique = 1,
FormatNotSupported = 1000000,
Code404 = 1000001
};
// precomputed arrays
private readonly double[] _inverseMaxDcgt;
private readonly double[] _discount;
private readonly int[] _oneTwoThree;
private int[][] _labelCounts;
// reusable memory, technical stuff
private int[][] _permutationBuffers;
private DcgPermutationComparer[] _comparers;
//gains
private double[] _gain;
private double[] _gainLabels;
// parameters
private int _maxDcgTruncationLevel;
private bool _trainDcg;
// A lookup table for the sigmoid used in the lambda calculation
// Note: Is built for a specific sigmoid parameter, so assumes this will be constant throughout computation
private double[] _sigmoidTable;
private double _minScore; // Computed: range of scores covered in table
private double _maxScore;
private double _minSigmoid;
private double _maxSigmoid;
private double _scoreToSigmoidTableFactor;
private const double _expAsymptote = -50; // exp( x < expAsymptote ) is assumed to be 0
private const int _sigmoidBins = 1000000; // Number of bins in the lookup table
// Secondary gains, currently not used in any way.
#pragma warning disable 0649
private double _secondaryMetricShare;
private double[] _secondaryInverseMaxDcgt;
private double[] _secondaryGains;
#pragma warning restore 0649
// Baseline risk.
private static int _iteration = 0; // This is a static class global member which keeps track of the iterations.
private double[] _baselineDcg;
private double[] _baselineAlpha;
private double _baselineAlphaCurrent;
// Current iteration risk statistics.
private double _idealNextRisk;
private double _currentRisk;
private double _countRisk;
// These reusable buffers are used for
// 1. preprocessing the scores for continuous cost function
// 2. shifted NDCG
// 3. max DCG per query
private double[] _scoresCopy;
private short[] _labelsCopy;
private short[] _groupIdToTopLabel;
// parameters
private double _sigmoidParam;
private char _costFunctionParam;
private bool _filterZeroLambdas;
private bool _distanceWeight2;
private bool _normalizeQueryLambdas;
private bool _useShiftedNdcg;
private IParallelTraining _parallelTraining;
// Used for training NDCG calculation
// Keeps track of labels of top 3 documents per query
public short[][] TrainQueriesTopLabels;
public LambdaRankObjectiveFunction(Dataset trainset, short[] labels, Arguments args, IParallelTraining parallelTraining)
: base(trainset,
args.LearningRates,
args.Shrinkage,
args.MaxTreeOutput,
args.GetDerivativesSampleRate,
args.BestStepRankingRegressionTrees,
args.RngSeed)
{
_labels = labels;
TrainQueriesTopLabels = new short[Dataset.NumQueries][];
for (int q = 0; q < Dataset.NumQueries; ++q)
TrainQueriesTopLabels[q] = new short[3];
_labelCounts = new int[Dataset.NumQueries][];
int relevancyLevel = DcgCalculator.LabelGainMap.Length;
for (int q = 0; q < Dataset.NumQueries; ++q)
_labelCounts[q] = new int[relevancyLevel];
// precomputed arrays
_maxDcgTruncationLevel = args.LambdaMartMaxTruncation;
_trainDcg = args.TrainDcg;
if (_trainDcg)
{
_inverseMaxDcgt = new double[Dataset.NumQueries];
for (int q = 0; q < Dataset.NumQueries; ++q)
_inverseMaxDcgt[q] = 1.0;
}
else
{
_inverseMaxDcgt = DcgCalculator.MaxDcg(_labels, Dataset.Boundaries, _maxDcgTruncationLevel, _labelCounts);
for (int q = 0; q < Dataset.NumQueries; ++q)
_inverseMaxDcgt[q] = 1.0 / _inverseMaxDcgt[q];
}
_discount = new double[Dataset.MaxDocsPerQuery];
FillDiscounts(args.PositionDiscountFreeform);
_oneTwoThree = new int[Dataset.MaxDocsPerQuery];
for (int d = 0; d < Dataset.MaxDocsPerQuery; ++d)
_oneTwoThree[d] = d;
// reusable resources
int numThreads = BlockingThreadPool.NumThreads;
_comparers = new DcgPermutationComparer[numThreads];
for (int i = 0; i < numThreads; ++i)
_comparers[i] = DcgPermutationComparerFactory.GetDcgPermutationFactory(args.SortingAlgorithm);
_permutationBuffers = new int[numThreads][];
for (int i = 0; i < numThreads; ++i)
_permutationBuffers[i] = new int[Dataset.MaxDocsPerQuery];
_gain = Dataset.DatasetSkeleton.LabelGainMap;
FillGainLabels();
#region parameters
_sigmoidParam = args.LearningRates;
_costFunctionParam = args.CostFunctionParam;
_distanceWeight2 = args.DistanceWeight2;
_normalizeQueryLambdas = args.NormalizeQueryLambdas;
_useShiftedNdcg = args.ShiftedNdcg;
_filterZeroLambdas = args.FilterZeroLambdas;
#endregion
_scoresCopy = new double[Dataset.NumDocs];
_labelsCopy = new short[Dataset.NumDocs];
_groupIdToTopLabel = new short[Dataset.NumDocs];
FillSigmoidTable(_sigmoidParam);
#if OLD_DATALOAD
SetupSecondaryGains(cmd);
#endif
SetupBaselineRisk(args);
_parallelTraining = parallelTraining;
}
#if OLD_DATALOAD
private void SetupSecondaryGains(Arguments args)
{
_secondaryGains = null;
_secondaryMetricShare = args.secondaryMetricShare;
_secondaryIsolabelExclusive = args.secondaryIsolabelExclusive;
if (_secondaryMetricShare != 0.0)
{
_secondaryGains = Dataset.Skeleton.GetData<double>("SecondaryGains");
if (_secondaryGains == null)
{
_secondaryMetricShare = 0.0;
return;
}
_secondaryInverseMaxDCGT = DCGCalculator.MaxDCG(_secondaryGains, Dataset.Boundaries,
new int[] { args.lambdaMartMaxTruncation })[0].Select(d => 1.0 / d).ToArray();
}
}
#endif
private void SetupBaselineRisk(Arguments args)
{
double[] scores = Dataset.Skeleton.GetData<double>("BaselineScores");
if (scores == null)
return;
// Calculate the DCG with the discounts as they exist in the objective function (this
// can differ versus the actual DCG discount)
DcgCalculator calc = new DcgCalculator(Dataset.MaxDocsPerQuery, args.SortingAlgorithm);
_baselineDcg = calc.DcgFromScores(Dataset, scores, _discount);
IniFileParserInterface ffi = IniFileParserInterface.CreateFromFreeform(string.IsNullOrEmpty(args.BaselineAlphaRisk) ? "0" : args.BaselineAlphaRisk);
IniFileParserInterface.FeatureEvaluator ffe = ffi.GetFeatureEvaluators()[0];
IniFileParserInterface.FeatureMap ffmap = ffi.GetFeatureMap();
string[] ffnames = Enumerable.Range(0, ffmap.RawFeatureCount)
.Select(x => ffmap.GetRawFeatureName(x)).ToArray();
string[] badffnames = ffnames.Where(x => x != "I" && x != "T").ToArray();
if (badffnames.Length > 0)
{
// The freeform should contain only I and T, that is, the iteration and total iterations.
throw Contracts.Except(
"alpha freeform must use only I (iterations) and T (total iterations), contains {0} unrecognized names {1}",
badffnames.Length, string.Join(", ", badffnames));
}
uint[] vals = new uint[ffmap.RawFeatureCount];
int iInd = Array.IndexOf(ffnames, "I");
int tInd = Array.IndexOf(ffnames, "T");
int totalTrees = args.NumTrees;
if (tInd >= 0)
vals[tInd] = (uint)totalTrees;
_baselineAlpha = Enumerable.Range(0, totalTrees).Select(i =>
{
if (iInd >= 0)
vals[iInd] = (uint)i;
return ffe.Evaluate(vals);
}).ToArray();
}
private void FillSigmoidTable(double sigmoidParam)
{
// minScore is such that 2*sigmoidParam*score is < expAsymptote if score < minScore
_minScore = _expAsymptote / sigmoidParam / 2;
_maxScore = -_minScore;
_sigmoidTable = new double[_sigmoidBins];
for (int i = 0; i < _sigmoidBins; i++)
{
double score = (_maxScore - _minScore) / _sigmoidBins * i + _minScore;
if (score > 0.0)
_sigmoidTable[i] = 2.0 - 2.0 / (1.0 + Math.Exp(-2.0 * sigmoidParam * score));
else
_sigmoidTable[i] = 2.0 / (1.0 + Math.Exp(2.0 * sigmoidParam * score));
}
_scoreToSigmoidTableFactor = _sigmoidBins / (_maxScore - _minScore);
_minSigmoid = _sigmoidTable[0];
_maxSigmoid = _sigmoidTable.Last();
}
private void IgnoreNonBestDuplicates(short[] labels, double[] scores, int[] order, UInt32[] dupeIds, int begin, int numDocuments)
{
if (dupeIds == null || dupeIds.Length == 0)
{
return;
}
// Reset top label for all groups
for (int i = begin; i < begin + numDocuments; ++i)
{
_groupIdToTopLabel[i] = -1;
}
for (int i = 0; i < numDocuments; ++i)
{
Contracts.Check(0 <= order[i] && order[i] < numDocuments, "the index to document exceeds range");
int index = begin + order[i];
UInt32 group = dupeIds[index];
if (group == (UInt32)DupeIdInfo.Code404 || group == (UInt32)DupeIdInfo.FormatNotSupported ||
group == (UInt32)DupeIdInfo.Unique || group == (UInt32)DupeIdInfo.NoInformation)
{
continue;
}
// group starts from 2 (since 0 is unknown and 1 is unique)
Contracts.Check(2 <= group && group < numDocuments + 2, "dupeId group exceeds range");
UInt32 groupIndex = (UInt32)begin + group - 2;
if (_groupIdToTopLabel[groupIndex] != -1)
{
// this is the second+ occurance of a result
// of the same duplicate group, so:
// - disconsider when applying the cost function
//
// Only do this if the rating of this dupe is worse or equal,
// otherwise we want this dupe to be pushed to the top
// so we keep it
if (labels[index] <= _groupIdToTopLabel[groupIndex])
{
labels[index] = 0;
scores[index] = double.MinValue;
}
}
else
{
_groupIdToTopLabel[groupIndex] = labels[index];
}
}
}
public override double[] GetGradient(IChannel ch, double[] scores)
{
// Set the risk and alpha accumulators appropriately.
_countRisk = _currentRisk = _idealNextRisk = 0.0;
_baselineAlphaCurrent = _baselineAlpha == null ? 0.0 : _baselineAlpha[_iteration];
double[] grads = base.GetGradient(ch, scores);
if (_baselineDcg != null)
{
ch.Info(
"Risk alpha {0:0.000}, total {1:0.000}, avg {2:0.000}, count {3}, next ideal {4:0.000}",
_baselineAlphaCurrent, _currentRisk, _currentRisk / Math.Max(1.0, _countRisk),
_countRisk, _idealNextRisk);
}
_iteration++;
return grads;
}
protected override void GetGradientInOneQuery(int query, int threadIndex)
{
int begin = Dataset.Boundaries[query];
int numDocuments = Dataset.Boundaries[query + 1] - Dataset.Boundaries[query];
Array.Clear(Gradient, begin, numDocuments);
Array.Clear(Weights, begin, numDocuments);
double inverseMaxDcg = _inverseMaxDcgt[query];
double secondaryInverseMaxDcg = _secondaryMetricShare == 0 ? 0.0 : _secondaryInverseMaxDcgt[query];
int[] permutation = _permutationBuffers[threadIndex];
short[] labels = _labels;
double[] scoresToUse = Scores;
if (_useShiftedNdcg)
{
// Copy the labels for this query
Array.Copy(_labels, begin, _labelsCopy, begin, numDocuments);
labels = _labelsCopy;
}
if (_costFunctionParam == 'c' || _useShiftedNdcg)
{
// Copy the scores for this query
Array.Copy(Scores, begin, _scoresCopy, begin, numDocuments);
scoresToUse = _scoresCopy;
}
// Keep track of top 3 labels for later use
//GetTopQueryLabels(query, permutation, false);
double lambdaSum = 0;
unsafe
{
fixed (int* pPermutation = permutation)
fixed (short* pLabels = labels)
fixed (double* pScores = scoresToUse)
fixed (double* pLambdas = Gradient)
fixed (double* pWeights = Weights)
fixed (double* pDiscount = _discount)
fixed (double* pGain = _gain)
fixed (double* pGainLabels = _gainLabels)
fixed (double* pSigmoidTable = _sigmoidTable)
fixed (double* pSecondaryGains = _secondaryGains)
fixed (int* pOneTwoThree = _oneTwoThree)
{
// calculates the permutation that orders "scores" in descending order, without modifying "scores"
Array.Copy(_oneTwoThree, permutation, numDocuments);
#if USE_FASTTREENATIVE
PermutationSort(permutation, scoresToUse, labels, numDocuments, begin);
// Get how far about baseline our current
double baselineDcgGap = 0.0;
if (_baselineDcg != null)
{
baselineDcgGap = _baselineDcg[query];
for (int d = 0; d < numDocuments; ++d)
{
baselineDcgGap -= _gainLabels[pPermutation[d] + begin] * _discount[d];
}
if (baselineDcgGap > 1e-7)
{
Utils.InterlockedAdd(ref _currentRisk, baselineDcgGap);
Utils.InterlockedAdd(ref _countRisk, 1.0);
}
}
//baselineDCGGap = ((new Random(query)).NextDouble() * 2 - 1)/inverseMaxDCG; // THIS IS EVIL CODE REMOVE LATER
// Keep track of top 3 labels for later use
GetTopQueryLabels(query, permutation, true);
if (_useShiftedNdcg)
{
// Set non-best (rank-wise) duplicates to be ignored. Set Score to MinValue, Label to 0
IgnoreNonBestDuplicates(labels, scoresToUse, permutation, Dataset.DupeIds, begin, numDocuments);
}
int numActualResults = numDocuments;
// If the const function is ContinuousWeightedRanknet, update output scores
if (_costFunctionParam == 'c')
{
for (int i = begin; i < begin + numDocuments; ++i)
{
if (pScores[i] == double.MinValue)
{
numActualResults--;
}
else
{
pScores[i] = pScores[i] * (1.0 - pLabels[i] * 1.0 / (20.0 * Dataset.DatasetSkeleton.LabelGainMap.Length));
}
}
}
// Continous cost function and shifted NDCG require a re-sort and recomputation of maxDCG
// (Change of scores in the former and scores and labels in the latter)
if (!_trainDcg && (_costFunctionParam == 'c' || _useShiftedNdcg))
{
PermutationSort(permutation, scoresToUse, labels, numDocuments, begin);
inverseMaxDcg = 1.0 / DcgCalculator.MaxDcgQuery(labels, begin, numDocuments, numDocuments, _labelCounts[query]);
}
// A constant related to secondary labels, which does not exist in the current codebase.
const bool secondaryIsolabelExclusive = false;
GetDerivatives(numDocuments, begin, pPermutation, pLabels,
pScores, pLambdas, pWeights, pDiscount,
inverseMaxDcg, pGainLabels,
_secondaryMetricShare, secondaryIsolabelExclusive, secondaryInverseMaxDcg, pSecondaryGains,
pSigmoidTable, _minScore, _maxScore, _sigmoidTable.Length, _scoreToSigmoidTableFactor,
_costFunctionParam, _distanceWeight2, numActualResults, &lambdaSum, double.MinValue,
_baselineAlphaCurrent, baselineDcgGap);
// For computing the "ideal" case of the DCGs.
if (_baselineDcg != null)
{
if (scoresToUse == Scores)
Array.Copy(Scores, begin, _scoresCopy, begin, numDocuments);
for (int i = begin; i < begin + numDocuments; ++i)
{
_scoresCopy[i] += Gradient[i] / Weights[i];
}
Array.Copy(_oneTwoThree, permutation, numDocuments);
PermutationSort(permutation, _scoresCopy, labels, numDocuments, begin);
double idealNextRisk = _baselineDcg[query];
for (int d = 0; d < numDocuments; ++d)
{
idealNextRisk -= _gainLabels[pPermutation[d] + begin] * _discount[d];
}
if (idealNextRisk > 1e-7)
{
Utils.InterlockedAdd(ref _idealNextRisk, idealNextRisk);
}
}
#else
if (_useShiftedNdcg || _costFunctionParam == 'c' || _distanceWeight2 || _normalizeQueryLambdas)
{
throw new Exception("Shifted NDCG / ContinuousWeightedRanknet / distanceWeight2 / normalized lambdas are only supported by unmanaged code");
}
var comparer = _comparers[threadIndex];
comparer.Scores = scoresToUse;
comparer.Labels = labels;
comparer.ScoresOffset = begin;
comparer.LabelsOffset = begin;
Array.Sort(permutation, 0, numDocuments, comparer);
// go over all pairs
double scoreHighMinusLow;
double lambdaP;
double weightP;
double deltaNdcgP;
for (int i = 0; i < numDocuments; ++i)
{
int high = begin + pPermutation[i];
if (pLabels[high] == 0)
continue;
double deltaLambdasHigh = 0;
double deltaWeightsHigh = 0;
for (int j = 0; j < numDocuments; ++j)
{
// only consider pairs with different labels, where "high" has a higher label than "low"
if (i == j)
continue;
int low = begin + pPermutation[j];
if (pLabels[high] <= pLabels[low])
continue;
// calculate the lambdaP for this pair
scoreHighMinusLow = pScores[high] - pScores[low];
if (scoreHighMinusLow <= _minScore)
lambdaP = _minSigmoid;
else if (scoreHighMinusLow >= _maxScore)
lambdaP = _maxSigmoid;
else
lambdaP = _sigmoidTable[(int)((scoreHighMinusLow - _minScore) * _scoreToSigmoidTableFactor)];
weightP = lambdaP * (2.0 - lambdaP);
// calculate the deltaNDCGP for this pair
deltaNdcgP =
(pGain[pLabels[high]] - pGain[pLabels[low]]) *
Math.Abs((pDiscount[i] - pDiscount[j])) *
inverseMaxDcg;
// update lambdas and weights
deltaLambdasHigh += lambdaP * deltaNdcgP;
pLambdas[low] -= lambdaP * deltaNdcgP;
deltaWeightsHigh += weightP * deltaNdcgP;
pWeights[low] += weightP * deltaNdcgP;
}
pLambdas[high] += deltaLambdasHigh;
pWeights[high] += deltaWeightsHigh;
}
#endif
if (_normalizeQueryLambdas)
{
if (lambdaSum > 0)
{
double normFactor = (10 * Math.Log(1 + lambdaSum)) / lambdaSum;
for (int i = begin; i < begin + numDocuments; ++i)
{
pLambdas[i] = pLambdas[i] * normFactor;
pWeights[i] = pWeights[i] * normFactor;
}
}
}
}
}
}
public void AdjustTreeOutputs(IChannel ch, RegressionTree tree, DocumentPartitioning partitioning,
ScoreTracker trainingScores)
{
const double epsilon = 1.4e-45;
double[] means = null;
if (!BestStepRankingRegressionTrees)
means = _parallelTraining.GlobalMean(Dataset, tree, partitioning, Weights, _filterZeroLambdas);
for (int l = 0; l < tree.NumLeaves; ++l)
{
double output = tree.LeafValue(l);
if (!BestStepRankingRegressionTrees)
output = (output + epsilon) / (2.0 * means[l] + epsilon);
if (output > MaxTreeOutput)
output = MaxTreeOutput;
else if (output < -MaxTreeOutput)
output = -MaxTreeOutput;
tree.SetLeafValue(l, output);
}
}
private void FillDiscounts(string positionDiscountFreeform)
{
if (positionDiscountFreeform == null)
{
for (int d = 0; d < Dataset.MaxDocsPerQuery; ++d)
_discount[d] = 1.0 / Math.Log(2.0 + d);
}
else
{
IniFileParserInterface inip = IniFileParserInterface.CreateFromFreeform(positionDiscountFreeform);
if (inip.GetFeatureMap().RawFeatureCount != 1)
{
throw Contracts.Except(
"The position discount freeform requires exactly 1 variable, {0} encountered",
inip.GetFeatureMap().RawFeatureCount);
}
var freeformEval = inip.GetFeatureEvaluators()[0];
uint[] p = new uint[1];
for (int d = 0; d < Dataset.MaxDocsPerQuery; ++d)
{
p[0] = (uint)d;
_discount[d] = freeformEval.Evaluate(p);
}
}
}
private void FillGainLabels()
{
_gainLabels = new double[Dataset.NumDocs];
for (int i = 0; i < Dataset.NumDocs; i++)
{
_gainLabels[i] = _gain[_labels[i]];
}
}
// Keep track of top 3 labels for later use.
private void GetTopQueryLabels(int query, int[] permutation, bool bAlreadySorted)
{
int numDocuments = Dataset.Boundaries[query + 1] - Dataset.Boundaries[query];
int begin = Dataset.Boundaries[query];
if (!bAlreadySorted)
{
// calculates the permutation that orders "scores" in descending order, without modifying "scores"
Array.Copy(_oneTwoThree, permutation, numDocuments);
PermutationSort(permutation, Scores, _labels, numDocuments, begin);
}
for (int i = 0; i < 3 && i < numDocuments; ++i)
TrainQueriesTopLabels[query][i] = _labels[begin + permutation[i]];
}
private static void PermutationSort(int[] permutation, double[] scores, short[] labels, int numDocs, int shift)
{
Contracts.AssertValue(permutation);
Contracts.AssertValue(scores);
Contracts.AssertValue(labels);
Contracts.Assert(numDocs > 0);
Contracts.Assert(shift >= 0);
Contracts.Assert(scores.Length - numDocs >= shift);
Contracts.Assert(labels.Length - numDocs >= shift);
Array.Sort(permutation, 0, numDocs,
Comparer<int>.Create((x, y) =>
{
if (scores[shift + x] > scores[shift + y])
return -1;
if (scores[shift + x] < scores[shift + y])
return 1;
if (labels[shift + x] < labels[shift + y])
return -1;
if (labels[shift + x] > labels[shift + y])
return 1;
return x - y;
}));
}
[DllImport("FastTreeNative", EntryPoint = "C_GetDerivatives", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern unsafe void GetDerivatives(
int numDocuments, int begin, int* pPermutation, short* pLabels,
double* pScores, double* pLambdas, double* pWeights, double* pDiscount,
double inverseMaxDcg, double* pGainLabels,
double secondaryMetricShare, [MarshalAs(UnmanagedType.U1)] bool secondaryExclusive, double secondaryInverseMaxDcg, double* pSecondaryGains,
double* lambdaTable, double minScore, double maxScore,
int lambdaTableLength, double scoreToLambdaTableFactor,
char costFunctionParam, [MarshalAs(UnmanagedType.U1)] bool distanceWeight2, int numActualDocuments,
double* pLambdaSum, double doubleMinValue, double alphaRisk, double baselineVersusCurrentDcg);
}
}
public sealed class FastTreeRankingPredictor : FastTreePredictionWrapper
{
public const string LoaderSignature = "FastTreeRankerExec";
public const string RegistrationName = "FastTreeRankingPredictor";
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "FTREE RA",
// verWrittenCur: 0x00010001, // Initial
// verWrittenCur: 0x00010002, // _numFeatures serialized
// verWrittenCur: 0x00010003, // Ini content out of predictor
// verWrittenCur: 0x00010004, // Add _defaultValueForMissing
verWrittenCur: 0x00010005, // Categorical splits.
verReadableCur: 0x00010004,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature);
}
protected override uint VerNumFeaturesSerialized => 0x00010002;
protected override uint VerDefaultValueSerialized => 0x00010004;
protected override uint VerCategoricalSplitSerialized => 0x00010005;
internal FastTreeRankingPredictor(IHostEnvironment env, Ensemble trainedEnsemble, int featureCount, string innerArgs)
: base(env, RegistrationName, trainedEnsemble, featureCount, innerArgs)
{
}
private FastTreeRankingPredictor(IHostEnvironment env, ModelLoadContext ctx)
: base(env, RegistrationName, ctx, GetVersionInfo())
{
}
protected override void SaveCore(ModelSaveContext ctx)
{
base.SaveCore(ctx);
ctx.SetVersionInfo(GetVersionInfo());
}
public static FastTreeRankingPredictor Create(IHostEnvironment env, ModelLoadContext ctx)
{
return new FastTreeRankingPredictor(env, ctx);
}
public override PredictionKind PredictionKind => PredictionKind.Ranking;
}
public static partial class FastTree
{
[TlcModule.EntryPoint(Name = "Trainers.FastTreeRanker",
Desc = FastTreeRankingTrainer.Summary,
UserName = FastTreeRankingTrainer.UserNameValue,
ShortName = FastTreeRankingTrainer.ShortName,
XmlInclude = new[] { @"<include file='../Microsoft.ML.FastTree/doc.xml' path='doc/members/member[@name=""FastTree""]/*' />",
@"<include file='../Microsoft.ML.FastTree/doc.xml' path='doc/members/example[@name=""FastTreeRanker""]/*' />"})]
public static CommonOutputs.RankingOutput TrainRanking(IHostEnvironment env, FastTreeRankingTrainer.Arguments input)
{
Contracts.CheckValue(env, nameof(env));
var host = env.Register("TrainFastTree");
host.CheckValue(input, nameof(input));
EntryPointUtils.CheckInputArgs(host, input);
return LearnerEntryPointsUtils.Train<FastTreeRankingTrainer.Arguments, CommonOutputs.RankingOutput>(host, input,
() => new FastTreeRankingTrainer(host, input),
() => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.LabelColumn),
() => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.WeightColumn),
() => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.GroupIdColumn));
}
}
}
| 45.233969 | 216 | 0.536973 | [
"MIT"
] | NileshGule/machinelearning | src/Microsoft.ML.FastTree/FastTreeRanking.cs | 52,200 | 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 Sage.CA.SBS.ERP.Sage300.GL.Resources.Forms {
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", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class OptionsResx {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal OptionsResx() {
}
/// <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("Sage.CA.SBS.ERP.Sage300.GL.Resources.Forms.OptionsResx", typeof(OptionsResx).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 string similar to Account.
/// </summary>
public static string AccountTab {
get {
return ResourceManager.GetString("AccountTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Allow Posting to Previous Years.
/// </summary>
public static string AllowPostingPrevYr {
get {
return ResourceManager.GetString("AllowPostingPrevYr", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Allow Provisional Posting.
/// </summary>
public static string AllowProvPosting {
get {
return ResourceManager.GetString("AllowProvPosting", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Budget Set 1.
/// </summary>
public static string BudgetSet1 {
get {
return ResourceManager.GetString("BudgetSet1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Budget Set 2.
/// </summary>
public static string BudgetSet2 {
get {
return ResourceManager.GetString("BudgetSet2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Budget Set 3.
/// </summary>
public static string BudgetSet3 {
get {
return ResourceManager.GetString("BudgetSet3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Budget Set 4.
/// </summary>
public static string BudgetSet4 {
get {
return ResourceManager.GetString("BudgetSet4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Budget Set 5.
/// </summary>
public static string BudgetSet5 {
get {
return ResourceManager.GetString("BudgetSet5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Company.
/// </summary>
public static string Company {
get {
return ResourceManager.GetString("Company", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fax.
/// </summary>
public static string CompanyFaxNumber {
get {
return ResourceManager.GetString("CompanyFaxNumber", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Phone.
/// </summary>
public static string CompanyPhoneNumber {
get {
return ResourceManager.GetString("CompanyPhoneNumber", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Contact Name.
/// </summary>
public static string ContactName {
get {
return ResourceManager.GetString("ContactName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current Fiscal Year.
/// </summary>
public static string CurrentYear {
get {
return ResourceManager.GetString("CurrentYear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decimal Places.
/// </summary>
public static string DecimalPlaces {
get {
return ResourceManager.GetString("DecimalPlaces", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Access.
/// </summary>
public static string DefaultAccess {
get {
return ResourceManager.GetString("DefaultAccess", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Closing Account.
/// </summary>
public static string DefaultClosingAcct {
get {
return ResourceManager.GetString("DefaultClosingAcct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Rate Type.
/// </summary>
public static string DefaultRateType {
get {
return ResourceManager.GetString("DefaultRateType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Source Code.
/// </summary>
public static string DefaultSourceCode {
get {
return ResourceManager.GetString("DefaultSourceCode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Structure Code.
/// </summary>
public static string DefaultStructureCode {
get {
return ResourceManager.GetString("DefaultStructureCode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default value cannot be blank for optional field {0}..
/// </summary>
public static string DefaultValueValidationForBlank {
get {
return ResourceManager.GetString("DefaultValueValidationForBlank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Imported Entries.
/// </summary>
public static string EditImportEnt {
get {
return ResourceManager.GetString("EditImportEnt", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to G/L Options.
/// </summary>
public static string Entity {
get {
return ResourceManager.GetString("Entity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Force Listing of Batches.
/// </summary>
public static string ForceBatchListing {
get {
return ResourceManager.GetString("ForceBatchListing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Functional Currency.
/// </summary>
public static string FunctionalCurrency {
get {
return ResourceManager.GetString("FunctionalCurrency", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to G/L Option Key.
/// </summary>
public static string GLOptionKey {
get {
return ResourceManager.GetString("GLOptionKey", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Keep.
/// </summary>
public static string Keep {
get {
return ResourceManager.GetString("Keep", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Last Batch.
/// </summary>
public static string LastBatch {
get {
return ResourceManager.GetString("LastBatch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Length.
/// </summary>
public static string Length {
get {
return ResourceManager.GetString("Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lock Budget Sets.
/// </summary>
public static string LockBudgetSets {
get {
return ResourceManager.GetString("LockBudgetSets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Account Segment.
/// </summary>
public static string MainAcctSegmentId {
get {
return ResourceManager.GetString("MainAcctSegmentId", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multicurrency.
/// </summary>
public static string MulticurrencyActivatedSwitch {
get {
return ResourceManager.GetString("MulticurrencyActivatedSwitch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Next Posting Sequence.
/// </summary>
public static string NextPostingSeq {
get {
return ResourceManager.GetString("NextPostingSeq", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Next Provisional Posting Sequence.
/// </summary>
public static string NextProvPostSeq {
get {
return ResourceManager.GetString("NextProvPostSeq", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of years to keep transaction detail cannot exceed the number of years to keep fiscal sets..
/// </summary>
public static string NumberOfYearsValidation {
get {
return ResourceManager.GetString("NumberOfYearsValidation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Oldest Year of Fiscal Sets.
/// </summary>
public static string OldestYearFS {
get {
return ResourceManager.GetString("OldestYearFS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Oldest Year of Transaction Detail.
/// </summary>
public static string OldestYearTrans {
get {
return ResourceManager.GetString("OldestYearTrans", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Options.
/// </summary>
public static string Options {
get {
return ResourceManager.GetString("Options", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Posting Statistics.
/// </summary>
public static string PostingStats {
get {
return ResourceManager.GetString("PostingStats", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Posting.
/// </summary>
public static string PostingTab {
get {
return ResourceManager.GetString("PostingTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maintain Quantities.
/// </summary>
public static string QuantityHistoryAllowed {
get {
return ResourceManager.GetString("QuantityHistoryAllowed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reserved Account History Clearing Account.
/// </summary>
public static string ReservedAcctHistoryClearingAcct {
get {
return ResourceManager.GetString("ReservedAcctHistoryClearingAcct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Delimiter.
/// </summary>
public static string SegmentDelim {
get {
return ResourceManager.GetString("SegmentDelim", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Name.
/// </summary>
public static string SegmentDescription {
get {
return ResourceManager.GetString("SegmentDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Length.
/// </summary>
public static string SegmentLength {
get {
return ResourceManager.GetString("SegmentLength", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number.
/// </summary>
public static string SegmentNumber {
get {
return ResourceManager.GetString("SegmentNumber", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segments must be defined in consecutive order by segment number..
/// </summary>
public static string SegmentOrderMessage {
get {
return ResourceManager.GetString("SegmentOrderMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segments.
/// </summary>
public static string SegmentTab {
get {
return ResourceManager.GetString("SegmentTab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Closing Account {0} is not a retained earnings account. You must select a retained earnings account..
/// </summary>
public static string SelectRetainedEarningsAcct {
get {
return ResourceManager.GetString("SelectRetainedEarningsAcct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Structure Code.
/// </summary>
public static string StructureCode {
get {
return ResourceManager.GetString("StructureCode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition Rounding Account.
/// </summary>
public static string TransitionRoundingAccount {
get {
return ResourceManager.GetString("TransitionRoundingAccount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use Account Groups.
/// </summary>
public static string UseAcctGroup {
get {
return ResourceManager.GetString("UseAcctGroup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use in Closing.
/// </summary>
public static string UseInClosing {
get {
return ResourceManager.GetString("UseInClosing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use G/L Security.
/// </summary>
public static string UseSecurity {
get {
return ResourceManager.GetString("UseSecurity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decimals allowed for Maintain Quantities cannot be changed to a smaller value..
/// </summary>
public static string ValidationDecimalMessage {
get {
return ResourceManager.GetString("ValidationDecimalMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Years of Fiscal Sets.
/// </summary>
public static string YearsOfFiscalSets {
get {
return ResourceManager.GetString("YearsOfFiscalSets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Years of Transaction Detail.
/// </summary>
public static string YearsOfTransDetail {
get {
return ResourceManager.GetString("YearsOfTransDetail", resourceCulture);
}
}
}
}
| 35.128521 | 201 | 0.539167 | [
"MIT"
] | PeterSorokac/Sage300-SDK | resources/Sage300Resources/Sage.CA.SBS.ERP.Sage300.GL.Resources/Forms/OptionsResx.Designer.cs | 19,955 | C# |
namespace ConfArch.Data.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public string FavoriteColor { get; set; }
public string Role { get; set; }
public string GoogleId { get; set; }
}
}
| 25.230769 | 49 | 0.567073 | [
"MIT"
] | ToanNN/Asp.NetCoreSecurity | ConfArch.Data/Models/User.cs | 330 | C# |
namespace _01.GenericBoxOfString
{
using System;
public class StartUp
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine();
var box = new Box<string>(input);
Console.WriteLine(box);
}
}
}
}
| 18.545455 | 50 | 0.446078 | [
"MIT"
] | anedyalkov/CSharp-OOP-Advanced | 04.Generics-Exercises/Generics-Exercises/01.GenericBoxOfString/StartUp.cs | 410 | C# |
namespace MyOnlineShop.Web
{
using Microsoft.AspNetCore.Http;
using MyOnlineShop.Application.Common.Contracts;
using System;
using System.Security.Claims;
using static Constants;
public class CurrentUserService : ICurrentUser
{
private readonly ClaimsPrincipal user;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
this.user = httpContextAccessor.HttpContext?.User;
if (user == null)
{
throw new InvalidOperationException("This request does not have an authenticated user.");
}
this.UserId = this.user.FindFirstValue(ClaimTypes.NameIdentifier);
this.Username = this.user.FindFirstValue(ClaimTypes.Email);
this.IsAdministrator = this.user.IsInRole(Roles.AdministratorRoleName);
}
public string UserId { get; }
public string Username { get; }
public bool IsAdministrator { get; }
}
} | 30.272727 | 105 | 0.653654 | [
"MIT"
] | DimchoLakov/MyOnlineShop-Domain-Driven-Design | MyOnlineShop/MyOnlineShop.Web/CurrentUserService.cs | 1,001 | C# |
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Rotativa.AspNetCore.Tests
{
[Trait("Rotativa.AspNetCore", "")]
public class RotativaTests: IDisposable
{
private IWebDriver selenium;
private StringBuilder verificationErrors;
public RotativaTests()
{
TestSetUp();
}
public void TestSetUp()
{
selenium = new ChromeDriver();
//selenium = new InternetExplorerDriver();
selenium.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 10);
verificationErrors = new StringBuilder();
var rotativaDemoUrl = "http://localhost:59941";//ConfigurationManager.AppSettings["RotativaDemoUrl"];
selenium.Navigate().GoToUrl(rotativaDemoUrl);
}
public void Dispose()
{
if (selenium != null) selenium.Quit();
}
[Fact]
public void Is_the_site_reachable()
{
Assert.Equal("Home Page - Rotativa.AspNetCore.Demo", selenium.Title);
}
[Fact]
public void Can_print_the_test_pdf()
{
var testLink = selenium.FindElement(By.LinkText("About"));
var pdfHref = testLink.GetAttribute("href");
using (var wc = new WebClient())
{
var pdfResult = wc.DownloadData(new Uri(pdfHref));
var pdfTester = new PdfTester();
pdfTester.LoadPdf(pdfResult);
Assert.True(pdfTester.PdfIsValid);
Assert.True(pdfTester.PdfContains("About"));
}
}
//[Fact]
//public void Can_print_the_test_image()
//{
// var testLink = selenium.FindElement(By.LinkText("Test Image"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_the_test_image_png()
//{
// var testLink = selenium.FindElement(By.LinkText("Test Image Png"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Png);
// }
//}
//[Fact]
//public void Can_print_the_authorized_pdf()
//{
// //// Log Off if required...
// var logoffLink = selenium.FindElements(By.LinkText("Log Off"));
// if (logoffLink.Any())
// logoffLink.First().Click();
// var testLink = selenium.FindElement(By.LinkText("Logged In Test"));
// var pdfHref = testLink.GetAttribute("href");
// var loginLink = selenium.FindElement(By.ClassName("logon"));
// loginLink.Click();
// var username = selenium.FindElement(By.Id("UserName"));
// username.SendKeys("admin");
// var password = selenium.FindElement(By.Id("Password"));
// password.Clear();
// password.SendKeys("admin");
// password.Submit();
// var manage = selenium.Manage();
// var cookies = manage.Cookies.AllCookies;
// using (var wc = new WebClient())
// {
// foreach (var cookie in cookies)
// {
// var cookieText = cookie.Name + "=" + cookie.Value;
// wc.Headers.Add(HttpRequestHeader.Cookie, cookieText);
// }
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains("My MVC Application").Should().Be.True();
// pdfTester.PdfContains("admin").Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_the_authorized_image()
//{
// //// Log Off if required...
// var logoffLink = selenium.FindElements(By.LinkText("Log Off"));
// if (logoffLink.Any())
// logoffLink.First().Click();
// var testLink = selenium.FindElement(By.LinkText("Logged In Test Image"));
// var pdfHref = testLink.GetAttribute("href");
// testLink.Click();
// var username = selenium.FindElement(By.Id("UserName"));
// username.SendKeys("admin");
// var password = selenium.FindElement(By.Id("Password"));
// password.Clear();
// password.SendKeys("admin");
// password.Submit();
// var manage = selenium.Manage();
// var cookies = manage.Cookies.AllCookies;
// using (var wc = new WebClient())
// {
// foreach (var cookie in cookies)
// {
// var cookieText = cookie.Name + "=" + cookie.Value;
// wc.Headers.Add(HttpRequestHeader.Cookie, cookieText);
// }
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_the_pdf_from_a_view()
//{
// var testLink = selenium.FindElement(By.LinkText("Test View"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains("My MVC Application").Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_the_image_from_a_view()
//{
// var testLink = selenium.FindElement(By.LinkText("Test View Image"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_the_pdf_from_a_view_with_non_ascii_chars()
//{
// var testLink = selenium.FindElement(By.LinkText("Test View"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains("àéù").Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_the_image_from_a_view_with_non_ascii_chars()
//{
// var testLink = selenium.FindElement(By.LinkText("Test View Image"));
// var pdfHref = testLink.GetAttribute("href");
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_the_pdf_from_a_view_with_a_model()
//{
// var testLink = selenium.FindElement(By.LinkText("Test ViewAsPdf with a model"));
// var pdfHref = testLink.GetAttribute("href");
// var title = "This is a test";
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains(title).Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_the_image_from_a_view_with_a_model()
//{
// var testLink = selenium.FindElement(By.LinkText("Test ViewAsImage with a model"));
// var pdfHref = testLink.GetAttribute("href");
// var title = "This is a test";
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_the_pdf_from_a_partial_view_with_a_model()
//{
// var testLink = selenium.FindElement(By.LinkText("Test PartialViewAsPdf with a model"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "This is a test with a partial view";
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains(content).Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_the_image_from_a_partial_view_with_a_model()
//{
// var testLink = selenium.FindElement(By.LinkText("Test PartialViewAsImage with a model"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "This is a test with a partial view";
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_pdf_from_page_with_content_from_ajax_request()
//{
// var testLink = selenium.FindElement(By.LinkText("Ajax Test"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "Hi there, this is content from a Ajax call.";
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains(content).Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_image_from_page_with_content_from_ajax_request()
//{
// var testLink = selenium.FindElement(By.LinkText("Ajax Image Test"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "Hi there, this is content from a Ajax call.";
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
//[Fact]
//public void Can_print_pdf_from_page_with_external_css_file()
//{
// var testLink = selenium.FindElement(By.LinkText("External CSS Test"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "Hi guys, this content shows up thanks to css file.";
// using (var wc = new WebClient())
// {
// var pdfResult = wc.DownloadData(new Uri(pdfHref));
// var pdfTester = new PdfTester();
// pdfTester.LoadPdf(pdfResult);
// pdfTester.PdfIsValid.Should().Be.True();
// pdfTester.PdfContains(content).Should().Be.True();
// }
//}
//[Fact]
//public void Can_print_image_from_page_with_external_css_file()
//{
// var testLink = selenium.FindElement(By.LinkText("External CSS Test Image"));
// var pdfHref = testLink.GetAttribute("href");
// var content = "Hi guys, this content shows up thanks to css file.";
// using (var wc = new WebClient())
// {
// var imageResult = wc.DownloadData(new Uri(pdfHref));
// var image = Image.FromStream(new MemoryStream(imageResult));
// image.Should().Not.Be.Null();
// image.RawFormat.Should().Be.EqualTo(ImageFormat.Jpeg);
// }
//}
}
}
| 39.921127 | 113 | 0.530342 | [
"MIT"
] | SRJPN/Rotativa.AspNetCore | Rotativa.AspNetCore.Tests/RotativaTests.cs | 14,177 | 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.Devices
{
/// <summary>
/// The X509 Certificate.
/// API Version: 2020-03-01.
/// </summary>
[AzureNativeResourceType("azure-native:devices:DpsCertificate")]
public partial class DpsCertificate : Pulumi.CustomResource
{
/// <summary>
/// The entity tag.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// The name of the certificate.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// properties of a certificate
/// </summary>
[Output("properties")]
public Output<Outputs.CertificatePropertiesResponse> Properties { get; private set; } = null!;
/// <summary>
/// The resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a DpsCertificate resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public DpsCertificate(string name, DpsCertificateArgs args, CustomResourceOptions? options = null)
: base("azure-native:devices:DpsCertificate", name, args ?? new DpsCertificateArgs(), MakeResourceOptions(options, ""))
{
}
private DpsCertificate(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:devices:DpsCertificate", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:devices:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20170821preview:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20170821preview:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20171115:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20171115:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20180122:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20180122:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20200101:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200101:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20200301:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200301:DpsCertificate"},
new Pulumi.Alias { Type = "azure-native:devices/v20200901preview:DpsCertificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200901preview:DpsCertificate"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing DpsCertificate resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static DpsCertificate Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new DpsCertificate(name, id, options);
}
}
public sealed class DpsCertificateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Base-64 representation of the X509 leaf certificate .cer file or just .pem file content.
/// </summary>
[Input("certificate")]
public Input<string>? Certificate { get; set; }
/// <summary>
/// The name of the certificate create or update.
/// </summary>
[Input("certificateName")]
public Input<string>? CertificateName { get; set; }
/// <summary>
/// True indicates that the certificate will be created in verified state and proof of possession will not be required.
/// </summary>
[Input("isVerified")]
public Input<bool>? IsVerified { get; set; }
/// <summary>
/// The name of the provisioning service.
/// </summary>
[Input("provisioningServiceName", required: true)]
public Input<string> ProvisioningServiceName { get; set; } = null!;
/// <summary>
/// Resource group identifier.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public DpsCertificateArgs()
{
}
}
}
| 43.151079 | 131 | 0.603368 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Devices/DpsCertificate.cs | 5,998 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Apigateway.V20180808.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyApiRequest : AbstractModel
{
/// <summary>
/// Unique service ID of API.
/// </summary>
[JsonProperty("ServiceId")]
public string ServiceId{ get; set; }
/// <summary>
/// API backend service type. Valid values: HTTP, MOCK, TSF, CLB, SCF, WEBSOCKET, TARGET (in beta test).
/// </summary>
[JsonProperty("ServiceType")]
public string ServiceType{ get; set; }
/// <summary>
/// Request frontend configuration.
/// </summary>
[JsonProperty("RequestConfig")]
public RequestConfig RequestConfig{ get; set; }
/// <summary>
/// Unique API ID.
/// </summary>
[JsonProperty("ApiId")]
public string ApiId{ get; set; }
/// <summary>
/// Custom API name.
/// </summary>
[JsonProperty("ApiName")]
public string ApiName{ get; set; }
/// <summary>
/// Custom API description.
/// </summary>
[JsonProperty("ApiDesc")]
public string ApiDesc{ get; set; }
/// <summary>
/// API type. Valid values: NORMAL, TSF. Default value: NORMAL.
/// </summary>
[JsonProperty("ApiType")]
public string ApiType{ get; set; }
/// <summary>
/// API authentication type. Valid values: SECRET, NONE, OAUTH, APP. Default value: NONE.
/// </summary>
[JsonProperty("AuthType")]
public string AuthType{ get; set; }
/// <summary>
/// Whether signature authentication is required. True: yes; False: no. This parameter is to be disused.
/// </summary>
[JsonProperty("AuthRequired")]
public bool? AuthRequired{ get; set; }
/// <summary>
/// API backend service timeout period in seconds.
/// </summary>
[JsonProperty("ServiceTimeout")]
public long? ServiceTimeout{ get; set; }
/// <summary>
/// API frontend request type, such as HTTP, HTTPS, or HTTP and HTTPS.
/// </summary>
[JsonProperty("Protocol")]
public string Protocol{ get; set; }
/// <summary>
/// Whether to enable CORS. True: yes; False: no.
/// </summary>
[JsonProperty("EnableCORS")]
public bool? EnableCORS{ get; set; }
/// <summary>
/// Constant parameter.
/// </summary>
[JsonProperty("ConstantParameters")]
public ConstantParameter[] ConstantParameters{ get; set; }
/// <summary>
/// Frontend request parameter.
/// </summary>
[JsonProperty("RequestParameters")]
public ReqParameter[] RequestParameters{ get; set; }
/// <summary>
/// This field is valid if `AuthType` is `OAUTH`. NORMAL: business API; OAUTH: authorization API.
/// </summary>
[JsonProperty("ApiBusinessType")]
public string ApiBusinessType{ get; set; }
/// <summary>
/// Returned message of API backend Mock, which is required if `ServiceType` is `Mock`.
/// </summary>
[JsonProperty("ServiceMockReturnMessage")]
public string ServiceMockReturnMessage{ get; set; }
/// <summary>
/// List of microservices bound to API.
/// </summary>
[JsonProperty("MicroServices")]
public MicroServiceReq[] MicroServices{ get; set; }
/// <summary>
/// Load balancing configuration of microservice.
/// </summary>
[JsonProperty("ServiceTsfLoadBalanceConf")]
public TsfLoadBalanceConfResp ServiceTsfLoadBalanceConf{ get; set; }
/// <summary>
/// Health check configuration of microservice.
/// </summary>
[JsonProperty("ServiceTsfHealthCheckConf")]
public HealthCheckConf ServiceTsfHealthCheckConf{ get; set; }
/// <summary>
/// `target` type load balancing configuration (in beta test).
/// </summary>
[JsonProperty("TargetServicesLoadBalanceConf")]
public long? TargetServicesLoadBalanceConf{ get; set; }
/// <summary>
/// `target` health check configuration (in beta test).
/// </summary>
[JsonProperty("TargetServicesHealthCheckConf")]
public HealthCheckConf TargetServicesHealthCheckConf{ get; set; }
/// <summary>
/// SCF function name, which takes effect if the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceScfFunctionName")]
public string ServiceScfFunctionName{ get; set; }
/// <summary>
/// SCF WebSocket registration function, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketRegisterFunctionName")]
public string ServiceWebsocketRegisterFunctionName{ get; set; }
/// <summary>
/// SCF WebSocket cleanup function, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketCleanupFunctionName")]
public string ServiceWebsocketCleanupFunctionName{ get; set; }
/// <summary>
/// SCF WebSocket transfer function, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketTransportFunctionName")]
public string ServiceWebsocketTransportFunctionName{ get; set; }
/// <summary>
/// SCF function namespace, which takes effect if the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceScfFunctionNamespace")]
public string ServiceScfFunctionNamespace{ get; set; }
/// <summary>
/// SCF function version, which takes effect if the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceScfFunctionQualifier")]
public string ServiceScfFunctionQualifier{ get; set; }
/// <summary>
/// SCF WebSocket registration function namespace, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketRegisterFunctionNamespace")]
public string ServiceWebsocketRegisterFunctionNamespace{ get; set; }
/// <summary>
/// SCF WebSocket transfer function version, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketRegisterFunctionQualifier")]
public string ServiceWebsocketRegisterFunctionQualifier{ get; set; }
/// <summary>
/// SCF WebSocket transfer function namespace, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketTransportFunctionNamespace")]
public string ServiceWebsocketTransportFunctionNamespace{ get; set; }
/// <summary>
/// SCF WebSocket transfer function version, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketTransportFunctionQualifier")]
public string ServiceWebsocketTransportFunctionQualifier{ get; set; }
/// <summary>
/// SCF WebSocket cleanup function namespace, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketCleanupFunctionNamespace")]
public string ServiceWebsocketCleanupFunctionNamespace{ get; set; }
/// <summary>
/// SCF WebSocket cleanup function version, which takes effect if the frontend type is `WEBSOCKET` and the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceWebsocketCleanupFunctionQualifier")]
public string ServiceWebsocketCleanupFunctionQualifier{ get; set; }
/// <summary>
/// Whether to enable response integration, which takes effect if the backend type is `SCF`.
/// </summary>
[JsonProperty("ServiceScfIsIntegratedResponse")]
public bool? ServiceScfIsIntegratedResponse{ get; set; }
/// <summary>
/// Billing after debugging starts (reserved field for marketplace).
/// </summary>
[JsonProperty("IsDebugAfterCharge")]
public bool? IsDebugAfterCharge{ get; set; }
/// <summary>
/// Tag.
/// </summary>
[JsonProperty("TagSpecifications")]
public Tag TagSpecifications{ get; set; }
/// <summary>
/// Whether to delete the error codes for custom response configuration. If the value is left empty or `False`, the error codes will not be deleted. If the value is `True`, all custom response configuration error codes of the API will be deleted.
/// </summary>
[JsonProperty("IsDeleteResponseErrorCodes")]
public bool? IsDeleteResponseErrorCodes{ get; set; }
/// <summary>
/// Return type.
/// </summary>
[JsonProperty("ResponseType")]
public string ResponseType{ get; set; }
/// <summary>
/// Sample response for successful custom response configuration.
/// </summary>
[JsonProperty("ResponseSuccessExample")]
public string ResponseSuccessExample{ get; set; }
/// <summary>
/// Sample response for failed custom response configuration.
/// </summary>
[JsonProperty("ResponseFailExample")]
public string ResponseFailExample{ get; set; }
/// <summary>
/// API backend service configuration.
/// </summary>
[JsonProperty("ServiceConfig")]
public ServiceConfig ServiceConfig{ get; set; }
/// <summary>
/// Unique ID of associated authorization API, which takes effect only if `AuthType` is `OAUTH` and `ApiBusinessType` is `NORMAL`. It is the unique ID of the OAuth 2.0 authorization API bound to the business API.
/// </summary>
[JsonProperty("AuthRelationApiId")]
public string AuthRelationApiId{ get; set; }
/// <summary>
/// API backend service parameter.
/// </summary>
[JsonProperty("ServiceParameters")]
public ServiceParameter[] ServiceParameters{ get; set; }
/// <summary>
/// OAuth configuration, which takes effect if `AuthType` is `OAUTH`.
/// </summary>
[JsonProperty("OauthConfig")]
public OauthConfig OauthConfig{ get; set; }
/// <summary>
/// Custom error code configuration.
/// </summary>
[JsonProperty("ResponseErrorCodes")]
public ResponseErrorCodeReq[] ResponseErrorCodes{ get; set; }
/// <summary>
/// Whether to enable Base64 encoding. This parameter takes effect only when the backend is SCF.
/// </summary>
[JsonProperty("IsBase64Encoded")]
public bool? IsBase64Encoded{ get; set; }
/// <summary>
/// Whether to trigger Base64 encoding by header. This parameter takes effect only when the backend is SCF.
/// </summary>
[JsonProperty("IsBase64Trigger")]
public bool? IsBase64Trigger{ get; set; }
/// <summary>
/// Header trigger rules. The number of rules cannot exceed 10.
/// </summary>
[JsonProperty("Base64EncodedTriggerRules")]
public Base64EncodedTriggerRule[] Base64EncodedTriggerRules{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ServiceId", this.ServiceId);
this.SetParamSimple(map, prefix + "ServiceType", this.ServiceType);
this.SetParamObj(map, prefix + "RequestConfig.", this.RequestConfig);
this.SetParamSimple(map, prefix + "ApiId", this.ApiId);
this.SetParamSimple(map, prefix + "ApiName", this.ApiName);
this.SetParamSimple(map, prefix + "ApiDesc", this.ApiDesc);
this.SetParamSimple(map, prefix + "ApiType", this.ApiType);
this.SetParamSimple(map, prefix + "AuthType", this.AuthType);
this.SetParamSimple(map, prefix + "AuthRequired", this.AuthRequired);
this.SetParamSimple(map, prefix + "ServiceTimeout", this.ServiceTimeout);
this.SetParamSimple(map, prefix + "Protocol", this.Protocol);
this.SetParamSimple(map, prefix + "EnableCORS", this.EnableCORS);
this.SetParamArrayObj(map, prefix + "ConstantParameters.", this.ConstantParameters);
this.SetParamArrayObj(map, prefix + "RequestParameters.", this.RequestParameters);
this.SetParamSimple(map, prefix + "ApiBusinessType", this.ApiBusinessType);
this.SetParamSimple(map, prefix + "ServiceMockReturnMessage", this.ServiceMockReturnMessage);
this.SetParamArrayObj(map, prefix + "MicroServices.", this.MicroServices);
this.SetParamObj(map, prefix + "ServiceTsfLoadBalanceConf.", this.ServiceTsfLoadBalanceConf);
this.SetParamObj(map, prefix + "ServiceTsfHealthCheckConf.", this.ServiceTsfHealthCheckConf);
this.SetParamSimple(map, prefix + "TargetServicesLoadBalanceConf", this.TargetServicesLoadBalanceConf);
this.SetParamObj(map, prefix + "TargetServicesHealthCheckConf.", this.TargetServicesHealthCheckConf);
this.SetParamSimple(map, prefix + "ServiceScfFunctionName", this.ServiceScfFunctionName);
this.SetParamSimple(map, prefix + "ServiceWebsocketRegisterFunctionName", this.ServiceWebsocketRegisterFunctionName);
this.SetParamSimple(map, prefix + "ServiceWebsocketCleanupFunctionName", this.ServiceWebsocketCleanupFunctionName);
this.SetParamSimple(map, prefix + "ServiceWebsocketTransportFunctionName", this.ServiceWebsocketTransportFunctionName);
this.SetParamSimple(map, prefix + "ServiceScfFunctionNamespace", this.ServiceScfFunctionNamespace);
this.SetParamSimple(map, prefix + "ServiceScfFunctionQualifier", this.ServiceScfFunctionQualifier);
this.SetParamSimple(map, prefix + "ServiceWebsocketRegisterFunctionNamespace", this.ServiceWebsocketRegisterFunctionNamespace);
this.SetParamSimple(map, prefix + "ServiceWebsocketRegisterFunctionQualifier", this.ServiceWebsocketRegisterFunctionQualifier);
this.SetParamSimple(map, prefix + "ServiceWebsocketTransportFunctionNamespace", this.ServiceWebsocketTransportFunctionNamespace);
this.SetParamSimple(map, prefix + "ServiceWebsocketTransportFunctionQualifier", this.ServiceWebsocketTransportFunctionQualifier);
this.SetParamSimple(map, prefix + "ServiceWebsocketCleanupFunctionNamespace", this.ServiceWebsocketCleanupFunctionNamespace);
this.SetParamSimple(map, prefix + "ServiceWebsocketCleanupFunctionQualifier", this.ServiceWebsocketCleanupFunctionQualifier);
this.SetParamSimple(map, prefix + "ServiceScfIsIntegratedResponse", this.ServiceScfIsIntegratedResponse);
this.SetParamSimple(map, prefix + "IsDebugAfterCharge", this.IsDebugAfterCharge);
this.SetParamObj(map, prefix + "TagSpecifications.", this.TagSpecifications);
this.SetParamSimple(map, prefix + "IsDeleteResponseErrorCodes", this.IsDeleteResponseErrorCodes);
this.SetParamSimple(map, prefix + "ResponseType", this.ResponseType);
this.SetParamSimple(map, prefix + "ResponseSuccessExample", this.ResponseSuccessExample);
this.SetParamSimple(map, prefix + "ResponseFailExample", this.ResponseFailExample);
this.SetParamObj(map, prefix + "ServiceConfig.", this.ServiceConfig);
this.SetParamSimple(map, prefix + "AuthRelationApiId", this.AuthRelationApiId);
this.SetParamArrayObj(map, prefix + "ServiceParameters.", this.ServiceParameters);
this.SetParamObj(map, prefix + "OauthConfig.", this.OauthConfig);
this.SetParamArrayObj(map, prefix + "ResponseErrorCodes.", this.ResponseErrorCodes);
this.SetParamSimple(map, prefix + "IsBase64Encoded", this.IsBase64Encoded);
this.SetParamSimple(map, prefix + "IsBase64Trigger", this.IsBase64Trigger);
this.SetParamArrayObj(map, prefix + "Base64EncodedTriggerRules.", this.Base64EncodedTriggerRules);
}
}
}
| 46.72118 | 254 | 0.649854 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Apigateway/V20180808/Models/ModifyApiRequest.cs | 17,427 | C# |
using System;
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
#endif
namespace Acedia
{
/// <summary>
/// Hides the field when the editor is in play-mode.
/// </summary>
/// <inheritdoc cref="BaseOnPlayAttribute"/>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class HideOnPlayAttribute : BaseOnPlayAttribute, IMultipleAttribute
{
public bool justDisable { get; private set; }
/// <inheritdoc cref="HideOnPlayAttribute"/>
public HideOnPlayAttribute(bool justDisable = false) : base()
{
this.justDisable = justDisable;
}
#if UNITY_EDITOR
public override bool OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
return false;
}
public override bool GetPropertyHeight(SerializedProperty property, GUIContent label, out float result)
{
result = 0f;
return false;
}
public override bool HidesProperty(SerializedProperty property)
{
return !justDisable && CompareValue(property);
}
#endif
}
}
| 26.5 | 111 | 0.639794 | [
"MIT"
] | imAcedia/unity-acedia-collection | Runtime/Attributes/FieldVisibility/OnPlay/HideOnPlayAttribute.cs | 1,168 | C# |
using Loans.Api.Models;
using Loans.Api.Services.Abstract;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Loans.Api.Services.Concrete
{
public class LoanDetailsService : ILoanDetailsService
{
private readonly LoansContext _context;
public LoanDetailsService(LoansContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<List<LoanDetails>> GetLoanDetails()
{
return await _context.LoanDetail.Include(i => i.LoanTypes).OrderByDescending(o => o.StartDate).ToListAsync();
}
public async Task<LoanDetails> GetLoanDetailsById(int id)
{
return await _context.LoanDetail.Include(i => i.LoanTypes).FirstOrDefaultAsync(f => f.Id == id);
}
public async Task<bool> AddLoanDetails(LoanDetails loanDetails)
{
try
{
_context.LoanDetail.Add(loanDetails);
await _context.SaveChangesAsync();
return true;
}
catch (Exception)
{
throw;
}
}
public async Task<bool> UpdateLoanDetails(LoanDetails loanDetails)
{
try
{
_context.LoanDetail.Update(loanDetails);
await _context.SaveChangesAsync();
return true;
}
catch (Exception)
{
throw;
}
}
}
}
| 27.9 | 121 | 0.574074 | [
"MIT"
] | harshjp722/hp-banking-system | src/Services/Loans/Loans.Api/Services/Concrete/LoanDetailsService.cs | 1,676 | C# |
using KPLN_DataBase.Controll;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace KPLN_DataBase.Collections
{
public class DbUser : DbElement, INotifyPropertyChanged, IDisposable
{
public static ObservableCollection<DbUser> GetAllUsers(ObservableCollection<DbUserInfo> userInfo)
{
ObservableCollection<DbUser> users = new ObservableCollection<DbUser>();
foreach (DbUserInfo userData in userInfo)
{
users.Add(new DbUser(userData));
}
return users;
}
private DbUser(DbUserInfo userData)
{
_systemname = userData.SystemName;
_name = userData.Name;
_family = userData.Family;
_surname = userData.Surname;
_department = userData.Department;
_status = userData.Status;
_connection = userData.Connection;
_sex = userData.Sex;
}
public override string TableName
{
get
{
return "Users";
}
}
private string _systemname { get; set; }
public string SystemName
{
get { return _systemname; }
set
{
if (SQLiteDBUtills.SetValue(this, "SystemName", value))
{
_systemname = value;
NotifyPropertyChanged();
}
}
}
private string _name { get; set; }
public string Name
{
get { return _name; }
set
{
if (SQLiteDBUtills.SetValue(this, "Name", value))
{
_name = value;
NotifyPropertyChanged();
}
}
}
private string _family { get; set; }
public string Family
{
get { return _family; }
set
{
if (SQLiteDBUtills.SetValue(this, "Family", value))
{
_family = value;
NotifyPropertyChanged();
}
}
}
private string _surname { get; set; }
public string Surname
{
get { return _surname; }
set
{
if (SQLiteDBUtills.SetValue(this, "Surname", value))
{
_surname = value;
NotifyPropertyChanged();
}
}
}
private DbDepartment _department { get; set; }
public DbDepartment Department
{
get { return _department; }
set
{
if (SQLiteDBUtills.SetValue(this, "Department", value.Id))
{
_department = value;
NotifyPropertyChanged();
}
}
}
private string _status { get; set; }
public string Status
{
get { return _status; }
set
{
if (SQLiteDBUtills.SetValue(this, "Status", value))
{
_status = value;
NotifyPropertyChanged();
}
}
}
private string _connection { get; set; }
public string Connection
{
get { return _connection; }
set
{
if (SQLiteDBUtills.SetValue(this, "Connection", value))
{
_connection = value;
NotifyPropertyChanged();
}
}
}
private string _sex { get; set; }
public string Sex
{
get { return _sex; }
set
{
if (SQLiteDBUtills.SetValue(this, "Sex", value))
{
_sex = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 29.322148 | 105 | 0.460746 | [
"Apache-2.0"
] | bimkpln/Git_Repo_KPLN | KPLN_DataBase/KPLN_DataBase/Collections/DbUser.cs | 4,371 | C# |
namespace Netnr.Func.ViewModel
{
/// <summary>
/// 登录用户信息
/// </summary>
public class LoginUserVM
{
/// <summary>
/// 用户ID
/// </summary>
public string UserId { get; set; }
/// <summary>
/// 登录账号
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 昵称
/// </summary>
public string Nickname { get; set; }
/// <summary>
/// 角色ID
/// </summary>
public string RoleId { get; set; }
}
}
| 21.192308 | 44 | 0.433757 | [
"MIT"
] | chaojunluo/netnrf | src/Netnr.ResponseFramework/Netnr.Func/ViewModel/LoginUserVM.cs | 585 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ToDoAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.518519 | 70 | 0.642961 | [
"MIT"
] | fupn26/ProjectManager_Onlab_2021 | src/ProjectService/ToDoAPI/Program.cs | 689 | C# |
using Microsoft.AspNetCore.DataProtection;
namespace aggregator.cli
{
class MyProtector
{
readonly IDataProtector _protector;
// the 'provider' parameter is provided by DI
public MyProtector(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Aggregator.CLI.Logon.Protector.v1");
}
public string Encrypt(string input) => _protector.Protect(input);
public string Decrypt(string encrypted) => _protector.Unprotect(encrypted);
}
}
| 26.8 | 87 | 0.682836 | [
"Apache-2.0"
] | rjosborne/aggregator-cli | src/aggregator-cli/Logon/MyProtector.cs | 538 | C# |
using System;
using Newtonsoft.Json;
namespace Timemicro.Zcash.RPCClient
{
public class JsonRPCResponseError
{
public JsonRPCResponseError()
{
}
[JsonProperty("code")]
public string Code
{
get;
set;
}
[JsonProperty("message")]
public string Message
{
get;
set;
}
}
}
| 15.518519 | 37 | 0.479714 | [
"MIT"
] | timemicrotech/Zcash.RPCClient | src/Timemicro.Zcash.RPCClient/JsonRPCResponseError.cs | 421 | C# |
using AutoMapper;
using DasBlog.Core.Common;
using DasBlog.Managers;
using DasBlog.Managers.Interfaces;
using DasBlog.Services.ActivityLogs;
using DasBlog.Services.ConfigFile.Interfaces;
using DasBlog.Services.FileManagement;
using DasBlog.Web.Identity;
using DasBlog.Web.Settings;
using DasBlog.Web.Mappers;
using DasBlog.Web.Services;
using DasBlog.Web.Services.Interfaces;
using DasBlog.Web.TagHelpers.RichEdit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Hosting;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
using System;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using DasBlog.Services.Site;
using DasBlog.Services.ConfigFile;
using DasBlog.Services.Users;
using DasBlog.Services;
using Microsoft.AspNetCore.HttpOverrides;
using DasBlog.Services.FileManagement.Interfaces;
using Microsoft.Extensions.Logging;
namespace DasBlog.Web
{
public class Startup
{
private readonly string SiteSecurityConfigPath;
private readonly string IISUrlRewriteConfigPath;
private readonly string SiteConfigPath;
private readonly string MetaConfigPath;
private readonly string AppSettingsConfigPath;
private readonly string ThemeFolderPath;
private readonly string LogFolderPath;
private readonly string BinariesPath;
private readonly string BinariesUrlRelativePath;
private readonly IWebHostEnvironment hostingEnvironment;
public static IServiceCollection DasBlogServices { get; private set; }
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment env)
{
hostingEnvironment = env;
var envname = string.IsNullOrWhiteSpace(hostingEnvironment.EnvironmentName) ?
"." : string.Format($".{hostingEnvironment.EnvironmentName}.");
SiteSecurityConfigPath = Path.Combine("Config", $"siteSecurity{envname}config");
IISUrlRewriteConfigPath = Path.Combine("Config", $"IISUrlRewrite{envname}config");
SiteConfigPath = Path.Combine("Config", $"site{envname}config");
MetaConfigPath = Path.Combine("Config", $"meta{envname}config");
AppSettingsConfigPath = $"appsettings.json";
Configuration = DasBlogConfigurationBuilder();
BinariesPath = new DirectoryInfo(Path.Combine(env.ContentRootPath, Configuration.GetValue<string>("BinariesDir"))).FullName;
ThemeFolderPath = new DirectoryInfo(Path.Combine(hostingEnvironment.ContentRootPath, "Themes", Configuration.GetSection("Theme").Value)).FullName;
LogFolderPath = new DirectoryInfo(Path.Combine(hostingEnvironment.ContentRootPath, Configuration.GetSection("LogDir").Value)).FullName;
BinariesUrlRelativePath = "content/binary";
}
public IConfiguration DasBlogConfigurationBuilder()
{
var configBuilder = new ConfigurationBuilder();
configBuilder
.AddXmlFile(Path.Combine(hostingEnvironment.ContentRootPath, SiteConfigPath), optional: false, reloadOnChange: true)
.AddXmlFile(Path.Combine(hostingEnvironment.ContentRootPath, MetaConfigPath), optional: false, reloadOnChange: true)
.AddJsonFile(Path.Combine(hostingEnvironment.ContentRootPath, AppSettingsConfigPath), optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
return configBuilder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(builder =>
{
builder.AddFile(opts => opts.LogDirectory = LogFolderPath);
});
services.AddOptions();
services.AddHealthChecks().AddCheck<DasBlogHealthChecks>("health_check");
services.AddMemoryCache();
services.Configure<TimeZoneProviderOptions>(Configuration);
services.Configure<SiteConfig>(Configuration);
services.Configure<MetaTags>(Configuration);
services.Configure<ConfigFilePathsDataOption>(options =>
{
options.SiteConfigFilePath = Path.Combine(hostingEnvironment.ContentRootPath, SiteConfigPath);
options.MetaConfigFilePath = Path.Combine(hostingEnvironment.ContentRootPath, MetaConfigPath);
options.SecurityConfigFilePath = Path.Combine(hostingEnvironment.ContentRootPath, SiteSecurityConfigPath);
options.IISUrlRewriteFilePath = Path.Combine(hostingEnvironment.ContentRootPath, IISUrlRewriteConfigPath);
options.ThemesFolder = ThemeFolderPath;
options.BinaryFolder = BinariesPath;
options.BinaryUrlRelative = string.Format("{0}/", BinariesUrlRelativePath);
});
services.Configure<ActivityRepoOptions>(options
=> options.Path = LogFolderPath);
//Important if you're using Azure, hosting on Nginx, or behind any reverse proxy
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.All;
options.AllowedHosts = Configuration.GetValue<string>("AllowedHosts")?.Split(';').ToList<string>();
});
// Add identity types
services
.AddIdentity<DasBlogUser, DasBlogRole>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/account/login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/account/logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/account/accessdenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromSeconds(10000);
options.Cookie = new CookieBuilder
{
HttpOnly = true
};
});
services.AddResponseCaching();
services.Configure<RazorViewEngineOptions>(rveo =>
{
rveo.ViewLocationExpanders.Add(new DasBlogLocationExpander(Configuration.GetSection("Theme").Value));
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1000);
});
services
.AddHttpContextAccessor();
services
.AddTransient<IDasBlogSettings, DasBlogSettings>()
.AddTransient<IUserStore<DasBlogUser>, DasBlogUserStore>()
.AddTransient<IRoleStore<DasBlogRole>, DasBlogUserRoleStore>()
.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User)
.AddTransient<ISiteRepairer, SiteRepairer>();
services.AddScoped<IRichEditBuilder>(SelectRichEditor)
.AddScoped<IBlogPostViewModelCreator, BlogPostViewModelCreator>();
services
.AddSingleton(hostingEnvironment.ContentRootFileProvider)
.AddSingleton<IBlogManager, BlogManager>()
.AddSingleton<IArchiveManager, ArchiveManager>()
.AddSingleton<ICategoryManager, CategoryManager>()
.AddSingleton<ISiteSecurityManager, SiteSecurityManager>()
.AddSingleton<IXmlRpcManager, XmlRpcManager>()
.AddSingleton<ISiteManager, SiteManager>()
.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
.AddSingleton<IFileSystemBinaryManager, FileSystemBinaryManager>()
.AddSingleton<IUserDataRepo, UserDataRepo>()
.AddSingleton<ISiteSecurityConfig, SiteSecurityConfig>()
.AddSingleton<IUserService, UserService>()
.AddSingleton<IActivityService, ActivityService>()
.AddSingleton<IActivityRepoFactory, ActivityRepoFactory>()
.AddSingleton<IEventLineParser, EventLineParser>()
.AddSingleton<ITimeZoneProvider, TimeZoneProvider>()
.AddSingleton<ISubscriptionManager, SubscriptionManager>()
.AddSingleton<IConfigFileService<MetaTags>, MetaConfigFileService>()
.AddSingleton<IConfigFileService<SiteConfig>, SiteConfigFileService>()
.AddSingleton<IConfigFileService<SiteSecurityConfigData>, SiteSecurityConfigFileService>();
services
.AddAutoMapper((serviceProvider, mapperConfig) =>
{
mapperConfig.AddProfile(new ProfilePost(serviceProvider.GetService<IDasBlogSettings>()));
mapperConfig.AddProfile(new ProfileDasBlogUser(serviceProvider.GetService<ISiteSecurityManager>()));
mapperConfig.AddProfile(new ProfileSettings());
})
.AddMvc()
.AddXmlSerializerFormatters();
services
.AddControllersWithViews()
.AddRazorRuntimeCompilation();
DasBlogServices = services;
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDasBlogSettings dasBlogSettings)
{
(var siteOk, var siteError) = RepairSite(app);
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
//app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/home/error");
}
if (!siteOk)
{
app.Run(async context => await context.Response.WriteAsync(siteError));
return;
}
var options = new RewriteOptions()
.AddIISUrlRewrite(env.ContentRootFileProvider, IISUrlRewriteConfigPath);
app.UseRewriter(options);
app.UseRouting();
//if you've configured it at /blog or /whatever, set that pathbase so ~ will generate correctly
var rootUri = new Uri(dasBlogSettings.SiteConfiguration.Root);
var path = rootUri.AbsolutePath;
//Deal with path base and proxies that change the request path
if (path != "/")
{
app.Use((context, next) =>
{
context.Request.PathBase = new PathString(path);
return next.Invoke();
});
}
app.UseForwardedHeaders();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(BinariesPath),
RequestPath = string.Format("/{0}", BinariesUrlRelativePath)
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Themes")),
RequestPath = "/theme"
});
app.UseAuthentication();
app.Use(PopulateThreadCurrentPrincipalForMvc);
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/healthcheck");
if (dasBlogSettings.SiteConfiguration.EnableTitlePermaLinkUnique)
{
endpoints.MapControllerRoute(
"Original Post Format",
"~/{year:int}/{month:int}/{day:int}/{posttitle}.aspx",
new { controller = "BlogPost", action = "Post", posttitle = "" });
endpoints.MapControllerRoute(
"New Post Format",
"~/{year:int}/{month:int}/{day:int}/{posttitle}",
new { controller = "BlogPost", action = "Post", postitle = "" });
}
else
{
endpoints.MapControllerRoute(
"Original Post Format",
"~/{posttitle}.aspx",
new { controller = "BlogPost", action = "Post", posttitle = "" });
endpoints.MapControllerRoute(
"New Post Format",
"~/{posttitle}",
new { controller = "BlogPost", action = "Post", postitle = "" });
}
endpoints.MapControllerRoute(
name: "default", "~/{controller=Home}/{action=Index}/{id?}");
});
}
/// <summary>
/// BlogDataService and DayEntry rely on the thread's CurrentPrincipal and its role to determine if users
/// should be allowed edit and add posts.
/// Unfortunately the asp.net team no longer favour an approach involving the current thread so
/// much as I am loath to stick values on globalish type stuff going up and down the stack
/// this is a light touch way of including the functionality and actually looks fairly safe.
/// Hopefully, in the fullness of time we will beautify the legacy code and this can go.
/// </summary>
/// <param name="context">provides the user data</param>
/// <param name="next">standdard middleware - in this case MVC iteelf</param>
/// <returns></returns>
private Task PopulateThreadCurrentPrincipalForMvc(HttpContext context, Func<Task> next)
{
IPrincipal existingThreadPrincipal = null;
try
{
existingThreadPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = context.User;
return next();
}
finally
{
Thread.CurrentPrincipal = existingThreadPrincipal;
}
}
private static (bool result, string errorMessage) RepairSite(IApplicationBuilder app)
{
var sr = app.ApplicationServices.GetService<ISiteRepairer>();
return sr.RepairSite();
}
private IRichEditBuilder SelectRichEditor(IServiceProvider serviceProvider)
{
var entryEditControl = serviceProvider.GetService<IDasBlogSettings>().SiteConfiguration.EntryEditControl.ToLower();
IRichEditBuilder richEditBuilder;
switch (entryEditControl)
{
case Constants.TinyMceEditor:
richEditBuilder = new TinyMceBuilder();
break;
case Constants.NicEditEditor:
richEditBuilder = new NicEditBuilder();
break;
case Constants.TextAreaEditor:
richEditBuilder = new TextAreaBuilder();
break;
case Constants.FroalaEditor:
richEditBuilder = new FroalaBuilder();
break;
default:
throw new Exception($"Attempt to use unknown rich edit control, {entryEditControl}");
}
return richEditBuilder;
}
}
}
| 35.856041 | 150 | 0.746989 | [
"MIT"
] | dsmeltz/dasblog-core | source/DasBlog.Web.UI/Startup.cs | 13,950 | C# |
namespace Agoda.Frameworks.LoadBalancing
{
public class FixedDeltaWeightManipulationStrategy : IWeightManipulationStrategy
{
public int Delta { get; }
public FixedDeltaWeightManipulationStrategy(int delta)
{
Delta = delta;
}
public WeightItem UpdateWeight<T>(T source, WeightItem originalWeight, bool isSuccess)
{
var delta = Delta * (isSuccess ? 1 : -1);
return originalWeight.SetNewWeight(delta);
}
}
}
| 26.947368 | 94 | 0.628906 | [
"Apache-2.0"
] | JTOne123/net-loadbalancing | Agoda.Frameworks.LoadBalancing/FixedDeltaWeightManipulationStrategy.cs | 514 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
//using Discount.GRPC.Extensions;
namespace Discount.GRPC
{
public class Program
{
public static void Main(string[] args)
{
//var host = CreateHostBuilder(args).Build();
//host.MigrateDatabase<Program>();
//host.Run();
CreateHostBuilder(args).Build().Run();
}
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 31.84375 | 136 | 0.636899 | [
"MIT"
] | pourali1982/AspNetCoreMicroservices | src/Services/Discount/Discount.GRPC/Program.cs | 1,019 | C# |
using GRINTSYS.SAPRestApi.BussinessLogic.Inputs;
using GRINTSYS.SAPRestApi.Domain.Output;
using GRINTSYS.SAPRestApi.Inputs;
using GRINTSYS.SAPRestApi.Models;
using GRINTSYS.SAPRestApi.Persistence.Repositories;
using SAPbobsCOM;
using System;
using System.Threading.Tasks;
namespace GRINTSYS.SAPRestApi.Domain.Services
{
public enum PaymentStatus
{
CreadoEnAplicacion = 0,
CreadoEnSAP = 1,
Error = 2,
CanceladoPorFinanzas = 3,
Autorizado = 4
}
public enum PaymentType
{
Efectivo = 0,
Cheque = 1,
Transferencia = 2,
EfectivoDolar = 3,
MaquinaPOS = 4
}
public class SapPayment : SapDocumentServiceBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly IPaymentService _paymentService;
private ITenantRepository _tenantRepository;
public SapPayment(IPaymentService paymentService,
ITenantRepository tenantRepository) : base()
{
_paymentService = paymentService;
_tenantRepository = tenantRepository;
}
public override async Task<TaskResponse> Execute(ISapDocumentInput input)
{
log.Info($"Begin to create a payment {((SAPPaymentInput)input).Id}");
TaskResponse response = new TaskResponse() { Success = true, Message = string.Empty };
string message = string.Empty;
try
{
var payment = await _paymentService.GetAsync(((SAPPaymentInput)input).Id);
var tenant = await _tenantRepository.GetTenantById(payment.TenantId);
Company company = this.Connect(new SapSettingsInput { Companydb = "SBO_VH_PRUEBAS"/*tenant.SAPDatabase*/ });
Payments paymentDoc = (Payments)company.GetBusinessObject(BoObjectTypes.oIncomingPayments);
paymentDoc.DocObjectCode = BoPaymentsObjectType.bopot_IncomingPayments;
paymentDoc.DocTypte = BoRcptTypes.rCustomer;
paymentDoc.CardCode = payment.CardCode;
paymentDoc.DocDate = payment.PayedDate;
paymentDoc.TaxDate = DateTime.Now;
paymentDoc.VatDate = DateTime.Now;
paymentDoc.DueDate = DateTime.Now;
paymentDoc.Remarks = payment.Comment;
paymentDoc.JournalRemarks = payment.Comment.Length > 50 ? payment.Comment.Substring(0, 49) : payment.Comment;
paymentDoc.CounterReference = payment.Id.ToString();
if (paymentDoc.UserFields.Fields.Count > 0)
{
paymentDoc.UserFields.Fields.Item("U_Cobrador").Value = payment.AbpUser.PrintBluetoothAddress;
}
if (payment.Type == (int)PaymentType.Efectivo)
{
paymentDoc.CashAccount = payment.Bank.GeneralAccount;
paymentDoc.CashSum = payment.PayedAmount;
}
if (payment.Type == (int)PaymentType.Transferencia || payment.Type == (int)PaymentType.MaquinaPOS)
{
paymentDoc.TransferAccount = payment.Bank.GeneralAccount;
paymentDoc.TransferDate = payment.PayedDate;
paymentDoc.TransferReference = payment.ReferenceNumber;
paymentDoc.TransferSum = payment.PayedAmount;
}
if (payment.Type == (int)PaymentType.EfectivoDolar)
{
/*paymentDoc.CashAccount = payment.Bank.GeneralAccount;
paymentDoc.CashSum = payment.PayedAmount;
paymentDoc.LocalCurrency = BoYesNoEnum.tNO;
paymentDoc.DocCurrency = "USD";*/
message = $"Error tipo de moneda de documento debe ser diferente a dolar $";
payment.Status = (int)PaymentStatus.Error;
response.Success = false;
log.Error(message);
}
if (payment.Type == (int)PaymentType.Cheque)
{
/*paymentDoc.Checks.CheckAccount = payment.Bank.GeneralAccount;
paymentDoc.Checks.CheckSum = payment.PayedAmount;
paymentDoc.Checks.CheckNumber = Convert.ToInt32(payment.ReferenceNumber);
paymentDoc.Checks.DueDate = payment.PayedDate;
//paymentDoc.Checks.BankCode = payment.Bank.Code;
//paymentDoc.Checks.Add();*/
message = $"Error tipo de pago de documento debe ser diferente a cheque.";
payment.Status = (int)PaymentStatus.Error;
response.Success = false;
log.Error(message);
}
if (payment.paymentInvoiceItems != null)
{
foreach (var invoice in payment.paymentInvoiceItems)
{
paymentDoc.Invoices.DocEntry = invoice.DocEntry;
paymentDoc.Invoices.InvoiceType = BoRcptInvTypes.it_Invoice;
paymentDoc.Invoices.SumApplied = invoice.PayedAmount;
//paymentDoc.Invoices.AppliedFC = invoice.PayedAmount;
paymentDoc.Invoices.Add();
}
}
if (response.Success)
{
if (paymentDoc.Add() == 0)
{
string newObjectKey = company.GetNewObjectKey();
message = $"Successfully added Payment. DocEntry: {newObjectKey}";
payment.DocEntry = newObjectKey;
payment.Status = (int)PaymentStatus.CreadoEnSAP;
log.Info(message);
}
else
{
message = $"Error Code: {company.GetLastErrorCode().ToString()} - {company.GetLastErrorDescription()}";
payment.Status = (int)PaymentStatus.Error;
response.Success = false;
log.Error(message);
}
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(paymentDoc);
paymentDoc = null;
company.Disconnect();
response.Message = message;
payment.LastMessage = message;
await _paymentService.UpdateAsync(payment);
}
catch (Exception e)
{
response.Success = false;
response.Message = e.Message;
log.Error(e.Message);
}
return response;
}
}
}
| 42.030488 | 143 | 0.556652 | [
"MIT"
] | Grintsys/GRINTSYS.SAPRestApi | Domain/Services/Payments/SapPaymentService.cs | 6,895 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// La plantilla de elemento Página en blanco está documentada en https://go.microsoft.com/fwlink/?LinkId=234238
namespace MemeCollection
{
/// <summary>
/// Una página vacía que se puede usar de forma independiente o a la que se puede navegar dentro de un objeto Frame.
/// </summary>
public sealed partial class CategoriaDeportesPage : Page
{
public CategoriaDeportesPage()
{
this.InitializeComponent();
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
cargarMemes();
}
private void cargarMemes()
{
this.meme1.titulo = "Baloncesto y hamburguesa";
this.meme1.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme1.jpg"));
this.meme2.titulo = "Baloncesto profesional";
this.meme2.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme2.jpg"));
this.meme3.titulo = "Hazard";
this.meme3.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme3.jpg"));
this.meme4.titulo = "Pelota de Basket";
this.meme4.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme4.jpg"));
this.meme5.titulo = "PSG";
this.meme5.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme5.jpg"));
this.meme6.titulo = "Sevilla";
this.meme6.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme6.jpg"));
this.meme7.titulo = "Wii Basket";
this.meme7.ruta = new BitmapImage(new Uri("ms-appx:///Images/Memes/Deportes/meme7.jpg"));
}
}
}
| 41.576923 | 120 | 0.668363 | [
"MIT"
] | jalvarezz13/MemeCollection | MemeCollection/CategoriaDeportesPage.xaml.cs | 2,168 | C# |
using Floo.Core.Shared;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Floo.Infrastructure
{
public class IdentityContext : IIdentityContext
{
public static readonly IdentityContext Empty = new IdentityContext();
private readonly ClaimsPrincipal User;
public IdentityContext()
{
}
public IdentityContext(IHttpContextAccessor httpContextAccessor)
{
User = httpContextAccessor.HttpContext?.User;
}
public virtual long? UserId => this.GetClaimValueAsLong(User, ClaimTypes.NameIdentifier);
public virtual string UserName => this.GetClaimValue(User, JwtClaimTypes.Name);
public string NickName => this.GetClaimValue(User, JwtClaimTypes.NickName);
public string Avatar => this.GetClaimValue(User, JwtClaimTypes.Picture);
private string GetClaimValue(ClaimsPrincipal user, string claimType)
{
var first = user?.FindFirst(claimType);
return first?.Value;
}
private long? GetClaimValueAsLong(ClaimsPrincipal user, string claimType)
{
var claimValue = this.GetClaimValue(user, claimType);
if (claimValue == null)
{
return null;
}
if (!long.TryParse(claimValue, out var value))
{
return null;
}
return value;
}
public Task GetState()
{
return Task.CompletedTask;
}
}
} | 27.637931 | 97 | 0.618216 | [
"Apache-2.0"
] | ElderJames/Floo | src/Floo.Infrastructure/IdentityContext.cs | 1,605 | C# |
// 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Gets or sets the ISV specific extended information.</summary>
public partial class AssessmentDetailsExtendedInfo
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="AssessmentDetailsExtendedInfo" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
/// <param name="exclusions"></param>
internal AssessmentDetailsExtendedInfo(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet<string> exclusions = null)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IAssociativeArray<string>)this).AdditionalProperties, null ,exclusions );
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IAssessmentDetailsExtendedInfo.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IAssessmentDetailsExtendedInfo.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IAssessmentDetailsExtendedInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new AssessmentDetailsExtendedInfo(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="AssessmentDetailsExtendedInfo" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="AssessmentDetailsExtendedInfo" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IAssociativeArray<string>)this).AdditionalProperties, container);
AfterToJson(ref container);
return container;
}
}
} | 67.242991 | 253 | 0.693398 | [
"MIT"
] | Agazoth/azure-powershell | src/Migrate/generated/api/Models/Api20180901Preview/AssessmentDetailsExtendedInfo.json.cs | 7,089 | C# |
using System;
namespace MathLibrary
{
public class MathHelper
{
public int Max(int x, int y)
{
if (x == y)
{
return x;
}
if (x > y)
{
return x;
}
else
{
return y;
}
}
}
}
| 14.68 | 36 | 0.286104 | [
"MIT"
] | thewahome/math-master | MathLibrary/MathHelper.cs | 369 | C# |
using System;
using System.Globalization;
using System.IO;
using Aspose.Note;
using System.Drawing;
using System.Collections.Generic;
namespace Aspose.Note.Examples.CSharp.Text
{
using System.Linq;
public class ChangeStyle
{
public static void Run()
{
// ExStart:ChangeStyle
// ExFor:RichText.Styles
// ExFor:TextStyle.FontColor
// ExFor:TextStyle.Highlight
// ExFor:TextStyle.FontSize
// ExSummary:Shows how to change style for a text.
string dataDir = RunExamples.GetDataDir_Text();
// Load the document into Aspose.Note.
Document document = new Document(dataDir + "Aspose.one");
// Get a particular RichText node
RichText richText = document.GetChildNodes<RichText>().First();
foreach (TextStyle style in richText.Styles)
{
// Set font color
style.FontColor = Color.Yellow;
// Set highlight color
style.Highlight = Color.Blue;
// Set font size
style.FontSize = 20;
}
// ExEnd:ChangeStyle
Console.WriteLine("\nStyle changed successfully.");
}
}
}
| 26.571429 | 75 | 0.560676 | [
"MIT"
] | alexeiso/Aspose.Note-for-.NET | Examples/CSharp/Text/ChangeStyle.cs | 1,304 | C# |
#region LICENSE
/*
Sora - A Modular Bancho written in C#
Copyright (C) 2019 Robin A. P.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#endregion
using Sora.Attributes;
using Sora.Enums;
using Sora.EventArgs;
using Sora.Helpers;
namespace Sora.Events.BanchoEvents.Multiplayer
{
[EventClass]
public class OnBanchoMatchSettingsEvent
{
[Event(EventType.BanchoMatchChangeSettings)]
public void OnBroadcastFrames(BanchoMatchChangeSettingsArgs args)
{
if (args.pr.JoinedRoom == null)
return;
if (args.pr.JoinedRoom.HostId != args.pr.User.Id)
return;
if (args.pr.JoinedRoom.Name != args.room.Name)
Logger.Info(
"%#F94848%" + args.pr.User.Username,
"%#B342F4%(", args.pr.User.Id, "%#B342F4%)",
"%#FFFFFF% renamed a %#f1fc5a%Multiplayer Room %#FFFFFF%called %#F94848%" +
args.pr.JoinedRoom.Name,
"%#B342F4%(", args.room.MatchId, "%#B342F4%)",
"%#FFFFFF%and is now called %#F94848%" +
args.room.Name,
"%#B342F4%(", args.room.MatchId, "%#B342F4%)"
);
Logger.Info(
"%#F94848%" + args.pr.User.Username,
"%#B342F4%(", args.pr.User.Id, "%#B342F4%)",
"%#FFFFFF%changed the Settings of a %#f1fc5a%Multiplayer Room %#FFFFFF%called %#F94848%" +
args.room.Name,
"%#B342F4%(", args.room.MatchId, "%#B342F4%)"
);
args.pr.JoinedRoom.ChangeSettings(args.room);
}
}
}
| 35.584615 | 106 | 0.587549 | [
"MIT"
] | Tiller431/yes | Sora/Sora/Events/BanchoEvents/Multiplayer/Match/OnBanchoMatchSettingsEvent.cs | 2,313 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace RetroGG.net.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailChangeModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public ConfirmEmailChangeModel(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string email, string code)
{
if (userId == null || email == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ChangeEmailAsync(user, email, code);
if (!result.Succeeded)
{
StatusMessage = "Error changing email.";
return Page();
}
// In our UI email and user name are one and the same, so when we update the email
// we need to update the user name.
var setUserNameResult = await _userManager.SetUserNameAsync(user, email);
if (!setUserNameResult.Succeeded)
{
StatusMessage = "Error changing user name.";
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Thank you for confirming your email change.";
return Page();
}
}
}
| 34.030769 | 120 | 0.617993 | [
"MIT"
] | Tru-Dev/RetroGG.net | RetroGG.net/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs | 2,214 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using NanoFabric.Mediatr.Commands;
using SampleService.Kestrel.Application.CommandSide.Commands;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SampleService.Kestrel.Controllers
{
[Route("api/[controller]")]
public class EchoController : Controller
{
private readonly IMediator _mediator;
public EchoController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPut]
[ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetEcho(
[FromBody] EchoCommand command,
[FromHeader(Name = "x-requestid")] string requestId
)
{
if (!Guid.TryParse(requestId, out var guid))
{
return BadRequest();
}
var identifiedCommand = new IdentifiedCommand<EchoCommand, string>(
command,
guid
);
return Ok(await _mediator.Send(identifiedCommand));
}
}
}
| 28.446809 | 116 | 0.639491 | [
"MIT"
] | AndrewChien/NanoFabric | sample/SampleService.Kestrel/Controllers/EchoController.cs | 1,339 | C# |
/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Design Automation team for Inventor
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using Autodesk.Forge.DesignAutomation.Model;
// ReSharper disable PossibleInvalidOperationException
namespace webapplication.Definitions
{
public class FdaStatsDTO
{
private const double CreditsPerHour = 6.0; // should it be in config?
private const double CreditsPerSecond = CreditsPerHour / 3600.0;
public double Credits { get; set; }
public double? Queueing { get; set; }
public double? Download { get; set; }
public double? Processing { get; set; }
public double? Upload { get; set; }
public double? Total { get; set; }
/// <summary>
/// Generate processing statistics.
/// </summary>
/// <param name="stats"></param>
/// <returns></returns>
public static FdaStatsDTO All(ICollection<Statistics> stats)
{
return Convert(stats);
}
/// <summary>
/// Generate processing statistics for cached item (without timings).
/// </summary>
public static FdaStatsDTO CreditsOnly(ICollection<Statistics> stats)
{
return All(stats).ClearTimings();
}
private static FdaStatsDTO Convert(ICollection<Statistics> stats)
{
if (stats == null || stats.Count == 0) return null;
var sum = new FdaStatsDTO();
foreach (var s in stats)
{
var current = ConvertSingle(s);
sum.Queueing = sum.Queueing.GetValueOrDefault() + current.Queueing;
sum.Download = sum.Download.GetValueOrDefault() + current.Download;
sum.Processing = sum.Processing.GetValueOrDefault() + current.Processing;
sum.Upload = sum.Upload.GetValueOrDefault() + current.Upload;
sum.Total = sum.Total.GetValueOrDefault() + current.Total;
sum.Credits += current.Credits;
}
return sum;
}
private static FdaStatsDTO ConvertSingle(Statistics stats)
{
// it's assumed that statistics calculated for successful job, so all timings are present
var downloadSec = stats.TimeInstructionsStarted.Value.Subtract(stats.TimeDownloadStarted.Value).TotalSeconds;
var processingSec = stats.TimeInstructionsEnded.Value.Subtract(stats.TimeInstructionsStarted.Value).TotalSeconds;
var uploadSec = stats.TimeUploadEnded.Value.Subtract(stats.TimeInstructionsEnded.Value).TotalSeconds;
var result = new FdaStatsDTO
{
Queueing = stats.TimeDownloadStarted.Value.Subtract(stats.TimeQueued).TotalSeconds,
Download = downloadSec,
Processing = processingSec,
Upload = uploadSec,
Total = stats.TimeFinished.Value.Subtract(stats.TimeQueued).TotalSeconds,
Credits = (downloadSec + processingSec + uploadSec) * CreditsPerSecond
};
return result;
}
/// <summary>
/// Remove timings.
/// Used for cached jobs, where timings are not important.
/// </summary>
private FdaStatsDTO ClearTimings()
{
Queueing = null;
Download = null;
Processing = null;
Upload = null;
Total = null;
return this;
}
}
}
| 39.230088 | 125 | 0.588992 | [
"MIT"
] | Developer-Autodesk/forge-configurator-inventor | WebApplication/Definitions/FdaStatsDTO.cs | 4,435 | C# |
using System.Windows;
namespace BreweryApp
{
/// <summary>
/// Logique d'interaction pour App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 15.416667 | 43 | 0.610811 | [
"MIT"
] | yves982/BreweryApp | BreweryApp/App.xaml.cs | 187 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Tci.V20190318.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateLibraryRequest : AbstractModel
{
/// <summary>
/// 人员库名称
/// </summary>
[JsonProperty("LibraryName")]
public string LibraryName{ get; set; }
/// <summary>
/// 人员库唯一标志符,为空则系统自动生成。
/// </summary>
[JsonProperty("LibraryId")]
public string LibraryId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "LibraryName", this.LibraryName);
this.SetParamSimple(map, prefix + "LibraryId", this.LibraryId);
}
}
}
| 30.117647 | 83 | 0.642578 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Tci/V20190318/Models/CreateLibraryRequest.cs | 1,584 | 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: IEntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IMailFolderChildFoldersCollectionRequest.
/// </summary>
public partial interface IMailFolderChildFoldersCollectionRequest : IBaseRequest
{
/// <summary>
/// Adds the specified MailFolder to the collection via POST.
/// </summary>
/// <param name="mailFolder">The MailFolder to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created MailFolder.</returns>
System.Threading.Tasks.Task<MailFolder> AddAsync(MailFolder mailFolder, CancellationToken cancellationToken = default);
/// <summary>
/// Adds the specified MailFolder to the collection via POST and returns a <see cref="GraphResponse{MailFolder}"/> object of the request.
/// </summary>
/// <param name="mailFolder">The MailFolder to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{MailFolder}"/> object of the request.</returns>
System.Threading.Tasks.Task<GraphResponse<MailFolder>> AddResponseAsync(MailFolder mailFolder, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IMailFolderChildFoldersCollectionPage> GetAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Gets the collection page and returns a <see cref="GraphResponse{MailFolderChildFoldersCollectionResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{MailFolderChildFoldersCollectionResponse}"/> object.</returns>
System.Threading.Tasks.Task<GraphResponse<MailFolderChildFoldersCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Expand(Expression<Func<MailFolder, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Select(Expression<Func<MailFolder, object>> selectExpression);
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Top(int value);
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Filter(string value);
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest Skip(int value);
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
IMailFolderChildFoldersCollectionRequest OrderBy(string value);
}
}
| 48.441441 | 157 | 0.642924 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IMailFolderChildFoldersCollectionRequest.cs | 5,377 | C# |
using Shop.Infrastructure.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Shop.Module.Catalog.Entities
{
/// <summary>
/// 产品属性模板(例:女装属性模板、连衣裙属性模板)
/// </summary>
public class ProductAttributeTemplate : EntityBase
{
public ProductAttributeTemplate()
{
CreatedOn = DateTime.Now;
UpdatedOn = DateTime.Now;
}
[Required]
[StringLength(450)]
public string Name { get; set; }
public bool IsDeleted { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public IList<ProductAttributeTemplateRelation> ProductAttributes { get; protected set; } = new List<ProductAttributeTemplateRelation>();
public void AddAttribute(int attributeId)
{
var productTempateProductAttribute = new ProductAttributeTemplateRelation
{
Template = this,
AttributeId = attributeId
};
ProductAttributes.Add(productTempateProductAttribute);
}
}
}
| 27.452381 | 144 | 0.626193 | [
"MIT"
] | LGinC/module-shop | src/server/src/Modules/Shop.Module.Catalog.Abstractions/Entities/ProductAttributeTemplate.cs | 1,203 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NuGet.Common;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.Test.Utility;
using NuGet.Versioning;
using Xunit;
using Xunit.Abstractions;
namespace NuGet.CommandLine.Test
{
public class RestoreNetCoreTest
{
private readonly ITestOutputHelper _output;
public RestoreNetCoreTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public async Task RestoreNetCore_AddExternalTargetVerifyTargetUsedAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var pkgX = new SimpleTestPackageContext("x", "1.0.0");
var pkgY = new SimpleTestPackageContext("y", "1.0.0");
// Add y to the project
projectA.AddPackageToAllFrameworks(pkgY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX, pkgY);
// Inject dependency x
var doc = XDocument.Load(projectA.ProjectPath);
var ns = doc.Root.GetDefaultNamespace().NamespaceName;
doc.Root.AddFirst(
new XElement(XName.Get("Target", ns),
new XAttribute(XName.Get("Name"), "RunMe"),
new XAttribute(XName.Get("BeforeTargets"), "CollectPackageReferences"),
new XElement(XName.Get("ItemGroup", ns),
new XElement(XName.Get("PackageReference", ns),
new XAttribute(XName.Get("Include"), "x"),
new XAttribute(XName.Get("Version"), "1.0.0")))));
doc.Save(projectA.ProjectPath);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
projectA.AssetsFile.GetLibrary("x", NuGetVersion.Parse("1.0.0")).Should().NotBeNull();
projectA.AssetsFile.GetLibrary("y", NuGetVersion.Parse("1.0.0")).Should().NotBeNull();
}
}
[PlatformFact(Platform.Windows)]
public void RestoreNetCore_IfProjectsWitAndWithoutRestoreTargetsExistVerifyValidProjectsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Remove all contents from B to make it invalid for restore.
File.Delete(projectB.ProjectPath);
File.WriteAllText(projectB.ProjectPath, "<Project ToolsVersion=\"15.0\"></Project>");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
File.Exists(projectA.AssetsFileOutputPath).Should().BeTrue();
File.Exists(projectB.AssetsFileOutputPath).Should().BeFalse();
r.AllOutput.Should().Contain("NU1503");
r.AllOutput.Should().Contain("The project file may be invalid or missing targets required for restore.");
}
}
[PlatformFact(Platform.Windows)]
public void RestoreNetCore_IfAllProjectsAreWithoutRestoreTargetsVerifySuccess()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Remove all contents from A to make it invalid for restore.
File.Delete(projectA.ProjectPath);
File.WriteAllText(projectA.ProjectPath, "<Project ToolsVersion=\"15.0\"></Project>");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
File.Exists(projectA.AssetsFileOutputPath).Should().BeFalse();
r.AllOutput.Should().Contain("NU1503");
r.AllOutput.Should().Contain("The project file may be invalid or missing targets required for restore.");
}
}
/// <summary>
/// Create 3 projects, each with their own nuget.config file and source.
/// When restoring with a solution, the settings from the project folder should not be used.
/// </summary>
[Fact]
public async Task RestoreNetCore_WithNuGetExe_WhenRestoringASolution_VerifyPerProjectConfigSourcesAreNotUsed()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projects = new Dictionary<string, SimpleTestProjectContext>();
const string packageId = "packageA";
const string packageVersion = "1.0.0";
await SimpleTestPackageUtility.CreatePackagesAsync(
pathContext.PackageSource,
new SimpleTestPackageContext()
{
Id = packageId,
Version = packageVersion
}
); ;
foreach (var number in new[] { "2", "3" })
{
// Project
var project = SimpleTestProjectContext.CreateNETCore(
$"project{number}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projects.Add(number, project);
// Package
var referencePackage = new SimpleTestPackageContext()
{
Id = packageId,
Version = "*",
PrivateAssets = "all",
};
project.AddPackageToAllFrameworks(referencePackage);
project.Properties.Clear();
solution.Projects.Add(project);
// Source
var source = Path.Combine(pathContext.WorkingDirectory, $"source{number}");
await SimpleTestPackageUtility.CreatePackagesAsync(
source,
new SimpleTestPackageContext()
{
Id = packageId,
Version = $"{number}.0.0"
});
// Create a nuget.config for the project specific source.
var projectDir = Path.GetDirectoryName(project.ProjectPath);
Directory.CreateDirectory(projectDir);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "projectSource"));
sourceEntry.Add(new XAttribute(XName.Get("value"), source));
packageSources.Add(sourceEntry);
File.WriteAllText(configPath, doc.ToString());
}
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, pathContext.SolutionRoot, expectedExitCode: 0);
// Assert
r.Success.Should().BeTrue();
projects.Should().NotBeEmpty();
foreach (var number in projects.Keys)
{
projects[number].AssetsFile.Libraries.Select(e => e.Name).Should().Contain(packageId);
projects[number].AssetsFile.Libraries.Single(e => e.Name.Equals(packageId)).Version.ToString().Should().Be(packageVersion);
}
}
}
/// <summary>
/// Create 3 projects, each with their own nuget.config file and source.
/// When restoring without a solution settings should be found from the project folder.
/// Solution settings are verified in RestoreProjectJson_RestoreFromSlnUsesNuGetFolderSettings and RestoreNetCore_WithNuGetExe_WhenRestoringASolution_VerifyPerProjectConfigSourcesAreNotUsed
/// </summary>
[Fact]
public async Task RestoreNetCore_WithNuGetExe_VerifyPerProjectConfigSourcesAreUsedForChildProjectsWithoutSolutionAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projects = new Dictionary<string, SimpleTestProjectContext>();
var sources = new List<string>();
foreach (var letter in new[] { "A", "B", "C", "D" })
{
// Project
var project = SimpleTestProjectContext.CreateNETCore(
$"project{letter}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projects.Add(letter, project);
solution.Projects.Add(project);
// Package
var package = new SimpleTestPackageContext()
{
Id = $"package{letter}",
Version = "1.0.0"
};
// Do not flow the reference up
package.PrivateAssets = "all";
project.AddPackageToAllFrameworks(package);
project.Properties.Clear();
// Source
var source = Path.Combine(pathContext.WorkingDirectory, $"source{letter}");
await SimpleTestPackageUtility.CreatePackagesAsync(source, package);
sources.Add(source);
// Create a nuget.config for the project specific source.
var projectDir = Path.GetDirectoryName(project.ProjectPath);
Directory.CreateDirectory(projectDir);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "projectSource"));
sourceEntry.Add(new XAttribute(XName.Get("value"), source));
packageSources.Add(sourceEntry);
File.WriteAllText(configPath, doc.ToString());
}
// Create root project
var projectRoot = SimpleTestProjectContext.CreateNETCore(
"projectRoot",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// Link the root project to all other projects
foreach (var child in projects.Values)
{
projectRoot.AddProjectToAllFrameworks(child);
}
projectRoot.Save();
solution.Projects.Add(projectRoot);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectRoot.ProjectPath, expectedExitCode: 0, additionalArgs: "-Recursive");
// Assert
Assert.True(projects.Count > 0);
foreach (var letter in projects.Keys)
{
Assert.True(projects[letter].AssetsFile.Libraries.Select(e => e.Name).Contains($"package{letter}"));
}
}
}
/// <summary>
/// Verify the project level config can override a solution level config's sources.
/// </summary>
[Fact]
public async Task RestoreNetCore_VerifyProjectConfigCanOverrideSolutionConfigAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
// Project
var project = SimpleTestProjectContext.CreateNETCore(
$"projectA",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
solution.Projects.Add(project);
// Package
var packageGood = new SimpleTestPackageContext()
{
Id = $"packageA",
Version = "1.0.0"
};
var packageGoodDep = new SimpleTestPackageContext()
{
Id = $"packageB",
Version = "1.0.0"
};
packageGood.Dependencies.Add(packageGoodDep);
var packageBad = new SimpleTestPackageContext()
{
Id = $"packageA",
Version = "1.0.0"
};
project.AddPackageToAllFrameworks(packageBad);
project.Properties.Clear();
// Source
var source = Path.Combine(pathContext.WorkingDirectory, "sourceA");
// The override source contains an extra dependency
await SimpleTestPackageUtility.CreatePackagesAsync(source, packageGood, packageGoodDep);
// The solution level source does not contain B
await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageBad);
// Create a nuget.config for the project specific source.
var projectDir = Path.GetDirectoryName(project.ProjectPath);
Directory.CreateDirectory(projectDir);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
packageSources.Add(new XElement(XName.Get("clear")));
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "projectSource"));
sourceEntry.Add(new XAttribute(XName.Get("value"), source));
packageSources.Add(sourceEntry);
File.WriteAllText(configPath, doc.ToString());
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, project.ProjectPath);
// Assert
Assert.True(project.AssetsFile.Libraries.Select(e => e.Name).Contains("packageB"));
}
}
[Fact]
public async Task RestoreNetCore_VerifyProjectConfigChangeTriggersARestoreAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
//Act
var r1 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r1.Item1);
Assert.Contains("Writing cache file", r1.Item2);
// Act
var r2 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r2.Item1);
Assert.DoesNotContain("Writing cache file", r2.Item2);
// create a config file
var projectDir = Path.GetDirectoryName(projectA.ProjectPath);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "projectSource"));
sourceEntry.Add(new XAttribute(XName.Get("value"), "https://www.nuget.org/api/v2"));
packageSources.Add(sourceEntry);
var localSource = new XElement(XName.Get("add"));
localSource.Add(new XAttribute(XName.Get("key"), "localSource"));
localSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource));
packageSources.Add(localSource);
File.WriteAllText(configPath, doc.ToString());
// Act
var r3 = Util.RestoreSolution(pathContext, 0, "-configFile", "NuGet.Config");
//Assert.
Assert.Equal(0, r3.Item1);
Assert.Contains("Writing cache file", r3.Item2);
}
}
[Fact]
public async Task RestoreNetCore_VerifyFallbackFoldersChangeTriggersARestoreAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
//Act
var r1 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r1.Item1);
Assert.Contains("Writing cache file", r1.Item2);
// Act
var r2 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r2.Item1);
Assert.DoesNotContain("Writing cache file", r2.Item2);
// create a config file
var projectDir = Path.GetDirectoryName(projectA.ProjectPath);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var packageSources = new XElement(XName.Get("fallbackFolders"));
configuration.Add(packageSources);
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "folder"));
sourceEntry.Add(new XAttribute(XName.Get("value"), "blaa"));
packageSources.Add(sourceEntry);
var sources = new XElement(XName.Get("packageSources"));
configuration.Add(sources);
var localSource = new XElement(XName.Get("add"));
localSource.Add(new XAttribute(XName.Get("key"), "localSource"));
localSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource));
sources.Add(localSource);
File.WriteAllText(configPath, doc.ToString());
// Act
var r3 = Util.RestoreSolution(pathContext, 0, "-configFile", "NuGet.Config");
//Assert.
Assert.Equal(0, r3.Item1);
Assert.Contains("Writing cache file", r3.Item2);
}
}
[Fact]
public async Task RestoreNetCore_VerifyGlobalPackagesPathChangeTriggersARestoreAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
//Act
var r1 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r1.Item1);
Assert.Contains("Writing cache file", r1.Item2);
// Act
var r2 = Util.RestoreSolution(pathContext);
//Assert.
Assert.Equal(0, r2.Item1);
Assert.DoesNotContain("Writing cache file", r2.Item2);
// create a config file
var projectDir = Path.GetDirectoryName(projectA.ProjectPath);
var configPath = Path.Combine(projectDir, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var config = new XElement(XName.Get("config"));
configuration.Add(config);
var sourceEntry = new XElement(XName.Get("add"));
sourceEntry.Add(new XAttribute(XName.Get("key"), "globalPackagesPath"));
sourceEntry.Add(new XAttribute(XName.Get("value"), "blaa"));
configuration.Add(sourceEntry);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
var localSource = new XElement(XName.Get("add"));
localSource.Add(new XAttribute(XName.Get("key"), "localSource"));
localSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource));
packageSources.Add(localSource);
File.WriteAllText(configPath, doc.ToString());
// Act
var r3 = Util.RestoreSolution(pathContext, 0, "-configFile", "NuGet.Config");
//Assert.
Assert.Equal(0, r3.Item1);
Assert.Contains("Writing cache file", r3.Item2);
}
}
[Fact]
public async Task RestoreNetCore_VerifyPackageReference_WithoutRestoreProjectStyleAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
projectA.Properties.Clear();
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var propsXML = XDocument.Load(projectA.PropsOutput);
var styleNode = propsXML.Root.Elements().First().Elements(XName.Get("NuGetProjectStyle", "http://schemas.microsoft.com/developer/msbuild/2003")).FirstOrDefault();
// Assert
var assetsFile = projectA.AssetsFile;
Assert.NotNull(assetsFile);
Assert.Equal(ProjectStyle.PackageReference, assetsFile.PackageSpec.RestoreMetadata.ProjectStyle);
Assert.Equal("PackageReference", styleNode.Value);
}
}
[Fact]
public async Task RestoreNetCore_SetProjectStyleWithProperty_PackageReferenceAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
// Add a project.json file which will be ignored
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net45': {
'x': '1.0.0'
}
}
}");
projectA.AddPackageToAllFrameworks(packageX);
projectA.Properties.Clear();
projectA.Properties.Add("RestoreProjectStyle", "PackageReference");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
File.WriteAllText(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "project.json"), projectJson.ToString());
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var propsXML = XDocument.Load(projectA.PropsOutput);
var styleNode = propsXML.Root.Elements().First().Elements(XName.Get("NuGetProjectStyle", "http://schemas.microsoft.com/developer/msbuild/2003")).FirstOrDefault();
// Assert
var assetsFile = projectA.AssetsFile;
Assert.NotNull(assetsFile);
Assert.Equal(ProjectStyle.PackageReference, assetsFile.PackageSpec.RestoreMetadata.ProjectStyle);
Assert.Equal("PackageReference", styleNode.Value);
}
}
[Fact]
public async Task RestoreNetCore_SetProjectStyleWithProperty_ProjectJsonAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
// Create a .NETCore project, but add a project.json file to it.
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectJson = JObject.Parse(@"{
'dependencies': {
'x': '1.0.0'
},
'frameworks': {
'net45': { }
}
}");
// Force this project to ProjectJson
projectA.Properties.Clear();
projectA.Properties.Add("RestoreProjectStyle", "ProjectJson");
projectA.Type = ProjectStyle.ProjectJson;
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
File.WriteAllText(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "project.json"), projectJson.ToString());
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("build/net45/x.targets");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var projectXML = XDocument.Load(projectA.ProjectPath);
projectXML.Root.AddFirst(new XElement(XName.Get("Target", "http://schemas.microsoft.com/developer/msbuild/2003"), new XAttribute(XName.Get("Name"), "_SplitProjectReferencesByFileExistence")));
projectXML.Save(projectA.ProjectPath);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var assetsFile = projectA.AssetsFile;
Assert.NotNull(assetsFile);
Assert.Equal(ProjectStyle.ProjectJson, assetsFile.PackageSpec.RestoreMetadata.ProjectStyle);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_Recursive()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// B -> C
projectB.AddProjectToAllFrameworks(projectC);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed",
"-Recursive"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectC.AssetsFileOutputPath));
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_RecursiveIgnoresNonRestorable()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"));
var projectB = SimpleTestProjectContext.CreateNonNuGet(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// B -> C
projectB.AddProjectToAllFrameworks(projectC);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed",
"-Recursive"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.False(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectC.AssetsFileOutputPath));
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRIDAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
var assetsFile = projectA.AssetsFile;
Assert.Equal(2, assetsFile.Targets.Count);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal("win7-x86", assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).RuntimeIdentifier);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRID_ValidateRID_FailureAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("ref/net45/x.dll");
packageX.AddFile("lib/win8/x.dll");
projectA.AddPackageToAllFrameworks(packageX);
projectA.Properties.Add("ValidateRuntimeIdentifierCompatibility", "true");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
var output = r.Item2 + " " + r.Item3;
// Assert
Assert.True(r.Item1 == 1);
Assert.Contains("no run-time assembly compatible", output);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRID_ValidateRID_IgnoreFailureAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("ref/net45/x.dll");
packageX.AddFile("lib/win8/x.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Item1 == 0);
Assert.DoesNotContain("no run-time assembly compatible", r.Item3);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRID_ValidateRID_FailureForProjectJsonAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJson = JObject.Parse(@"{
'dependencies': {
'x': '1.0.0'
},
'frameworks': {
'net45': {
}
},
'runtimes': { 'win7-x86': {} }
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("ref/net45/x.dll");
packageX.AddFile("lib/win8/x.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
var output = r.Item2 + " " + r.Item3;
// Assert
Assert.True(r.Item1 == 1);
Assert.Contains("no run-time assembly compatible", output);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRIDSingleAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifier", "win7-x86");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
var assetsFile = projectA.AssetsFile;
Assert.Equal(2, assetsFile.Targets.Count);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal("win7-x86", assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).RuntimeIdentifier);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithRIDDuplicatesAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifier", "win7-x86");
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86;win7-x86;;");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
var assetsFile = projectA.AssetsFile;
Assert.Equal(2, assetsFile.Targets.Count);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal(NuGetFramework.Parse("net45"), assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).TargetFramework);
Assert.Equal("win7-x86", assetsFile.Targets.Single(t => !string.IsNullOrEmpty(t.RuntimeIdentifier)).RuntimeIdentifier);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithSupportsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var guid = Guid.NewGuid().ToString();
projectA.Properties.Add("RuntimeSupports", guid);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var output = r.Item2 + r.Item3;
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), output);
Assert.Contains($"Compatibility Profile: {guid}", output);
}
}
[Fact]
public async Task RestoreNetCore_RestoreWithMultipleRIDsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86;win7-x64");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
var assetsFile = projectA.AssetsFile;
Assert.Equal(3, assetsFile.Targets.Count);
Assert.Equal("win7-x64", assetsFile.Targets.Single(t => t.RuntimeIdentifier == "win7-x64").RuntimeIdentifier);
Assert.Equal("win7-x86", assetsFile.Targets.Single(t => t.RuntimeIdentifier == "win7-x86").RuntimeIdentifier);
}
}
[Fact]
public async Task RestoreNetCore_MultipleProjects_SameToolDifferentVersionsWithMultipleHitsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Create this many different tool versions and projects
var testCount = 10;
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var avoidVersion = $"{testCount + 100}.0.0";
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = avoidVersion
};
var projects = new List<SimpleTestProjectContext>();
for (var i = 0; i < testCount; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
var packageZSub = new SimpleTestPackageContext()
{
Id = "z",
Version = $"{i + 1}.0.0"
};
project.DotnetCLIToolReferences.Add(packageZSub);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageZSub);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
}
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", avoidVersion, "netcoreapp1.0", "project.assets.json");
var zPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
// Version should not be used
Assert.False(File.Exists(path), r.Item2);
// Each project should have its own tool verion
Assert.Equal(testCount, Directory.GetDirectories(zPath).Length);
}
}
[Fact]
public async Task RestoreNetCore_MultipleProjects_SameToolDifferentVersionsWithMultipleHits_NoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Create this many different tool versions and projects
var testCount = 10;
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var avoidVersion = $"{testCount + 100}.0.0";
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = avoidVersion
};
var projects = new List<SimpleTestProjectContext>();
for (var i = 0; i < testCount; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
var packageZSub = new SimpleTestPackageContext()
{
Id = "z",
Version = $"{i + 1}.0.0"
};
project.DotnetCLIToolReferences.Add(packageZSub);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageZSub);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
}
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", avoidVersion, "netcoreapp1.0", "project.assets.json");
var cacheFile = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", avoidVersion, "netcoreapp1.0", "z.nuget.cache");
var zPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
// Version should not be used
Assert.False(File.Exists(path), r.Item2);
Assert.False(File.Exists(cacheFile), r.Item2);
// Each project should have its own tool verion
Assert.Equal(testCount, Directory.GetDirectories(zPath).Length);
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
// Version should not be used
Assert.False(File.Exists(path), r2.Item2);
Assert.False(File.Exists(cacheFile), r2.Item2);
Assert.DoesNotContain("NU1603", r2.Item2);
for (var i = 1; i <= testCount; i++)
{
Assert.Contains($"The restore inputs for 'z-netcoreapp1.0-[{i}.0.0, )' have not changed. No further actions are required to complete the restore.", r2.Item2);
}
// Each project should have its own tool verion
Assert.Equal(testCount, Directory.GetDirectories(zPath).Length);
}
}
[Fact]
public async Task RestoreNetCore_NoOp_AddingNewPackageRestoresAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "20.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
//re-arrange again
project.AddPackageToAllFrameworks(packageZ);
project.Save();
//assert
Assert.Contains("Writing cache file", r.Item2);
Assert.Equal(0, r.Item1);
}
}
[Fact]
public async Task RestoreNetCore_OriginalTargetFrameworkArePreservedAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCoreWithSDK(
"proj",
pathContext.SolutionRoot,
"net46",
"net45");
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
Assert.Equal(0, r.Item1);
Assert.True(File.Exists(project.PropsOutput), r.Item2);
var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput));
var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ItemGroup").ToList();
Assert.Contains("'$(TargetFramework)' == 'net45' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Contains("'$(TargetFramework)' == 'net46' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[2].Attribute(XName.Get("Condition")).Value.Trim());
}
}
[Fact]
public async Task RestoreNetCore_NoOp_AddingANewProjectRestoresOnlyThatProjectAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "20.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
// build project
var project2 = SimpleTestProjectContext.CreateNETCore(
$"proj2",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project2.AddPackageToAllFrameworks(packageZ);
solution.Projects.Add(project2);
solution.Save();
project2.Save();
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.Equal(0, r2.Item1);
Assert.Contains("Writing cache file", r2.Item2);
Assert.Contains("No further actions are required to complete", r2.Item2);
}
}
[Fact]
public async Task RestoreNetCore_NoOp_WarningsAndErrorsDontAffectHashAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
// Setup - set warnings As Errors
project.WarningsAsErrors = true;
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
//Setup - remove the warnings and errors
project.WarningsAsErrors = false;
project.Save();
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.Equal(0, r2.Item1);
Assert.Contains("No further actions are required to complete", r2.Item2);
}
}
[Fact(Skip = "https://github.com/NuGet/Home/issues/10075")]
public async Task RestoreNetCore_MultipleProjects_SameToolDifferentVersionsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "20.0.0"
};
var projects = new List<SimpleTestProjectContext>();
for (var i = 0; i < 10; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = $"{i}.0.0"
});
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
}
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "20.0.0", "netcoreapp1.0", "project.assets.json");
var zPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(path), r.Item2);
Assert.Equal(1, Directory.GetDirectories(zPath).Length);
}
}
[Fact]
public async Task RestoreNetCore_MultipleProjects_SameToolAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
for (var i = 0; i < 10; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
});
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
}
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "project.assets.json");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(path), r.Item2);
}
}
[Fact(Skip = "https://github.com/NuGet/Home/issues/9128")]
public async Task RestoreNetCore_MultipleProjects_SameTool_DifferentVersionRanges_DoesNotNoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj1",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
});
var project2 = SimpleTestProjectContext.CreateNETCore(
$"proj2",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project2.AddPackageToAllFrameworks(packageX);
project2.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "1.5.*"
});
solution.Projects.Add(project2);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// This is expected, because despite the fact that both projects resolve to the same tool, the version range they request is different so they will keep overwriting each other
// Basically, it is impossible for both tools to no-op.
Assert.Contains($"Writing tool assets file to disk", r2.Item2);
r = Util.RestoreSolution(pathContext);
}
}
[Fact(Skip = "https://github.com/NuGet/Home/issues/9128")]
public async Task RestoreNetCore_MultipleProjects_SameTool_OverlappingVersionRanges_DoesNoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj1",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
});
var project2 = SimpleTestProjectContext.CreateNETCore(
$"proj2",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project2.AddPackageToAllFrameworks(packageX);
project2.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.*"
});
solution.Projects.Add(project2);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// This is expected, because despite the fact that both projects resolve to the same tool, the version range they request is different so they will keep overwriting each other
// Basically, it is impossible for both tools to no-op.
Assert.Contains($"Writing tool assets file to disk", r2.Item2);
}
}
[Fact]
public async Task RestoreNetCore_MultipleProjects_SameTool_OverlappingVersionRanges_OnlyOneMatchesPackage_DoesNoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "2.5.0"
};
var packageZ20 = new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj1",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.0"
});
var project2 = SimpleTestProjectContext.CreateNETCore(
$"proj2",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project2.AddPackageToAllFrameworks(packageX);
project2.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "2.0.*"
});
solution.Projects.Add(project2);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.5.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.5.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Setup Again. Add the new package....should not be picked up though
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageZ20);
var assetsPath20 = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath20 = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "2.0.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
Assert.True(File.Exists(assetsPath20));
Assert.True(File.Exists(cachePath20));
}
}
[Fact]
public async Task RestoreNetCore_MultipleProjects_SameTool_NoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
for (var i = 0; i < 10; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
});
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
}
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
Assert.Contains($"The restore inputs for 'z-netcoreapp1.0-[1.0.0, )' have not changed. No further actions are required to complete the restore", r2.Item2);
r = Util.RestoreSolution(pathContext);
}
}
[Fact]
public async Task RestoreNetCore_SingleToolRestoreAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageZ.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
projectA.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
});
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ,
packageY);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "project.assets.json");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(path), r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_SingleToolRestore_NoopAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageZ.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
projectA.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
});
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ,
packageY);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "z.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
Assert.Contains($"The restore inputs for 'z-netcoreapp1.0-[1.0.0, )' have not changed. No further actions are required to complete the restore.", r2.Item2);
r = Util.RestoreSolution(pathContext);
}
}
// Just utlizing the infrastracture that we have here, rather than trying to create my own directory structure to test this :)
[Theory]
[InlineData("[1.0.0]", "1.0.0")]
[InlineData("[5.0.0]", "5.0.0")]
[InlineData("[1.5.0]", null)]
[InlineData("1.1.*", "2.0.0")]
public async Task ToolPathResolver_FindsBestMatchingToolVersionAsync(string requestedVersion, string expectedVersion)
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
for (var i = 0; i < 10; i++)
{
var project = SimpleTestProjectContext.CreateNETCore(
$"proj{i}",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = $"{i}.0.0"
};
project.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = $"{i}.0.0"
});
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageZ);
solution.Projects.Add(project);
}
solution.Create(pathContext.SolutionRoot);
var r = Util.RestoreSolution(pathContext);
// Arrange
var target = new ToolPathResolver(pathContext.UserPackagesFolder, isLowercase: true);
var expected = expectedVersion != null ?
Path.Combine(
pathContext.UserPackagesFolder,
".tools",
"z",
expectedVersion,
"netcoreapp1.0")
: null;
// Act
var actual = target.GetBestToolDirectoryPath("z", VersionRange.Parse(requestedVersion), NuGetFramework.Parse("netcoreapp1.0"));
// Assert
Assert.True(StringComparer.Ordinal.Equals(expected, actual), $"{expected} : {actual}");
}
}
[Fact]
public async Task RestoreNetCore_RestoreToolInChildProjectWithRecursive_NoOpAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectB.DotnetCLIToolReferences.Add(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var assetsPath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "x", "1.0.0", "netcoreapp1.0", "project.assets.json");
var cachePath = Path.Combine(pathContext.UserPackagesFolder, ".tools", "x", "1.0.0", "netcoreapp1.0", "x.nuget.cache");
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 0, additionalArgs: "-Recursive");
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
// Act
var r2 = Util.RestoreSolution(pathContext, expectedExitCode: 0, additionalArgs: "-Recursive");
// Assert
Assert.True(File.Exists(assetsPath));
Assert.True(File.Exists(cachePath));
Assert.Contains($"The restore inputs for 'x-netcoreapp1.0-[1.0.0, )' have not changed. No further actions are required to complete the restore.", r2.Item2);
Assert.Contains($"The restore inputs for 'a' have not changed. No further actions are required to complete the restore.", r2.Item2);
Assert.Contains($"The restore inputs for 'b' have not changed. No further actions are required to complete the restore.", r2.Item2);
r = Util.RestoreSolution(pathContext);
}
}
[Fact]
public async Task RestoreNetCore_RestoreToolInChildProjectWithRecursiveAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectB.DotnetCLIToolReferences.Add(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "x", "1.0.0", "netcoreapp1.0", "project.assets.json");
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 0, additionalArgs: "-Recursive");
// Assert
Assert.True(File.Exists(path), r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_SkipRestoreToolInChildProjectForNonRecursiveAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectB.DotnetCLIToolReferences.Add(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "x", "1.0.0", "netcoreapp1.0", "project.assets.json");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.False(File.Exists(path), r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_ToolRestoreWithNoVersionAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageZ.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
projectA.DotnetCLIToolReferences.Add(new SimpleTestPackageContext()
{
Id = "z",
Version = ""
});
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageZ,
packageY);
var path = Path.Combine(pathContext.UserPackagesFolder, ".tools", "z", "1.0.0", "netcoreapp1.0", "project.assets.json");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.Contains("WARNING: NU1604", r.AllOutput);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyImportOrderAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
var packageS = new SimpleTestPackageContext()
{
Id = "s",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/x.targets");
packageZ.AddFile("buildCrossTargeting/z.targets");
packageS.AddFile("buildCrossTargeting/s.targets");
packageX.AddFile("buildCrossTargeting/x.props");
packageZ.AddFile("buildCrossTargeting/z.props");
packageS.AddFile("buildCrossTargeting/s.props");
packageX.AddFile("build/x.targets");
packageZ.AddFile("build/z.targets");
packageS.AddFile("build/s.targets");
packageX.AddFile("build/x.props");
packageZ.AddFile("build/z.props");
packageS.AddFile("build/s.props");
packageX.AddFile("lib/net45/test.dll");
packageZ.AddFile("lib/net45/test.dll");
packageS.AddFile("lib/net45/test.dll");
// To avoid sorting on case accidently
// A -> X -> Z -> S
packageX.Dependencies.Add(packageZ);
packageZ.Dependencies.Add(packageS);
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageZ);
projectA.AddPackageToAllFrameworks(packageS);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
var targetsXML = XDocument.Parse(File.ReadAllText(projectA.TargetsOutput));
var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList();
var propsXML = XDocument.Parse(File.ReadAllText(projectA.PropsOutput));
var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList();
// CrossTargeting should be first
Assert.Equal(2, targetItemGroups.Count);
Assert.Equal("'$(TargetFramework)' == '' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal("'$(TargetFramework)' == 'net45' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal(3, targetItemGroups[0].Elements().Count());
Assert.EndsWith("s.targets", targetItemGroups[0].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("z.targets", targetItemGroups[0].Elements().ToList()[1].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("x.targets", targetItemGroups[0].Elements().ToList()[2].Attribute(XName.Get("Project")).Value);
Assert.Equal(3, targetItemGroups[1].Elements().Count());
Assert.EndsWith("s.targets", targetItemGroups[1].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("z.targets", targetItemGroups[1].Elements().ToList()[1].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("x.targets", targetItemGroups[1].Elements().ToList()[2].Attribute(XName.Get("Project")).Value);
Assert.Equal(2, propsItemGroups.Count);
Assert.Equal("'$(TargetFramework)' == '' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal("'$(TargetFramework)' == 'net45' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal(3, propsItemGroups[0].Elements().Count());
Assert.EndsWith("s.props", propsItemGroups[0].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("z.props", propsItemGroups[0].Elements().ToList()[1].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("x.props", propsItemGroups[0].Elements().ToList()[2].Attribute(XName.Get("Project")).Value);
Assert.Equal(3, propsItemGroups[1].Elements().Count());
Assert.EndsWith("s.props", propsItemGroups[1].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("z.props", propsItemGroups[1].Elements().ToList()[1].Attribute(XName.Get("Project")).Value);
Assert.EndsWith("x.props", propsItemGroups[1].Elements().ToList()[2].Attribute(XName.Get("Project")).Value);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyImportIsAddedAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/x.targets");
packageX.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
var targetsXML = XDocument.Parse(File.ReadAllText(projectA.TargetsOutput));
var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList();
Assert.Equal(1, targetItemGroups.Count);
Assert.Equal("'$(TargetFramework)' == '' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal(1, targetItemGroups[0].Elements().Count());
Assert.EndsWith("x.targets", targetItemGroups[0].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyNoDuplicateImportsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
NuGetFramework.Parse("net46"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/x.targets");
packageX.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
var targetsXML = XDocument.Parse(File.ReadAllText(projectA.TargetsOutput));
var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList();
Assert.Equal(1, targetItemGroups.Count);
Assert.Equal("'$(TargetFramework)' == '' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Equal(1, targetItemGroups[0].Elements().Count());
Assert.EndsWith("x.targets", targetItemGroups[0].Elements().ToList()[0].Attribute(XName.Get("Project")).Value);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyImportIsNotAddedForUAPAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net45': {
'x': '1.0.0'
}
}
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/x.targets");
packageX.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.False(File.Exists(projectA.TargetsOutput), r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyImportRequiresPackageNameAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/a.targets");
packageX.AddFile("buildCrossTargeting/a.props");
packageX.AddFile("buildCrossTargeting/a.txt");
packageX.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var msbuildTargetsItems = TargetsUtility.GetMSBuildPackageImports(projectA.TargetsOutput);
var msbuildPropsItems = TargetsUtility.GetMSBuildPackageImports(projectA.PropsOutput);
// Assert
Assert.Equal(0, msbuildTargetsItems.Count);
Assert.Equal(0, msbuildPropsItems.Count);
}
}
[Fact]
public async Task RestoreNetCore_VerifyBuildCrossTargeting_VerifyImportNotAllowedInSubFolderAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageX.AddFile("buildCrossTargeting/net45/x.targets");
packageX.AddFile("buildCrossTargeting/net45/x.props");
packageX.AddFile("lib/net45/test.dll");
packageY.AddFile("buildCrossTargeting/a.targets");
packageY.AddFile("buildCrossTargeting/a.props");
packageY.AddFile("buildCrossTargeting/net45/y.targets");
packageY.AddFile("buildCrossTargeting/net45/y.props");
packageY.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
var msbuildTargetsItems = TargetsUtility.GetMSBuildPackageImports(projectA.TargetsOutput);
var msbuildPropsItems = TargetsUtility.GetMSBuildPackageImports(projectA.PropsOutput);
// Assert
Assert.Equal(0, msbuildTargetsItems.Count);
Assert.Equal(0, msbuildPropsItems.Count);
}
}
[Fact]
public async Task RestoreNetCore_NETCoreImports_VerifyImportFromPackageIsIgnoredAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("build/x.props", "<Project>This is a bad props file!!!!<");
packageX.AddFile("build/x.targets", "<Project>This is a bad target file!!!!<");
packageX.AddFile("lib/net45/test.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Restore one
var r = Util.RestoreSolution(pathContext);
var msbuildTargetsItems = TargetsUtility.GetMSBuildPackageImports(projectA.TargetsOutput);
var msbuildPropsItems = TargetsUtility.GetMSBuildPackageImports(projectA.PropsOutput);
// Assert
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.Equal(1, msbuildTargetsItems.Count);
Assert.Equal(1, msbuildPropsItems.Count);
// Act
r = Util.RestoreSolution(pathContext);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
msbuildTargetsItems = TargetsUtility.GetMSBuildPackageImports(projectA.TargetsOutput);
msbuildPropsItems = TargetsUtility.GetMSBuildPackageImports(projectA.PropsOutput);
Assert.Equal(1, msbuildTargetsItems.Count);
Assert.Equal(1, msbuildPropsItems.Count);
Assert.True(r.Item1 == 0);
}
}
[Fact]
public async Task RestoreNetCore_UAPImports_VerifyImportFromPackageIsIgnoredAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJson = JObject.Parse(@"{
'dependencies': {
'x': '1.0.0'
},
'frameworks': {
'net45': {
}
}
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("build/x.props", "<Project>This is a bad props file!!!!<");
packageX.AddFile("build/x.targets", "<Project>This is a bad target file!!!!<");
packageX.AddFile("lib/net45/test.dll");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Restore one
var r = Util.RestoreSolution(pathContext);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
// Act
r = Util.RestoreSolution(pathContext);
Assert.True(r.Item1 == 0);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_ProjectToProject_InterweavingAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
// A B C D E F G
// NETCore -> UAP -> Unknown -> NETCore -> UAP -> Unknown -> NETCore
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net45': { }
}
}");
var projectB = SimpleTestProjectContext.CreateUAP(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
var projectC = SimpleTestProjectContext.CreateNonNuGet(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectD = SimpleTestProjectContext.CreateNETCore(
"d",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectE = SimpleTestProjectContext.CreateUAP(
"e",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
var projectF = SimpleTestProjectContext.CreateNonNuGet(
"f",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectG = SimpleTestProjectContext.CreateNETCore(
"g",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// Link everything
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddProjectToAllFrameworks(projectC);
projectC.AddProjectToAllFrameworks(projectD);
projectD.AddProjectToAllFrameworks(projectE);
projectE.AddProjectToAllFrameworks(projectF);
projectF.AddProjectToAllFrameworks(projectG);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0-beta"
};
// G -> X
projectG.AddPackageToAllFrameworks(packageX);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Projects.Add(projectD);
solution.Projects.Add(projectE);
solution.Projects.Add(projectF);
solution.Projects.Add(projectG);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targets = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.ToDictionary(e => e.Name);
var libs = projectA.AssetsFile.Libraries.ToDictionary(e => e.Name);
// Verify everything showed up
Assert.Equal(new[] { "b", "c", "d", "e", "f", "g", "x" }, libs.Keys.OrderBy(s => s, StringComparer.OrdinalIgnoreCase));
Assert.Equal("1.0.0-beta", targets["x"].Version.ToNormalizedString());
Assert.Equal("package", targets["x"].Type);
Assert.Equal("1.0.0", targets["g"].Version.ToNormalizedString());
Assert.Equal("project", targets["g"].Type);
Assert.Equal(".NETFramework,Version=v4.5", targets["g"].Framework);
Assert.Equal("1.0.0", libs["g"].Version.ToNormalizedString());
Assert.Equal("project", libs["g"].Type);
Assert.Equal("../g/g.csproj", libs["g"].MSBuildProject);
Assert.Equal("../g/g.csproj", libs["g"].Path);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCoreToUnknown()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNonNuGet(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
// This is not populated for unknown project types, but this may change in the future.
Assert.Null(targetB.Framework);
Assert.Equal("../b/b.csproj", libB.Path);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCoreToUAP()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net45': { }
}
}");
var projectB = SimpleTestProjectContext.CreateUAP(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
projectJson);
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(".NETFramework,Version=v4.5", targetB.Framework);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
Assert.Equal("../b/project.json", libB.Path); // TODO: is this right?
}
}
[Fact]
public async Task RestoreNetCore_ProjectToProject_UAPToNetCoreAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'UAP10.0': { }
}
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("UAP10.0"),
projectJson);
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("netstandard1.3"),
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageY);
projectB.Frameworks[0].PackageReferences.Add(packageX);
projectB.Frameworks[1].PackageReferences.Add(packageY);
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var tfm = NuGetFramework.Parse("UAP10.0");
var target = projectA.AssetsFile.GetTarget(tfm, runtimeIdentifier: null);
var targetB = target.Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
var targetX = projectA.AssetsFile.Targets.Single(t => string.IsNullOrEmpty(t.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "x");
var targetY = projectA.AssetsFile.Targets.Single(t => string.IsNullOrEmpty(t.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "y");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(".NETStandard,Version=v1.3", targetB.Framework);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
Assert.Equal("../b/b.csproj", libB.Path);
Assert.Equal("1.0.0", targetX.Version.ToNormalizedString());
Assert.Null(targetY);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_UAPToUnknown()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'UAP10.0': { }
}
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("UAP10.0"),
projectJson);
var projectB = SimpleTestProjectContext.CreateNonNuGet(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("netstandard1.3"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("UAP10.0"))).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Null(targetB.Framework);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
Assert.Equal("../b/b.csproj", libB.Path);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_UAPToUAP_RestoreCSProjDirect()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectJsonA = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'NETCoreApp1.0': { }
}
}");
var projectA = SimpleTestProjectContext.CreateUAP(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"),
projectJsonA);
var projectJsonB = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'netstandard1.5': { }
}
}");
var projectB = SimpleTestProjectContext.CreateUAP(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"),
projectJsonB);
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("NETCoreApp1.0"))).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(NuGetFramework.Parse("netstandard1.5"), NuGetFramework.Parse(targetB.Framework));
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
Assert.Equal("../b/project.json", libB.Path);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCore_TransitiveForAllEdges()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net462': { }
}
}");
var projectC = SimpleTestProjectContext.CreateUAP(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"),
projectJson);
var projectD = SimpleTestProjectContext.CreateNonNuGet(
"d",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
var projectE = SimpleTestProjectContext.CreateNETCore(
"e",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
// Straight line
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddProjectToAllFrameworks(projectC);
projectC.AddProjectToAllFrameworks(projectD);
projectD.AddProjectToAllFrameworks(projectE);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Projects.Add(projectD);
solution.Projects.Add(projectE);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
var assetsFile = projectA.AssetsFile;
// Find all non _._ compile assets
var flowingCompile = assetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries
.Where(e => e.Type == "project")
.Where(e => e.CompileTimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any())
.Select(e => e.Name)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
Assert.Equal("bcde", string.Join("", flowingCompile));
// Runtime should always flow
var flowingRuntime = assetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries
.Where(e => e.Type == "project")
.Where(e => e.RuntimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any())
.Select(e => e.Name)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
Assert.Equal("bcde", string.Join("", flowingRuntime));
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCore_TransitiveOffForAllEdges()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
projectA.PrivateAssets = "compile";
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
projectB.PrivateAssets = "compile";
var projectJson = JObject.Parse(@"{
'dependencies': {
},
'frameworks': {
'net462': { }
}
}");
var projectC = SimpleTestProjectContext.CreateUAP(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"),
projectJson);
projectC.PrivateAssets = "compile";
var projectD = SimpleTestProjectContext.CreateNonNuGet(
"d",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
projectD.PrivateAssets = "compile";
var projectE = SimpleTestProjectContext.CreateNETCore(
"e",
pathContext.SolutionRoot,
NuGetFramework.Parse("net462"));
projectE.PrivateAssets = "compile";
// Straight line
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddProjectToAllFrameworks(projectC);
projectC.AddProjectToAllFrameworks(projectD);
projectD.AddProjectToAllFrameworks(projectE);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Projects.Add(projectD);
solution.Projects.Add(projectE);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
var assetsFile = projectA.AssetsFile;
// Find all non _._ compile assets
var flowingCompile = assetsFile.Targets.Single(e => string.IsNullOrEmpty(e.RuntimeIdentifier)).Libraries
.Where(e => e.Type == "project")
.Where(e => e.CompileTimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any())
.Select(e => e.Name)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
Assert.Equal("b", string.Join("", flowingCompile));
// Runtime should always flow
var flowingRuntime = assetsFile.Targets.Single(e => string.IsNullOrEmpty(e.RuntimeIdentifier)).Libraries
.Where(e => e.Type == "project")
.Where(e => e.RuntimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any())
.Select(e => e.Name)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
Assert.Equal("bcde", string.Join("", flowingRuntime));
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCoreToNETCore_RestoreCSProjDirect()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("NETCoreApp1.0")) && string.IsNullOrEmpty(e.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(NuGetFramework.Parse("netstandard1.5"), NuGetFramework.Parse(targetB.Framework));
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
Assert.Equal("../b/b.csproj", libB.Path);
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCoreToNETCore_VerifyVersionForDependency()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectD = SimpleTestProjectContext.CreateNETCore(
"d",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// A -> C
projectA.AddProjectToAllFrameworks(projectC);
// C -> D
projectC.AddProjectToAllFrameworks(projectD);
// Set project versions
projectB.Version = "2.4.5-alpha.1.2+build.a.b.c";
projectC.Version = "2.4.5-ignorethis";
projectD.Version = "1.4.9-child.project";
// Override with PackageVersion
projectC.Properties.Add("PackageVersion", "2.4.5-alpha.7+use.this");
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Projects.Add(projectD);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.True(0 == r.Item1, r.Item2 + " " + r.Item3);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("NETCoreApp1.0")) && string.IsNullOrEmpty(e.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
var targetC = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("NETCoreApp1.0")) && string.IsNullOrEmpty(e.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "c");
var libC = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "c");
var dDep = targetC.Dependencies.Single();
Assert.Equal("project", targetB.Type);
Assert.Equal("2.4.5-alpha.1.2", targetB.Version.ToNormalizedString());
Assert.Equal("2.4.5-alpha.1.2", libB.Version.ToNormalizedString());
Assert.Equal("project", targetC.Type);
Assert.Equal("2.4.5-alpha.7", targetC.Version.ToNormalizedString());
Assert.Equal("2.4.5-alpha.7", libC.Version.ToNormalizedString());
// Verify the correct version of D is shown under project C
Assert.Equal("[1.4.9-child.project, )", dDep.VersionRange.ToNormalizedString());
}
}
[Fact]
public void RestoreNetCore_ProjectToProject_NETCoreToNETCore_VerifyVersionForDependency_WithSnapshotsFails()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETCoreApp1.0"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
var projectD = SimpleTestProjectContext.CreateNETCore(
"d",
pathContext.SolutionRoot,
NuGetFramework.Parse("NETStandard1.5"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// A -> C
projectA.AddProjectToAllFrameworks(projectC);
// C -> D
projectC.AddProjectToAllFrameworks(projectD);
// Set project versions
projectA.Version = "2.0.0-a.*";
projectB.Version = "2.0.0-b.*";
projectC.Version = "2.0.0-c.*";
projectD.Version = "2.0.0-d.*";
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Projects.Add(projectD);
solution.Create(pathContext.SolutionRoot);
// Act
var nugetexe = Util.GetNuGetExePath();
var args = new string[] {
"restore",
projectA.ProjectPath,
"-Verbosity",
"detailed"
};
// Act
var r = CommandRunner.Run(
nugetexe,
pathContext.WorkingDirectory.Path,
string.Join(" ", args),
waitForExit: true);
// Assert
Assert.False(0 == r.Item1, r.Item2 + " " + r.Item3);
}
}
[Fact]
public async Task RestoreNetCore_VerifyPropsAndTargetsAreWrittenWhenRestoreFailsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("build/net45/x.targets");
var packageY = new SimpleTestPackageContext("y");
packageX.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var yPath = await SimpleTestPackageUtility.CreateFullPackageAsync(pathContext.PackageSource, packageY);
await SimpleTestPackageUtility.CreateFullPackageAsync(pathContext.PackageSource, packageX);
// y does not exist
yPath.Delete();
// Act
// Verify failure
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
var targets = TargetsUtility.GetMSBuildPackageImports(projectA.TargetsOutput);
// Assert
// Verify all files were written
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
Assert.Equal(1, targets.Count);
}
}
[Fact]
public async Task RestoreNetCore_SingleProjectAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
r.AllOutput.Should().NotContain("NU1503");
}
}
[Fact]
public async Task RestoreNetCore_SingleProjectWithPackageTargetFallbackAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("lib/dnxcore50/a.dll");
projectA.AddPackageToAllFrameworks(packageX);
// Add imports property
projectA.Properties.Add("PackageTargetFallback", "portable-net45+win8;dnxcore50");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var xTarget = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.Single();
// Assert
Assert.Equal("lib/dnxcore50/a.dll", xTarget.CompileTimeAssemblies.Single());
}
}
[Fact]
public async Task RestoreNetCore_SingleProjectWithPackageTargetFallbackAndWhitespaceAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile("lib/dnxcore50/a.dll");
projectA.AddPackageToAllFrameworks(packageX);
// Add imports property with whitespace
projectA.Properties.Add("PackageTargetFallback", "\n\t portable-net45+win8 ; ; dnxcore50\n ");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var xTarget = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.Single();
// Assert
Assert.Equal("lib/dnxcore50/a.dll", xTarget.CompileTimeAssemblies.Single());
}
}
[Fact]
public async Task RestoreNetCore_SingleProject_SingleTFMAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var xml = File.ReadAllText(projectA.ProjectPath);
xml = xml.Replace("<TargetFrameworks>", "<TargetFramework>");
xml = xml.Replace("</TargetFrameworks>", "</TargetFramework>");
File.WriteAllText(projectA.ProjectPath, xml);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
Assert.Equal(NuGetFramework.Parse("net45"), projectA.AssetsFile.Targets.Single(e => string.IsNullOrEmpty(e.RuntimeIdentifier)).TargetFramework);
}
}
[Fact]
public void RestoreNetCore_SingleProject_NonNuGet()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNonNuGet(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act && Assert
// Verify this is a noop and not a failure
var r = Util.RestoreSolution(pathContext);
}
}
[Fact]
public void RestoreNetCore_NETCore_ProjectToProject_VerifyProjectInTarget()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetB = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "b");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "b");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(".NETFramework,Version=v4.5", targetB.Framework);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("../b/b.csproj", libB.Path);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
}
}
[Fact]
public void RestoreNetCore_NETCore_ProjectToProject_VerifyPackageIdUsed()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// Add package ids
projectA.Properties.Add("PackageId", "x");
projectB.Properties.Add("PackageId", "y");
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetB = projectA.AssetsFile
.GetTarget(NuGetFramework.Parse("net45"), runtimeIdentifier: null)
.Libraries
.SingleOrDefault(e => e.Name == "y");
var libB = projectA.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "y");
Assert.Equal("1.0.0", targetB.Version.ToNormalizedString());
Assert.Equal("project", targetB.Type);
Assert.Equal(".NETFramework,Version=v4.5", targetB.Framework);
Assert.Equal("1.0.0", libB.Version.ToNormalizedString());
Assert.Equal("project", libB.Type);
Assert.Equal("y", libB.Name);
Assert.Equal("../b/b.csproj", libB.Path);
Assert.Equal("../b/b.csproj", libB.MSBuildProject);
// Verify project name is used
var group = projectA.AssetsFile.ProjectFileDependencyGroups.ToArray()[0];
Assert.Equal("y >= 1.0.0", group.Dependencies.Single());
}
}
[Fact]
public void RestoreNetCore_NETCore_ProjectToProject_IgnoreMissingProjectReference()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Delete B
File.Delete(projectB.ProjectPath);
// Act && Assert
// Missing projects are ignored during restore. These issues are reported at build time.
var r = Util.RestoreSolution(pathContext, expectedExitCode: 0);
}
}
[Fact]
public async Task RestoreNetCore_NETCore_ProjectToProject_VerifyTransitivePackageAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
// B -> X
projectB.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetX = projectA.AssetsFile.Targets.Single(target => string.IsNullOrEmpty(target.RuntimeIdentifier)).Libraries.SingleOrDefault(e => e.Name == "x");
Assert.Equal("1.0.0", targetX.Version.ToNormalizedString());
}
}
[Fact]
public async Task RestoreNetCore_NETCore_ProjectToProjectMultipleTFM_VerifyTransitivePackagesAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"),
NuGetFramework.Parse("netstandard1.6"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
NuGetFramework.Parse("netstandard1.3"));
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
// B -> X
projectB.Frameworks[0].PackageReferences.Add(packageX);
// B -> Y
projectB.Frameworks[1].PackageReferences.Add(packageY);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetNet = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("net46")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
var targetNS = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("netstandard1.6")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
Assert.Equal("x", targetNet.Libraries.Single(e => e.Type == "package").Name);
Assert.Equal("y", targetNS.Libraries.Single(e => e.Type == "package").Name);
}
}
[Fact]
public async Task RestoreNetCore_NETCoreAndUAP_ProjectToProjectMultipleTFM_VerifyTransitivePackagesAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"),
NuGetFramework.Parse("netstandard1.6"));
var projectJson = JObject.Parse(@"{
'dependencies': {
'x': '1.0.0'
},
'frameworks': {
'netstandard1.3': { }
}
}");
var projectB = SimpleTestProjectContext.CreateUAP(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("netstandard1.3"),
projectJson);
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
// B -> X
projectB.Frameworks[0].PackageReferences.Add(packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var targetNet = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("net46")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
var targetNS = projectA.AssetsFile.Targets.Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("netstandard1.6")) && string.IsNullOrEmpty(e.RuntimeIdentifier));
Assert.Equal("x", targetNet.Libraries.Single(e => e.Type == "package").Name);
Assert.Equal("x", targetNS.Libraries.Single(e => e.Type == "package").Name);
}
}
[Fact]
public async Task RestoreNetCore_LegacyPackagesDirectorySettingsIsIsolatedToProjectAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectA.Properties.Add("RestoreLegacyPackagesDirectory", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
projectC.Properties.Add("RestoreLegacyPackagesDirectory", "true");
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
// B -> C
projectB.AddProjectToAllFrameworks(projectC);
var packageX = new SimpleTestPackageContext()
{
Id = "PackageX",
Version = "1.0.0-BETA"
};
// C -> X
projectC.Frameworks[0].PackageReferences.Add(packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
var xLibraryInA = projectA.AssetsFile.Libraries.Single(x => x.Name == packageX.Id);
var xLibraryInB = projectB.AssetsFile.Libraries.Single(x => x.Name == packageX.Id);
var xLibraryInC = projectC.AssetsFile.Libraries.Single(x => x.Name == packageX.Id);
Assert.Equal("PackageX/1.0.0-BETA", xLibraryInA.Path);
Assert.Equal("packagex/1.0.0-beta", xLibraryInB.Path);
Assert.Equal("PackageX/1.0.0-BETA", xLibraryInC.Path);
}
}
[Fact]
public async Task RestoreNetCore_LegacyPackagesDirectoryEnabledInProjectFileAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "PackageX",
Version = "1.0.0-BETA"
};
packageX.AddFile("lib/net45/a.dll");
projectA.AddPackageToAllFrameworks(packageX);
projectA.Properties.Add("RestoreLegacyPackagesDirectory", "true");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var xLibrary = projectA.AssetsFile.Libraries.Single();
// Assert
Assert.Equal("PackageX/1.0.0-BETA", xLibrary.Path);
}
}
[Fact]
public async Task RestoreNetCore_LegacyPackagesDirectoryDisabledInProjectFileAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "PackageX",
Version = "1.0.0-BETA"
};
packageX.AddFile("lib/net45/a.dll");
projectA.AddPackageToAllFrameworks(packageX);
projectA.Properties.Add("RestoreLegacyPackagesDirectory", "false");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var xLibrary = projectA.AssetsFile.Libraries.Single();
// Assert
Assert.Equal("packagex/1.0.0-beta", xLibrary.Path);
}
}
[Fact]
public async Task RestoreNetCore_AssetTargetFallbackVerifyFallbackToNet46AssetsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("AssetTargetFallback", "net461");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net45/a.dll");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
var graph = projectA.AssetsFile.GetTarget(netcoreapp2, runtimeIdentifier: null);
var lib = graph.GetTargetLibrary("x");
// Assert
lib.CompileTimeAssemblies.Select(e => e.Path)
.ShouldBeEquivalentTo(new[] { "lib/net45/a.dll" },
"no compatible assets were found for ns2.0");
r.AllOutput.Should().Contain("This package may not be fully compatible with your project.");
}
}
[Fact]
public async Task RestoreNetCore_AssetTargetFallbackVerifyNoFallbackToNet46AssetsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("AssetTargetFallback", "net461");
projectA.Properties.Add("RuntimeIdentifiers", "win10");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net461/a.dll");
packageX.AddFile("ref/netstandard1.0/a.dll");
packageX.AddFile("ref/net461/a.dll");
packageX.AddFile("runtimes/win10/native/a.dll");
packageX.AddFile("runtimes/win10/lib/net461/a.dll");
packageX.AddFile("build/net461/x.targets");
packageX.AddFile("buildMultiTargeting/net461/x.targets");
packageX.AddFile("contentFiles/any/net461/a.txt");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
foreach (var graph in projectA.AssetsFile.Targets)
{
var lib = graph.GetTargetLibrary("x");
lib.CompileTimeAssemblies.Select(e => e.Path)
.ShouldBeEquivalentTo(new[] { "ref/netstandard1.0/a.dll" },
"ATF does not fallback to lib/net45 if other assets were found.");
lib.RuntimeAssemblies.Should().BeEmpty();
lib.BuildMultiTargeting.Should().BeEmpty();
lib.Build.Should().BeEmpty();
lib.ContentFiles.Should().BeEmpty();
lib.ResourceAssemblies.Should().BeEmpty();
// Native will contain a.dll for RID targets
}
}
}
[Fact]
public void RestoreNetCore_AssetTargetFallbackWithProjectReference_VerifyFallbackToNet46Assets()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var ne461 = NuGetFramework.Parse("net461");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("AssetTargetFallback", "net461");
projectA.Properties.Add("RuntimeIdentifiers", "win10");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
ne461);
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
foreach (var graph in projectA.AssetsFile.Targets)
{
var lib = graph.GetTargetLibrary("b");
lib.CompileTimeAssemblies.Select(e => e.Path)
.ShouldBeEquivalentTo(new[] { "bin/placeholder/b.dll" });
lib.RuntimeAssemblies.Select(e => e.Path)
.ShouldBeEquivalentTo(new[] { "bin/placeholder/b.dll" });
lib.BuildMultiTargeting.Should().BeEmpty();
lib.Build.Should().BeEmpty();
lib.ContentFiles.Should().BeEmpty();
lib.ResourceAssemblies.Should().BeEmpty();
// Native will contain a.dll for RID targets
}
}
}
[Fact]
public void RestoreNetCore_AssetTargetFallbackWithProjectReference_VerifyNoFallbackToNet46Assets()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var ne461 = NuGetFramework.Parse("net461");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("AssetTargetFallback", "net45");
projectA.Properties.Add("RuntimeIdentifiers", "win10");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
ne461);
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
// Assert
r.Success.Should().BeFalse();
r.AllOutput.Should().Contain("NU1201");
}
}
[Fact]
public async Task RestoreNetCore_BothAssetTargetFallbackPackageTargetFallbackVerifyErrorAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("AssetTargetFallback", "net461");
projectA.Properties.Add("PackageTargetFallback", "dnxcore50");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
// Assert
r.AllOutput.Should().Contain("PackageTargetFallback and AssetTargetFallback cannot be used together.");
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalSourcesAppliedAsync()
{
// Arrange
using (var extraSource = TestDirectory.Create())
using (var extraFallback = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreAdditionalProjectSources", extraSource.Path);
projectA.Properties.Add("RestoreAdditionalProjectFallbackFolders", extraFallback.Path);
var packageM = new SimpleTestPackageContext()
{
Id = "m",
Version = "1.0.0"
};
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageM);
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
projectA.AddPackageToAllFrameworks(packageZ);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// M is only in the fallback folder
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.FallbackFolder,
PackageSaveMode.Defaultv3,
packageM);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in the extra source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSource,
PackageSaveMode.Defaultv3,
packageY);
// Z is only in the extra fallback
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraFallback,
PackageSaveMode.Defaultv3,
packageZ);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "m", "x", "y", "z" });
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalSourcesConditionalOnFrameworkAsync()
{
// Arrange
using (var extraSourceA = TestDirectory.Create())
using (var extraSourceB = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp1 = NuGetFramework.Parse("netcoreapp1.0");
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp1,
netcoreapp2);
// Add conditional sources
projectA.Frameworks[0].Properties.Add("RestoreAdditionalProjectSources", extraSourceA.Path);
projectA.Frameworks[1].Properties.Add("RestoreAdditionalProjectSources", extraSourceB.Path);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceA,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in the extra source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceB,
PackageSaveMode.Defaultv3,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "x", "y" });
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalFallbackFolderConditionalOnFrameworkAsync()
{
// Arrange
using (var extraSourceA = TestDirectory.Create())
using (var extraSourceB = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp1 = NuGetFramework.Parse("netcoreapp1.0");
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp1,
netcoreapp2);
// Add conditional sources
projectA.Frameworks[0].Properties.Add("RestoreAdditionalProjectFallbackFolders", extraSourceA.Path);
projectA.Frameworks[1].Properties.Add("RestoreAdditionalProjectFallbackFolders", extraSourceB.Path);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceA,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in the extra source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceB,
PackageSaveMode.Defaultv3,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "x", "y" });
// Verify fallback folder added
projectA.AssetsFile.PackageFolders.Select(e => e.Path).Should().Contain(extraSourceA);
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalFallbackFolderExcludeAsync()
{
// Arrange
using (var extraSourceA = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp1 = NuGetFramework.Parse("netcoreapp1.0");
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp1,
netcoreapp2);
// Add and remove a fallback source, also add it as a source
projectA.Frameworks[0].Properties.Add("RestoreAdditionalProjectFallbackFolders", extraSourceA.Path);
projectA.Frameworks[1].Properties.Add("RestoreAdditionalProjectFallbackFoldersExcludes", extraSourceA.Path);
projectA.Frameworks[1].Properties.Add("RestoreAdditionalProjectSources", extraSourceA.Path);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceA,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in the extra source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSourceA,
PackageSaveMode.Defaultv3,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "x", "y" });
// Verify the fallback folder was not added
projectA.AssetsFile.PackageFolders.Select(e => e.Path).Should().NotContain(extraSourceA);
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalSourcesAppliedWithSingleFrameworkAsync()
{
// Arrange
using (var extraSource = TestDirectory.Create())
using (var extraFallback = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp1.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreAdditionalProjectSources", extraSource.Path);
projectA.Properties.Add("RestoreAdditionalProjectFallbackFoldersExcludes", extraFallback.Path);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSource.Path,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "x" });
// Verify the fallback folder was not added
projectA.AssetsFile.PackageFolders.Select(e => e.Path).Should().NotContain(extraFallback.Path);
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalFallbackFolderAppliedWithSingleFrameworkAsync()
{
// Arrange
using (var extraSource = TestDirectory.Create())
using (var extraFallback = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreAdditionalProjectFallbackFolders", extraFallback.Path);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraFallback.Path,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
projectA.AssetsFile.Libraries.Select(e => e.Name).OrderBy(e => e).ShouldBeEquivalentTo(new[] { "x" });
// Verify the fallback folder was added
projectA.AssetsFile.PackageFolders.Select(e => e.Path).Should().Contain(extraFallback.Path);
}
}
[Fact]
public async Task RestoreNetCore_VerifyPackagesFolderPathResolvedAgainstWorkingDirAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestorePackagesPath", "invalid");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var expectedFolder = Path.Combine(pathContext.WorkingDirectory, "pkgs");
var unexpectedFolder = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "invalid");
// Act
var r = Util.RestoreSolution(pathContext, 0, "-PackagesDirectory", "pkgs");
// Assert
Directory.GetDirectories(expectedFolder).Should().NotBeEmpty();
Directory.Exists(unexpectedFolder).Should().BeFalse();
Directory.GetDirectories(pathContext.UserPackagesFolder).Should().BeEmpty();
}
}
[Fact]
public async Task RestoreNetCore_VerifyAdditionalSourcesAppliedToToolsAsync()
{
// Arrange
using (var extraSource = TestDirectory.Create())
using (var extraFallback = TestDirectory.Create())
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreAdditionalProjectSources", extraSource.Path);
projectA.Properties.Add("RestoreAdditionalProjectFallbackFolders", extraFallback.Path);
var packageM = new SimpleTestPackageContext()
{
Id = "m",
Version = "1.0.0",
PackageType = PackageType.DotnetCliTool
};
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0",
PackageType = PackageType.DotnetCliTool
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0",
PackageType = PackageType.DotnetCliTool
};
var packageZ = new SimpleTestPackageContext()
{
Id = "z",
Version = "1.0.0",
PackageType = PackageType.DotnetCliTool
};
projectA.DotnetCLIToolReferences.Add(packageM);
projectA.DotnetCLIToolReferences.Add(packageX);
projectA.DotnetCLIToolReferences.Add(packageY);
projectA.DotnetCLIToolReferences.Add(packageZ);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// M is only in the fallback folder
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.FallbackFolder,
PackageSaveMode.Defaultv3,
packageM);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in the extra source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraSource,
PackageSaveMode.Defaultv3,
packageY);
// Z is only in the extra fallback
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
extraFallback,
PackageSaveMode.Defaultv3,
packageZ);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Directory.Exists(new ToolPathResolver(pathContext.UserPackagesFolder).GetToolDirectoryPath(packageM.Id, NuGetVersion.Parse(packageM.Version), netcoreapp2));
Directory.Exists(new ToolPathResolver(pathContext.UserPackagesFolder).GetToolDirectoryPath(packageX.Id, NuGetVersion.Parse(packageX.Version), netcoreapp2));
Directory.Exists(new ToolPathResolver(pathContext.UserPackagesFolder).GetToolDirectoryPath(packageY.Id, NuGetVersion.Parse(packageY.Version), netcoreapp2));
Directory.Exists(new ToolPathResolver(pathContext.UserPackagesFolder).GetToolDirectoryPath(packageZ.Id, NuGetVersion.Parse(packageZ.Version), netcoreapp2));
}
}
[Fact]
public async Task RestoreNetCore_VerifyPackagesFolderPathResolvedAgainstProjectPropertyAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestorePackagesPath", "valid");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var expectedFolder = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "valid");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Directory.GetDirectories(expectedFolder).Should().NotBeEmpty();
Directory.GetDirectories(pathContext.UserPackagesFolder).Should().BeEmpty();
}
}
// The scenario here is 2 different projects are setting RestoreSources, and the caching of the sources takes this into consideration
[Fact]
public async Task RestoreNetCore_VerifySourcesResolvedCorrectlyForMultipleProjectsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
var source1 = Path.Combine(pathContext.SolutionRoot, "source1");
var source2 = Path.Combine(pathContext.SolutionRoot, "source2");
// X is only in source1
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
source1,
PackageSaveMode.Defaultv3,
packageX);
// Y is only in source2
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
source2,
PackageSaveMode.Defaultv3,
packageY);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreSources", source1);
projectB.Properties.Add("RestoreSources", source2);
projectA.AddPackageToAllFrameworks(packageX);
projectB.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectB);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_VerifySourcesResolvedAgainstProjectPropertyAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreSources", "sub");
var source = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "sub");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
source,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_VerifySourcesResolvedAgainstWorkingDirAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreSources", "invalid");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var relativeSourceName = "valid";
var source = Path.Combine(pathContext.WorkingDirectory, relativeSourceName);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
source,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext, 0, "-Source", relativeSourceName);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_VerifyFallbackFoldersResolvedAgainstProjectPropertyAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("RestoreFallbackFolders", "sub");
var fallback = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "sub");
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// X is only in the source
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
fallback,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Directory.GetDirectories(pathContext.UserPackagesFolder).Should().BeEmpty();
}
}
[Fact]
public async Task RestoreNetCore_VerifyDisabledSourcesAreNotUsedAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// create a config file, no disabled sources
var projectDir = Path.GetDirectoryName(projectA.ProjectPath);
var configPath = Path.Combine(pathContext.SolutionRoot, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
packageSources.Add(new XElement(XName.Get("clear")));
var localSource = new XElement(XName.Get("add"));
localSource.Add(new XAttribute(XName.Get("key"), "localSource"));
localSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource));
packageSources.Add(localSource);
var brokenSource = new XElement(XName.Get("add"));
brokenSource.Add(new XAttribute(XName.Get("key"), "brokenLocalSource"));
brokenSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource + "brokenLocalSource"));
packageSources.Add(brokenSource);
// Disable that config
var disabledPackageSources = new XElement(XName.Get("disabledPackageSources"));
var disabledBrokenSource = new XElement(XName.Get("add"));
disabledBrokenSource.Add(new XAttribute(XName.Get("key"), "brokenLocalSource"));
disabledBrokenSource.Add(new XAttribute(XName.Get("value"), "true"));
disabledPackageSources.Add(disabledBrokenSource);
configuration.Add(disabledPackageSources);
File.WriteAllText(configPath, doc.ToString());
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
r2.Success.Should().BeTrue();
r2.AllOutput.Should().NotContain("brokenLocalSource");
}
}
[Fact]
public async Task RestoreNetCore_VerifyOrderOfConfigsAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// create a config file, no disabled sources
var projectDir = Path.GetDirectoryName(projectA.ProjectPath);
var configPath = Path.Combine(pathContext.SolutionRoot, "NuGet.Config");
var doc = new XDocument();
var configuration = new XElement(XName.Get("configuration"));
doc.Add(configuration);
var packageSources = new XElement(XName.Get("packageSources"));
configuration.Add(packageSources);
packageSources.Add(new XElement(XName.Get("clear")));
var localSource = new XElement(XName.Get("add"));
localSource.Add(new XAttribute(XName.Get("key"), "localSource"));
localSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource));
packageSources.Add(localSource);
File.WriteAllText(configPath, doc.ToString());
var solutionParent = Directory.GetParent(pathContext.SolutionRoot);
var configPath2 = Path.Combine(solutionParent.FullName, "NuGet.Config");
var doc2 = new XDocument();
var configuration2 = new XElement(XName.Get("configuration"));
doc2.Add(configuration2);
var packageSources2 = new XElement(XName.Get("packageSources"));
configuration2.Add(packageSources2);
packageSources2.Add(new XElement(XName.Get("clear")));
var brokenSource = new XElement(XName.Get("add"));
brokenSource.Add(new XAttribute(XName.Get("key"), "brokenLocalSource"));
brokenSource.Add(new XAttribute(XName.Get("value"), pathContext.PackageSource + "brokenLocalSource"));
packageSources2.Add(brokenSource);
// Disable that config
var disabledPackageSources = new XElement(XName.Get("disabledPackageSources"));
var disabledBrokenSource = new XElement(XName.Get("add"));
disabledBrokenSource.Add(new XAttribute(XName.Get("key"), "brokenLocalSource"));
disabledBrokenSource.Add(new XAttribute(XName.Get("value"), "true"));
disabledPackageSources.Add(disabledBrokenSource);
configuration2.Add(disabledPackageSources);
File.WriteAllText(configPath2, doc2.ToString());
// Act
var r2 = Util.RestoreSolution(pathContext);
// Assert
r2.Success.Should().BeTrue();
// Configs closer to the user should be first
Regex.Replace(r2.AllOutput, @"\s", "").Should().Contain($"NuGetConfigfilesused:{configPath}{configPath2}");
}
}
[Fact]
public async Task RestoreNetCore_VerifyConfigFileWithRelativePathIsUsedAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var xml = File.ReadAllText(projectA.ProjectPath);
xml = xml.Replace("<TargetFrameworks>", "<TargetFramework>");
xml = xml.Replace("</TargetFrameworks>", "</TargetFramework>");
File.WriteAllText(projectA.ProjectPath, xml);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var subDir = Path.Combine(pathContext.SolutionRoot, "sub");
var configPath = Path.Combine(subDir, "nuget.config");
Directory.CreateDirectory(subDir);
File.Move(pathContext.NuGetConfig, configPath);
var relativePathToConfig = PathUtility.GetRelativePath(pathContext.WorkingDirectory + Path.DirectorySeparatorChar, configPath);
// Act
var r = Util.RestoreSolution(pathContext, 0, $"-ConfigFile {relativePathToConfig}");
// Assert
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.Item2);
Assert.True(File.Exists(projectA.TargetsOutput), r.Item2);
Assert.True(File.Exists(projectA.PropsOutput), r.Item2);
Assert.Equal(NuGetFramework.Parse("net45"), projectA.AssetsFile.Targets.Single(e => string.IsNullOrEmpty(e.RuntimeIdentifier)).TargetFramework);
}
}
[Fact]
public async Task RestoreNetCore_WithMultipleProjectToProjectReferences_NoOpsAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var parentProject = SimpleTestProjectContext.CreateNETCore(
"parent",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var one = SimpleTestProjectContext.CreateNETCore(
"child1",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var two = SimpleTestProjectContext.CreateNETCore(
"child2",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var three = SimpleTestProjectContext.CreateNETCore(
"child3",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX
);
var rnd = new Random();
var projects = new SimpleTestProjectContext[] { one, two, three }.OrderBy(item => rnd.Next());
// Parent -> children. Very important that these are added in a random order
foreach (var project in projects)
{
parentProject.AddProjectToAllFrameworks(project);
}
solution.Projects.Add(one);
solution.Projects.Add(two);
solution.Projects.Add(three);
solution.Projects.Add(parentProject);
solution.Create(pathContext.SolutionRoot);
// Act && Assert
var r = Util.RestoreSolution(pathContext, expectedExitCode: 0);
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
// Do it again, it should no-op now.
// Act && Assert
var r2 = Util.RestoreSolution(pathContext, expectedExitCode: 0);
Assert.Equal(0, r2.Item1);
Assert.DoesNotContain("Writing cache file", r2.Item2);
Assert.Contains("The restore inputs for 'parent' have not changed. No further actions are required to complete the restore.", r2.Item2);
}
}
[Fact]
public async Task RestoreNetCore_PackageTypesDoNotAffectAssetsFileAsync()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var project = SimpleTestProjectContext.CreateNETCore(
"project",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.PackageTypes.Add(PackageType.Dependency);
packageX.PackageTypes.Add(PackageType.DotnetCliTool);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
// Act && Assert
var r = Util.RestoreSolution(pathContext, expectedExitCode: 0);
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
Assert.Contains("Writing assets file to disk", r.Item2);
// Pre-condition, Assert deleting the correct file
Assert.True(File.Exists(project.CacheFileOutputPath));
File.Delete(project.CacheFileOutputPath);
r = Util.RestoreSolution(pathContext, expectedExitCode: 0);
Assert.Equal(0, r.Item1);
Assert.Contains("Writing cache file", r.Item2);
Assert.DoesNotContain("Writing assets file to disk", r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_LongPathInPackage()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.AddFile(@"content/2.5.6/core/store/x64/netcoreapp2.0/microsoft.extensions.configuration.environmentvariables/2.0.0/lib/netstandard2.0/Microsoft.Extensions.Configuration.EnvironmentVariables.dll ");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_NoOp_MultipleProjectsInSameDirectoryDoNotNoOp()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
var secondaryProjectName = Path.Combine(Path.GetDirectoryName(project.ProjectPath), "proj-copy.csproj");
File.Copy(project.ProjectPath, secondaryProjectName);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Prerequisites
var r1 = Util.Restore(pathContext, project.ProjectPath);
Assert.Equal(0, r1.Item1);
Assert.Contains("Writing cache file", r1.Item2);
Assert.Contains("Writing assets file to disk", r1.Item2);
var r2 = Util.Restore(pathContext, secondaryProjectName);
Assert.Contains("Writing cache file", r2.Item2);
Assert.Equal(0, r2.Item1);
Assert.Contains("Writing assets file to disk", r2.Item2);
// Act
var result = Util.Restore(pathContext, project.ProjectPath);
// Assert
Assert.Equal(0, result.Item1);
Assert.Contains("Writing cache file", result.Item2);
Assert.Contains("Writing assets file to disk", result.Item2);
}
}
[Fact]
public async Task RestoreNetCore_InteropTypePackage()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net461"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net461/a.dll");
packageX.AddFile("embed/net461/a.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.NotNull(projectA.AssetsFile);
foreach (var target in projectA.AssetsFile.Targets)
{
var library = target.Libraries.FirstOrDefault(lib => lib.Name.Equals("x"));
Assert.NotNull(library);
Assert.True(library.EmbedAssemblies.Any(embed => embed.Path.Equals("embed/net461/a.dll")));
Assert.True(library.CompileTimeAssemblies.Any(embed => embed.Path.Equals("lib/net461/a.dll")));
Assert.True(library.RuntimeAssemblies.Any(embed => embed.Path.Equals("lib/net461/a.dll")));
}
}
}
[Fact]
public async Task RestoreNetCore_MultiTFM_ProjectToProject_PackagesLockFile()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"),
NuGetFramework.Parse("net45"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"),
NuGetFramework.Parse("net46"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
// A -> B
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.AddProjectToAllFrameworks(projectB);
// B
projectB.AddPackageToFramework("net45", packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Second Restore
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public void RestoreNetCore_PackagesLockFile_LowercaseProjectNameSolutionRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution and projects
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"ProjectA",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"ProjectB",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
var target = lockFile.Targets.Single(t => t.RuntimeIdentifier == null);
var projectReference = target.Dependencies.SingleOrDefault(d => d.Type == PackageDependencyType.Project);
StringComparer.Ordinal.Equals(projectReference.Id, projectB.ProjectName.ToLowerInvariant()).Should().BeTrue();
}
}
[Fact]
public void RestoreNetCore_PackagesLockFile_LowercaseProjectNameProjectRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution abd projects
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"ProjectA",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
var projectB = SimpleTestProjectContext.CreateNETCore(
"ProjectB",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
// A -> B
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.Restore(pathContext, projectA.ProjectPath);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
var net46 = NuGetFramework.Parse("net46");
var target = lockFile.Targets.First(t => t.TargetFramework == net46);
var projectReference = target.Dependencies.SingleOrDefault(d => d.Type == PackageDependencyType.Project);
StringComparer.Ordinal.Equals(projectReference.Id, projectB.ProjectName.ToLowerInvariant()).Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_BuildTransitive()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net461"));
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY.Files.Clear();
packageY.AddFile("lib/net461/y.dll");
packageY.AddFile("build/y.targets");
packageY.AddFile("buildCrossTargeting/y.targets");
packageY.AddFile("buildTransitive/y.targets");
packageY.Exclude = "build;analyzer";
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net461/x.dll");
packageX.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
var assetsFile = projectA.AssetsFile;
Assert.NotNull(assetsFile);
foreach (var target in assetsFile.Targets)
{
var library = target.Libraries.FirstOrDefault(lib => lib.Name.Equals("y"));
Assert.NotNull(library);
Assert.True(library.Build.Any(build => build.Path.Equals("buildTransitive/y.targets")));
}
}
}
[Fact]
public async Task RestoreNetCore_SkipBuildTransitive()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net461"));
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY.Files.Clear();
packageY.AddFile("lib/net461/y.dll");
packageY.AddFile("build/y.targets");
packageY.AddFile("buildCrossTargeting/y.targets");
packageY.AddFile("buildTransitive/y.targets");
packageY.Exclude = "buildTransitive";
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net461/x.dll");
packageX.Dependencies.Add(packageY);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX,
packageY);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
var assetsFile = projectA.AssetsFile;
Assert.NotNull(assetsFile);
foreach (var target in assetsFile.Targets)
{
var library = target.Libraries.FirstOrDefault(lib => lib.Name.Equals("y"));
Assert.NotNull(library);
Assert.False(library.Build.Any(build => build.Path.Equals("buildTransitive/y.targets")));
}
}
}
[Fact]
public async Task RestoreNetCore_NoOp_DgSpecJsonIsNotOverridenDuringNoOp()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Prerequisites
var result = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
Assert.Equal(0, result.Item1);
Assert.Contains("Writing cache file", result.Item2);
Assert.Contains("Writing assets file to disk", result.Item2);
Assert.Contains("Persisting dg", result.Item2);
var dgSpecFileName = Path.Combine(Path.GetDirectoryName(project.AssetsFileOutputPath), $"{Path.GetFileName(project.ProjectPath)}.nuget.dgspec.json");
var fileInfo = new FileInfo(dgSpecFileName);
Assert.True(fileInfo.Exists);
var lastWriteTime = fileInfo.LastWriteTime;
// Act
result = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.Equal(0, result.Item1);
Assert.DoesNotContain("Writing cache file", result.Item2);
Assert.DoesNotContain("Writing assets file to disk", result.Item2);
Assert.DoesNotContain("Persisting dg", result.Item2);
fileInfo = new FileInfo(dgSpecFileName);
Assert.True(fileInfo.Exists);
Assert.Equal(lastWriteTime, fileInfo.LastWriteTime);
}
}
[Fact]
public async Task RestoreNetCore_NoOp_EnableRestorePackagesWithLockFile_BySetProperty_ThenDeletePackageLockFile()
{
// Related issue: https://github.com/NuGet/Home/issues/7807
// First senario : Enable RestorePackagesWithLockFile by only setting property.
// First restore should fail the No-op, generate the package lock file. After deleting the package lock file, run the second restore.
// The second restore should fail the No-op, and generate the package lock file.
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.Properties.Add("RestorePackagesWithLockFile", "true");
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var packageLockFileName = project.NuGetLockFileOutputPath;
var noOpFailedMsg = "The lock file for " + project.ProjectName + " at location " + packageLockFileName + " does not exist, no-op is not possible. Continuing restore.";
// Act
var result1 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.Equal(0, result1.Item1);
Assert.Contains("Writing packages lock file at disk.", result1.Item2);
Assert.True(File.Exists(packageLockFileName));
// Act
File.Delete(packageLockFileName);
Assert.False(File.Exists(packageLockFileName));
var result2 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
//Assert
Assert.Equal(0, result2.Item1);
Assert.Contains(noOpFailedMsg, result2.Item2);
Assert.Contains("Writing packages lock file at disk.", result2.Item2);
Assert.True(File.Exists(packageLockFileName));
}
}
[Fact]
public async Task RestoreNetCore_NoOp_EnableRestorePackagesWithLockFile_BySetProperty_ThenNotDeletePackageLockFile()
{
// Related issue: https://github.com/NuGet/Home/issues/7807
// Contrast test to the first senario : do not delete package lock file at the end of the first restore.
// First restore should fail the No-op, generate the package lock file. DO NOT delete the package lock file, run the second restore.
// The second restore should No-op, and won't generate the package lock file.
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.Properties.Add("RestorePackagesWithLockFile", "true");
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var packageLockFileName = project.NuGetLockFileOutputPath;
var noOpFailedMsg = "The lock file for " + project.ProjectName + " at location " + packageLockFileName + " does not exist, no-op is not possible. Continuing restore.";
var noOpSucceedMsg = "No-Op restore. The cache will not be updated.";
// Act
var result1 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.Equal(0, result1.Item1);
Assert.Contains("Writing packages lock file at disk.", result1.Item2);
Assert.True(File.Exists(packageLockFileName));
// Act
var result2 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
//Assert
Assert.Equal(0, result2.Item1);
Assert.Contains(noOpSucceedMsg, result2.Item2);
Assert.DoesNotContain("Writing packages lock file at disk.", result2.Item2);
Assert.True(File.Exists(packageLockFileName));
}
}
[Fact]
public async Task RestoreNetCore_NoOp_EnableRestorePackagesWithLockFile_ByAddLockFile_ThenDeletePackageLockFile()
{
// Related issue: https://github.com/NuGet/Home/issues/7807
// Second senario : Enable RestorePackagesWithLockFile by only adding a lock file.
// First restore should fail the No-op, regenerate the package lock file. After deleting the package lock file, run the second restore.
// The second restore: since there is no property set and no lock file exists, no lockfile will be generated. And no-op succeed.
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var packageLockFileName = project.NuGetLockFileOutputPath;
Assert.False(File.Exists(packageLockFileName));
File.Create(packageLockFileName).Close();
Assert.True(File.Exists(packageLockFileName));
var noOpFailedMsg = "The lock file for " + project.ProjectName + " at location " + packageLockFileName + " does not exist, no-op is not possible. Continuing restore.";
var noOpSucceedMsg = "No-Op restore. The cache will not be updated.";
// Act
var result1 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.Equal(0, result1.Item1);
Assert.Contains("Writing packages lock file at disk.", result1.Item2);
Assert.True(File.Exists(packageLockFileName));
// Act
File.Delete(packageLockFileName);
Assert.False(File.Exists(packageLockFileName));
var result2 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
//Assert
Assert.Equal(0, result2.Item1);
Assert.Contains(noOpSucceedMsg, result2.Item2);
Assert.DoesNotContain("Writing packages lock file at disk.", result2.Item2);
Assert.False(File.Exists(packageLockFileName));
}
}
[Fact]
public async Task RestoreNetCore_NoOp_EnableRestorePackagesWithLockFile_ByAddLockFile_ThenNotDeletePackageLockFile()
{
// Related issue: https://github.com/NuGet/Home/issues/7807
// Contrast test to the second senario : do not delete package lock file at the end of the first restore.
// First restore should fail the No-op, regenerate the package lock file. DO NOT delete the package lock file, run the second restore.
// The second restore: No-op should succeed, lock file will not be regenerated.
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
var packageLockFileName = project.NuGetLockFileOutputPath;
Assert.False(File.Exists(packageLockFileName));
File.Create(packageLockFileName).Close();
Assert.True(File.Exists(packageLockFileName));
var noOpFailedMsg = "The lock file for " + project.ProjectName + " at location " + packageLockFileName + " does not exist, no-op is not possible. Continuing restore.";
var noOpSucceedMsg = "No-Op restore. The cache will not be updated.";
// Act
var result1 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.Equal(0, result1.Item1);
Assert.Contains("Writing packages lock file at disk.", result1.Item2);
Assert.True(File.Exists(packageLockFileName));
// Act
var result2 = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
//Assert
Assert.Equal(0, result2.Item1);
Assert.Contains(noOpSucceedMsg, result2.Item2);
Assert.DoesNotContain("Writing packages lock file at disk.", result2.Item2);
Assert.True(File.Exists(packageLockFileName));
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_SimplePackageDownload()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageDownloadToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version)), $"{packageX.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_InstallFirstPackageDownload()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX1 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX2 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX1,
packageX2);
projectA.AddPackageDownloadToAllFrameworks(packageX1);
projectA.AddPackageDownloadToAllFrameworks(packageX2);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks[0].DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks[0].DownloadDependencies[0].Name);
Assert.Equal($"[{packageX1.Version}, {packageX1.Version}]", lockFile.PackageSpec.TargetFrameworks[0].DownloadDependencies[0].VersionRange.ToNormalizedString());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX1.Identity.Id, packageX1.Version)), $"{packageX1.ToString()} is not installed");
Assert.False(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX2.Identity.Id, packageX2.Version)), $"{packageX2.ToString()} should not be installed");
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_SameIdMultipleVersions_MultiPackageDownload()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX1 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX2 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX1,
packageX2);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var xml = projectA.GetXML();
var props = new Dictionary<string, string>();
var attributes = new Dictionary<string, string>();
attributes.Add("Version", "[1.0.0];[2.0.0]");
ProjectFileUtils.AddItem(
xml,
"PackageDownload",
packageX1.Id,
NuGetFramework.AnyFramework,
props,
attributes);
xml.Save(projectA.ProjectPath);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(2, lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
Assert.Equal($"[{packageX1.Version}, {packageX1.Version}]", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().VersionRange.ToNormalizedString());
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.Last().Name);
Assert.Equal($"[{packageX2.Version}, {packageX2.Version}]", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.Last().VersionRange.ToNormalizedString());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX1.Identity.Id, packageX1.Version)), $"{packageX1.ToString()} is not installed");
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX2.Identity.Id, packageX2.Version)), $"{packageX2.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_MultiTfm_PackageDownloadAndPackageReference()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net45;net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX1 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX2 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX1,
packageX2);
projectA.AddPackageToFramework("net45", packageX1);
projectA.AddPackageDownloadToFramework("net46", packageX2);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(1, lockFile.Libraries.Count);
Assert.Equal(2, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.First().Dependencies.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
Assert.Equal($"[{packageX2.Version}, {packageX2.Version}]",
lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().VersionRange.ToNormalizedString());
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.First().Dependencies.Last().Name);
Assert.Equal($"[{packageX1.Version}, )",
lockFile.PackageSpec.TargetFrameworks.First().Dependencies.First().LibraryRange.VersionRange.ToNormalizedString());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX1.Identity.Id, packageX1.Version)),
$"{packageX1.ToString()} is not installed");
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX2.Identity.Id, packageX2.Version)),
$"{packageX2.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_MultiTfm_MultiPackageDownload()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net45;net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX1 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX2 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX1,
packageX2);
projectA.AddPackageDownloadToFramework("net45", packageX1);
projectA.AddPackageDownloadToFramework("net46", packageX2);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(2, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(0, lockFile.PackageSpec.TargetFrameworks.First().Dependencies.Count);
Assert.Equal(0, lockFile.PackageSpec.TargetFrameworks.Last().Dependencies.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
Assert.Equal($"[{packageX2.Version}, {packageX2.Version}]",
lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().VersionRange.ToNormalizedString());
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Last().Name);
Assert.Equal($"[{packageX1.Version}, {packageX1.Version}]",
lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.First().VersionRange.ToNormalizedString());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX1.Identity.Id, packageX1.Version)),
$"{packageX1.ToString()} is not installed");
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX2.Identity.Id, packageX2.Version)),
$"{packageX2.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_PackageDownload_NonExactVersion_Fails()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX1 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX1);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
var xml = projectA.GetXML();
var props = new Dictionary<string, string>();
var attributes = new Dictionary<string, string>();
attributes.Add("Version", "1.0.0");
ProjectFileUtils.AddItem(
xml,
"PackageDownload",
packageX1.Id,
NuGetFramework.AnyFramework,
props,
attributes);
xml.Save(projectA.ProjectPath);
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
// Assert
Assert.False(r.Success, r.AllOutput);
Assert.False(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
}
}
[Fact]
public async Task RestoreNetCore_PackageDownload_NoOpAccountsForMissingPackages()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageDownloadToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
var r = Util.RestoreSolution(pathContext);
// Preconditions
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
var packagePath = Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version);
Assert.True(Directory.Exists(packagePath), $"{packageX.ToString()} is not installed");
Directory.Delete(packagePath, true);
Assert.False(Directory.Exists(packagePath), $"{packageX.ToString()} should not be installed anymore.");
// Act
r = Util.RestoreSolution(pathContext);
Assert.True(r.Success, r.AllOutput);
Assert.True(Directory.Exists(packagePath), $"{packageX.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_PackageDownload_DoesNotAFfectNoOp()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageDownloadToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
var r = Util.RestoreSolution(pathContext);
// Preconditions
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.First().DownloadDependencies.Count);
Assert.Equal("x", lockFile.PackageSpec.TargetFrameworks.Last().DownloadDependencies.First().Name);
var packagePath = Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version);
Assert.True(Directory.Exists(packagePath), $"{packageX.ToString()} is not installed");
Assert.Contains("Writing cache file", r.Item2);
// Act
r = Util.RestoreSolution(pathContext);
Assert.True(r.Success, r.AllOutput);
Assert.True(Directory.Exists(packagePath), $"{packageX.ToString()} is not installed");
Assert.Equal(0, r.Item1);
Assert.DoesNotContain("Writing cache file", r.Item2);
Assert.Contains("No further actions are required to complete", r.Item2);
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_FrameworkReferenceFromPackage()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.FrameworkReferences.Add(NuGetFramework.Parse("net45"), new string[] { "FrameworkRef" });
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(1, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.Targets.First().Libraries.Count);
Assert.Equal(1, lockFile.Targets.First().Libraries.Single().FrameworkReferences.Count);
Assert.Equal("FrameworkRef", lockFile.Targets.First().Libraries.Single().FrameworkReferences.Single());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version)), $"{packageX.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_FrameworkReference_TransitivePackageToPackage()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.FrameworkReferences.Add(NuGetFramework.Parse("net45"), new string[] { "FrameworkRef" });
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY.Files.Clear();
packageY.UseDefaultRuntimeAssemblies = false;
packageY.AddFile("lib/net45/y.dll");
packageY.FrameworkReferences.Add(NuGetFramework.Parse("net45"), new string[] { "FrameworkRefY" });
packageX.Dependencies.Add(packageY);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX,
packageY);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(2, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(2, lockFile.Targets.First().Libraries.Count);
Assert.Equal("FrameworkRef", lockFile.Targets.First().Libraries.First().FrameworkReferences.Single());
Assert.Equal("FrameworkRefY", lockFile.Targets.First().Libraries.Last().FrameworkReferences.Single());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version)), $"{packageX.ToString()} is not installed");
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_FrameworkReference_TransitiveProjectToProject()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.FrameworkReferences.Add(NuGetFramework.Parse("net45"), new string[] { "FrameworkRef" });
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
var projectB = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "b",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
var xml = projectB.GetXML();
var props = new Dictionary<string, string>();
var attributes = new Dictionary<string, string>();
ProjectFileUtils.AddItem(
xml,
"FrameworkReference",
"FrameworkRefY",
NuGetFramework.AnyFramework,
props,
attributes);
xml.Save(projectB.ProjectPath);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(2, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(2, lockFile.Targets.First().Libraries.Count);
Assert.Equal("FrameworkRef", lockFile.Targets.First().Libraries.First().FrameworkReferences.Single());
Assert.Equal("FrameworkRefY", lockFile.Targets.First().Libraries.Last().FrameworkReferences.Single());
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version)), $"{packageX.ToString()} is not installed");
// Assert 2
Assert.True(File.Exists(projectB.AssetsFileOutputPath), r.AllOutput);
lockFile = LockFileUtilities.GetLockFile(projectB.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(0, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(0, lockFile.Targets.First().Libraries.Count);
Assert.Equal("FrameworkRefY", lockFile.PackageSpec.TargetFrameworks.Single().FrameworkReferences.Single().Name);
Assert.Equal("none", FrameworkDependencyFlagsUtils.GetFlagString(lockFile.PackageSpec.TargetFrameworks.Single().FrameworkReferences.Single().PrivateAssets));
}
}
[Fact]
public async Task RestoreNetCore_SingleTFM_FrameworkReference_TransitiveProjectToProject_PrivateAssets_SuppressesReference()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectFrameworks = "net46";
var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "a",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.FrameworkReferences.Add(NuGetFramework.Parse("net45"), new string[] { "FrameworkRef" });
packageX.Files.Clear();
packageX.AddFile("lib/net45/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
var projectB = SimpleTestProjectContext.CreateNETCoreWithSDK(
projectName: "b",
solutionRoot: pathContext.SolutionRoot,
frameworks: MSBuildStringUtility.Split(projectFrameworks));
projectB.AddProjectToAllFrameworks(projectA);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
var xml = projectA.GetXML();
var props = new Dictionary<string, string>();
var attributes = new Dictionary<string, string>();
ProjectFileUtils.AddItem(
xml,
"FrameworkReference",
"FrameworkRefY",
NuGetFramework.AnyFramework,
props,
attributes);
attributes.Add("PrivateAssets", "all");
ProjectFileUtils.AddItem(
xml,
"FrameworkReference",
"FrameworkRefSupressed",
NuGetFramework.AnyFramework,
props,
attributes);
xml.Save(projectA.ProjectPath);
Util.CreateTempGlobalJson(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
Assert.True(r.Success, r.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath), r.AllOutput);
var lockFile = LockFileUtilities.GetLockFile(projectA.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(1, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(1, lockFile.Targets.First().Libraries.Count);
Assert.Equal("FrameworkRef", string.Join(",", lockFile.Targets.First().Libraries.First().FrameworkReferences));
Assert.True(Directory.Exists(Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id, packageX.Version)), $"{packageX.ToString()} is not installed");
Assert.Equal("all", FrameworkDependencyFlagsUtils.GetFlagString(lockFile.PackageSpec.TargetFrameworks.Single().FrameworkReferences.First().PrivateAssets));
Assert.Equal("none", FrameworkDependencyFlagsUtils.GetFlagString(lockFile.PackageSpec.TargetFrameworks.Single().FrameworkReferences.Last().PrivateAssets));
// Assert 2
Assert.True(File.Exists(projectB.AssetsFileOutputPath), r.AllOutput);
lockFile = LockFileUtilities.GetLockFile(projectB.AssetsFileOutputPath, Common.NullLogger.Instance);
Assert.Equal(2, lockFile.Libraries.Count);
Assert.Equal(1, lockFile.PackageSpec.TargetFrameworks.Count);
Assert.Equal(2, lockFile.Targets.First().Libraries.Count);
Assert.Equal("FrameworkRef", string.Join(",", lockFile.Targets.First().Libraries.First().FrameworkReferences));
Assert.Equal("FrameworkRefY", string.Join(",", lockFile.Targets.First().Libraries.Last().FrameworkReferences));
}
}
[Fact]
public async Task RestoreNetCore_MovedProject_DoesNotOverwriteMSBuildPropsTargets()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCore(
$"proj",
pathContext.SolutionRoot,
NuGetFramework.Parse("net45"));
project.SetMSBuildProjectExtensionsPath = false;
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Prerequisites
var result = Util.Restore(pathContext, project.ProjectPath, additionalArgs: "-verbosity Detailed");
Assert.True(result.Success);
Assert.Contains("Writing cache file", result.AllOutput);
Assert.Contains("Writing assets file to disk", result.AllOutput);
// Move the project
var movedProjectFolder = Path.Combine(pathContext.SolutionRoot, "newProjectDir");
Directory.Move(Path.GetDirectoryName(project.ProjectPath), movedProjectFolder);
var movedProjectPath = Path.Combine(movedProjectFolder, Path.GetFileName(project.ProjectPath));
// Act
result = Util.Restore(pathContext, movedProjectPath, additionalArgs: "-verbosity Detailed");
// Assert
Assert.True(result.Success);
Assert.Contains("Writing cache file", result.AllOutput);
Assert.Contains("Writing assets file to disk", result.AllOutput);
Assert.DoesNotContain("Generating MSBuild file", result.AllOutput);
}
}
[Fact]
public async Task RestoreNetCore_IncompatiblePackageTypesFailRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var project = SimpleTestProjectContext.CreateNETCore(
"project",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.PackageTypes.Add(PackageType.DotnetPlatform);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
// Act & Assert
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
Assert.Contains(NuGetLogCode.NU1213.GetName(), r.AllOutput);
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_PackageRemove_UpdatesLockFile()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project File name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 1);
Assert.Equal(lockFile.Targets.First().Dependencies.First().Id, "x");
// Setup - remove package
projectA.Frameworks.First().PackageReferences.Clear();
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 0);
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_PackageRemoveTransitive_UpdatesLockFile()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectB.AddPackageToAllFrameworks(packageX);
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project File name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal(lockFile.Targets.First().Dependencies.FirstOrDefault(e => e.Type == PackageDependencyType.Transitive).Id, "x");
Assert.Equal(lockFile.Targets.First().Dependencies.FirstOrDefault(e => e.Type == PackageDependencyType.Project).Id, "b");
// Setup - remove package
projectB.Frameworks.First().PackageReferences.Clear();
projectB.Save();
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 1);
Assert.Equal(lockFile.Targets.First().Dependencies.First().Id, "b");
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_CustomAssemblyName_DoesNotBreakLockedMode()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
// A -> B
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectB.Properties.Add("AssemblyName", "CustomName");
projectA.AddProjectToAllFrameworks(projectB);
// B
projectB.AddPackageToFramework(tfm, packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project custom name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal("CustomName", lockFile.Targets.First().Dependencies.First(e => e.Type == PackageDependencyType.Project).Id);
// Setup - Enable locked mode
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
File.Delete(projectA.AssetsFileOutputPath);
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_CustomPackageId_DoesNotBreakLockedMode()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
// A -> B
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectB.Properties.Add("PackageId", "CustomName");
projectA.AddProjectToAllFrameworks(projectB);
// B
projectB.AddPackageToFramework(tfm, packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the custom name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal("CustomName", lockFile.Targets.First().Dependencies.First(e => e.Type == PackageDependencyType.Project).Id);
// Setup - Enable locked mode
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
File.Delete(projectA.AssetsFileOutputPath);
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public void RestoreNetCore_PackagesLockFile_ProjectReferenceChange_UpdatesLockFile()
{
// Arrange
// A -> B -> C and
// A -> B, A -> C
// should have different lock files
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddProjectToAllFrameworks(projectC);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
Assert.True(File.Exists(projectC.AssetsFileOutputPath));
Assert.False(File.Exists(projectC.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project File name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal(lockFile.Targets.First().Dependencies.First().Id, "b");
Assert.Equal(lockFile.Targets.First().Dependencies.First().Dependencies.Count, 1);
Assert.Equal(lockFile.Targets.First().Dependencies.Last().Id, "c");
// Setup - remove package
projectB.Frameworks.First().ProjectReferences.Clear();
projectB.Save();
projectA.Frameworks.First().ProjectReferences.Add(projectC);
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal(lockFile.Targets.First().Dependencies.First().Id, "b");
Assert.Equal(lockFile.Targets.First().Dependencies.First().Dependencies.Count, 0);
Assert.Equal(lockFile.Targets.First().Dependencies.Last().Id, "c");
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_WithProjectAndPackageReference_DoesNotBreakLockedMode()
{
// A -> B -> C
// -> X
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddPackageToAllFrameworks(packageX);
projectB.AddProjectToAllFrameworks(projectC);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
Assert.True(File.Exists(projectC.AssetsFileOutputPath));
Assert.False(File.Exists(projectC.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project File name.
Assert.Equal(lockFile.Targets.First().Dependencies.Count, 3);
Assert.Equal(lockFile.Targets.First().Dependencies.FirstOrDefault(e => e.Type == PackageDependencyType.Transitive).Id, "x");
Assert.Equal(lockFile.Targets.First().Dependencies.FirstOrDefault(e => e.Type == PackageDependencyType.Project).Id, "b");
Assert.Equal(lockFile.Targets.First().Dependencies.LastOrDefault(e => e.Type == PackageDependencyType.Project).Id, "c");
// Setup - remove package
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_ExclusiveLowerBound_RestoreSucceeds()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX110 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.1.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100,
packageX110);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Inject dependency with exclusive lower bound
var doc = XDocument.Load(projectA.ProjectPath);
var ns = doc.Root.GetDefaultNamespace().NamespaceName;
doc.Root.AddFirst(
new XElement(XName.Get("ItemGroup", ns),
new XElement(XName.Get("PackageReference", ns),
new XAttribute(XName.Get("Include"), "x"),
new XAttribute(XName.Get("Version"), "(1.0.0, )"))));
doc.Save(projectA.ProjectPath);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(1, projectA.AssetsFile.Libraries.Count);
var packageX = projectA.AssetsFile.Libraries.First();
Assert.NotNull(packageX);
Assert.Equal("1.1.0", packageX.Version.ToString());
}
}
[Fact]
public async Task RestoreNetCore_PackageDependencyWithExclusiveLowerBound_RestoreSucceeds()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageY = new SimpleTestPackageContext("y", "1.0.0")
{
Nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?>
<package>
<metadata>
<id>y</id>
<version>1.0.0</version>
<title />
<dependencies>
<group targetFramework=""net45"">
<dependency id=""x"" version=""(1.0.0, )"" />
</group>
</dependencies>
</metadata>
</package>")
};
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX110 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.1.0"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100,
packageX110,
packageY);
projectA.AddPackageToAllFrameworks(packageY);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(2, projectA.AssetsFile.Libraries.Count);
var packageX = projectA.AssetsFile.Libraries.FirstOrDefault(e => e.Name.Equals("x"));
Assert.NotNull(packageX);
Assert.Equal("1.1.0", packageX.Version.ToString());
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_EmptyLockFile_ErrorsInLockedMode()
{
// A -> X
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{tfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
projectA.Properties.Add("RestoreLockedMode", "true");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
File.WriteAllText(projectA.NuGetLockFileOutputPath, "");
// Act
var r = Util.RestoreSolution(pathContext, expectedExitCode: 1);
// Assert
r.Success.Should().BeFalse();
r.AllOutput.Should().Contain("NU1004");
}
}
[Fact]
public async Task RestoreNetCore_PackagesLockFile_AssetTargetFallback_DoesNotBreakLockedMode()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "netcoreapp2.0";
var fallbackTfm = "net46";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
projectA.Properties.Add("AssetTargetFallback", fallbackTfm);
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(tfm));
projectB.Properties.Add("AssetTargetFallback", fallbackTfm); // This is the important ATF.
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile($"lib/{fallbackTfm}/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX);
// A -> B
projectA.AddProjectToAllFrameworks(projectB);
projectA.AddPackageToFramework(tfm, packageX);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectB.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.False(File.Exists(projectB.NuGetLockFileOutputPath));
var packagesLockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
// Assert that the project name is the project custom name.
Assert.Equal(packagesLockFile.Targets.First().Dependencies.Count, 2);
Assert.Equal(packagesLockFile.Targets.First().Dependencies.First(e => e.Type == PackageDependencyType.Project).Id, "b");
// Setup - Enable locked mode
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
File.Delete(projectA.CacheFileOutputPath);
// Act
result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
}
}
[Fact]
public async Task RestoreNetCore_ProjectProvidedRuntimeIdentifierGraph_SelectsCorrectRuntimeAssets()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp20 = "netcoreapp2.0";
var netcoreapp21 = "netcoreapp2.1";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20), NuGetFramework.Parse(netcoreapp21));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
projectA.Properties.Add("RuntimeIdentifier", " ");
// Set up the package and source
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/netcoreapp2.0/x.dll");
packageX.AddFile("ref/netcoreapp2.0/x.dll");
packageX.AddFile("runtimes/win7/lib/netcoreapp2.0/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
// set up rid graph
var ridGraphPath = Path.Combine(pathContext.WorkingDirectory, "runtime.json");
projectA.Frameworks.First(e => e.Framework.GetShortFolderName().Equals(netcoreapp20)).Properties.Add("RuntimeIdentifierGraphPath", ridGraphPath);
File.WriteAllBytes(ridGraphPath, GetTestUtilityResource("runtime.json"));
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(4, projectA.AssetsFile.Targets.Count);
Assert.Equal(1, projectA.AssetsFile.Libraries.Count);
Assert.Equal("runtimes/win7/lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
Assert.Equal("lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
}
}
[Fact]
public async Task RestoreNetCore_BadProjectProvidedRuntimeIdentifierGraph_FailsRestore()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp20 = "netcoreapp2.0";
var netcoreapp21 = "netcoreapp2.1";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20), NuGetFramework.Parse(netcoreapp21));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
projectA.Properties.Add("RuntimeIdentifier", " ");
// Set up the package and source
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/netcoreapp2.0/x.dll");
packageX.AddFile("ref/netcoreapp2.0/x.dll");
packageX.AddFile("runtimes/win7/lib/netcoreapp2.0/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
// set up rid graph
var ridGraphPath = Path.Combine(pathContext.WorkingDirectory, "runtime.json");
projectA.Frameworks.First(e => e.Framework.GetShortFolderName().Equals(netcoreapp20)).Properties.Add("RuntimeIdentifierGraphPath", ridGraphPath);
File.WriteAllText(ridGraphPath, "{ dsadas , dasda, dsadas { } : dsada } ");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext, expectedExitCode: 1);
// Assert
result.Success.Should().BeFalse();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Contains("NU1007", result.AllOutput);
Assert.Equal(NuGetLogCode.NU1007, projectA.AssetsFile.LogMessages.Single().Code);
}
}
[Fact]
public async Task RestoreNetCore_ProjectProvidedRuntimeIdentifierGraphChange_DoesNotAffectNoOp()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp20 = "netcoreapp2.0";
var netcoreapp21 = "netcoreapp2.1";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20), NuGetFramework.Parse(netcoreapp21));
projectA.Properties.Add("RuntimeIdentifiers", "win7-x86");
projectA.Properties.Add("RuntimeIdentifier", " ");
// Set up the package and source
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/netcoreapp2.0/x.dll");
packageX.AddFile("ref/netcoreapp2.0/x.dll");
packageX.AddFile("runtimes/win7/lib/netcoreapp2.0/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
// setup rid graph.
var ridGraphPath = Path.Combine(pathContext.WorkingDirectory, "runtime.json");
projectA.Frameworks.First(e => e.Framework.GetShortFolderName().Equals(netcoreapp20)).Properties.Add("RuntimeIdentifierGraphPath", ridGraphPath);
File.WriteAllBytes(ridGraphPath, GetTestUtilityResource("runtime.json"));
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var commandRunnerResult = Util.RestoreSolution(pathContext);
// Assert
commandRunnerResult.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(4, projectA.AssetsFile.Targets.Count);
Assert.Equal(1, projectA.AssetsFile.Libraries.Count);
Assert.Equal("runtimes/win7/lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
Assert.Equal("lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
// second set-up. Change the graph. Affect no-op.
File.Delete(ridGraphPath);
ridGraphPath = Path.Combine(pathContext.WorkingDirectory, "runtime-2.json");
projectA.Frameworks.First(e => e.Framework.GetShortFolderName().Equals(netcoreapp20)).Properties["RuntimeIdentifierGraphPath"] = ridGraphPath;
File.WriteAllBytes(ridGraphPath, GetTestUtilityResource("runtime.json"));
projectA.Save();
// Act & Assert
commandRunnerResult = Util.RestoreSolution(pathContext);
commandRunnerResult.Success.Should().BeTrue();
commandRunnerResult.AllOutput.Contains("Writing cache file");
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(4, projectA.AssetsFile.Targets.Count);
Assert.Equal(1, projectA.AssetsFile.Libraries.Count);
Assert.Equal("runtimes/win7/lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
Assert.Equal("lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
// second set-up. Change the graph. Affect no-op.
File.Delete(ridGraphPath);
File.WriteAllText(ridGraphPath, "{ }"); // empty rid graph.
projectA.Save();
// Act & Assert. The result should not be affected by the runtime json change.
commandRunnerResult = Util.RestoreSolution(pathContext);
commandRunnerResult.Success.Should().BeTrue();
Assert.Contains("No-Op restore", commandRunnerResult.AllOutput);
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(4, projectA.AssetsFile.Targets.Count);
Assert.Equal(1, projectA.AssetsFile.Libraries.Count);
Assert.Equal("runtimes/win7/lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp20)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
Assert.Equal("lib/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().RuntimeAssemblies.Select(e => e.Path)));
Assert.Equal("ref/netcoreapp2.0/x.dll",
string.Join(";", projectA.AssetsFile.Targets.First(e => string.Equals("win7-x86", e.RuntimeIdentifier) && string.Equals(e.TargetFramework.GetShortFolderName(), netcoreapp21)).Libraries.Single().CompileTimeAssemblies.Select(e => e.Path)));
}
}
[Theory]
[InlineData(new string[] { "win7-x86" }, new string[] { "win-x64" })]
[InlineData(new string[] { "win7-x86", "win-x64" }, new string[] { "win-x64" })]
[InlineData(new string[] { "win7-x86" }, new string[] { "win7-x86", "win-x64" })]
public void RestoreNetCore_PackagesLockFile_WithProjectChangeRuntimeAndLockedMode_FailsRestore(string[] intitialRuntimes, string[] updatedRuntimes)
{
// A project with RestoreLockedMode should fail restore if the project's runtime is changed between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var tfm = "net45";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
new NuGetFramework[] { NuGetFramework.Parse(tfm) });
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
projectA.Properties.Add("RuntimeIdentifiers", string.Join(";", intitialRuntimes));
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
var lockRuntimes = lockFile.Targets.Where(t => t.RuntimeIdentifier != null).Select(t => t.RuntimeIdentifier).ToList();
intitialRuntimes.ShouldBeEquivalentTo(lockRuntimes);
// Setup - change runtimes
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Remove("RuntimeIdentifiers");
projectA.Properties.Add("RuntimeIdentifiers", string.Join(";", updatedRuntimes));
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext, 1);
// Assert
r.Success.Should().BeFalse();
lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
lockRuntimes = lockFile.Targets.Where(t => t.RuntimeIdentifier != null).Select(t => t.RuntimeIdentifier).ToList();
// No change expected in the lock file.
intitialRuntimes.ShouldBeEquivalentTo(lockRuntimes);
Assert.Contains("NU1004", r.Errors);
}
}
[Theory]
[InlineData(new string[] { "net45" }, new string[] { "net46" })]
[InlineData(new string[] { "net45", "net46" }, new string[] { "net46" })]
[InlineData(new string[] { "net45" }, new string[] { "net45", "net46" })]
public void RestoreNetCore_PackagesLockFile_WithProjectChangeFramweorksAndLockedMode_FailsRestore(string[] intitialFrameworks, string[] updatedFrameworks)
{
// A project with RestoreLockedMode should fail restore if the project's frameworks list is changed between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
intitialFrameworks.Select(tfm => NuGetFramework.Parse(tfm)).ToArray());
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// The framework as they are in the lock file
var lockFrameworkTransformed = intitialFrameworks.Select(f => $".NETFramework,Version=v{f.Replace("net", "")[0]}.{f.Replace("net", "")[1]}").ToList();
_output.WriteLine($"InputFrameworks: {string.Join(",", lockFrameworkTransformed)}");
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
var lockFrameworks = lockFile.Targets.Select(t => t.TargetFramework.DotNetFrameworkName).Distinct().ToList();
_output.WriteLine($"PackageLockFrameworks First Evaluation: {string.Join(",", lockFrameworks)}");
lockFrameworkTransformed.ShouldBeEquivalentTo(lockFrameworks);
// Setup - change frameworks
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Frameworks = updatedFrameworks.Select(tfm => new SimpleTestProjectFrameworkContext(NuGetFramework.Parse(tfm))).ToList();
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext, 1);
// Assert
r.Success.Should().BeFalse();
lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
lockFrameworks = lockFile.Targets.Select(t => t.TargetFramework.DotNetFrameworkName).Distinct().ToList();
_output.WriteLine($"PackageLockFrameworks Second Evaluation: {string.Join(",", lockFrameworks)}");
// The frameworks should not chnage in the lock file.
lockFrameworkTransformed.ShouldBeEquivalentTo(lockFrameworks);
Assert.Contains("NU1004", r.Errors);
}
}
[Theory]
[InlineData(new string[] { "x_lockmodedepch/1.0.0" }, new string[] { "x_lockmodedepch/2.0.0" })]
[InlineData(new string[] { "x_lockmodedepch/1.0.0" }, new string[] { "y_lockmodedepch/1.0.0" })]
[InlineData(new string[] { "x_lockmodewdepch/1.0.0" }, new string[] { "x_lockmodedepch/1.0.0", "y_lockmodedepch/1.0.0" })]
[InlineData(new string[] { "x_lockmodedepch/1.0.0", "y_lockmodedepch/1.0.0" }, new string[] { "y_lockmodedepch/1.0.0" })]
public async Task RestoreNetCore_PackagesLockFile_WithProjectChangePackageDependencyAndLockedMode_FailsRestore(
string[] initialPackageIdAndVersion,
string[] updatedPackageIdAndVersion)
{
// A project with RestoreLockedMode should fail restore if the project's package dependencies were changed between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp20 = "netcoreapp2.0";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
// Set up the package and source
var packages = initialPackageIdAndVersion.Select(p =>
{
var id = p.Split('/')[0];
var version = p.Split('/')[1];
var package = new SimpleTestPackageContext()
{
Id = id,
Version = version
};
package.Files.Clear();
package.AddFile($"lib/netcoreapp2.0/{id}.dll");
package.AddFile($"ref/netcoreapp2.0/{id}.dll");
package.AddFile($"runtimes/win7/lib/netcoreapp2.0/{id}.dll");
return package;
}).ToArray();
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packages);
projectA.AddPackageToAllFrameworks(packages);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Setup - change project's packages
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.CleanPackagesFromAllFrameworks();
packages = updatedPackageIdAndVersion.Select(p =>
{
var id = p.Split('/')[0];
var version = p.Split('/')[1];
var package = new SimpleTestPackageContext()
{
Id = id,
Version = version
};
package.Files.Clear();
package.AddFile($"lib/netcoreapp2.0/{id}.dll");
package.AddFile($"ref/netcoreapp2.0/{id}.dll");
package.AddFile($"runtimes/win7/lib/netcoreapp2.0/{id}.dll");
return package;
}).ToArray();
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packages);
projectA.AddPackageToAllFrameworks(packages);
projectA.Save();
// Act
r = Util.RestoreSolution(pathContext, 1);
// Assert
r.Success.Should().BeFalse();
Assert.Contains("NU1004", r.Errors);
}
}
[Theory]
[InlineData(new string[] { "x_lockmodetdepch/1.0.0" }, new string[] { "x_lockmodetdepch/2.0.0" })]
[InlineData(new string[] { "x_lockmodetdepch/1.0.0" }, new string[] { "y_lockmodetdepch/1.0.0" })]
[InlineData(new string[] { "x_lockmodetdepch/1.0.0" }, new string[] { "x_lockmodetdepch/1.0.0", "y_lockmodetdepch/1.0.0" })]
[InlineData(new string[] { "x_lockmodetdepch/1.0.0", "y_lockmodetdepch/1.0.0" }, new string[] { "y_lockmodetdepch/1.0.0" })]
public async Task RestoreNetCore_PackagesLockFile_WithDependentProjectChangeOfPackageDependencyAndLockedMode_FailsRestore(
string[] initialPackageIdAndVersion,
string[] updatedPackageIdAndVersion)
{
// A project with RestoreLockedMode should fail restore if the package dependencies of a dependent project were changed between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp20 = "netcoreapp2.0";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
NuGetFramework.Parse(netcoreapp20));
// Set up the package and source
var packages = initialPackageIdAndVersion.Select(p =>
{
var id = p.Split('/')[0];
var version = p.Split('/')[1];
var package = new SimpleTestPackageContext()
{
Id = id,
Version = version
};
package.Files.Clear();
package.AddFile($"lib/netcoreapp2.0/{id}.dll");
package.AddFile($"ref/netcoreapp2.0/{id}.dll");
package.AddFile($"runtimes/win7/lib/netcoreapp2.0/{id}.dll");
return package;
}).ToArray();
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packages);
projectB.AddPackageToAllFrameworks(packages);
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Setup - change project's packages
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
projectB.CleanPackagesFromAllFrameworks();
packages = updatedPackageIdAndVersion.Select(p =>
{
var id = p.Split('/')[0];
var version = p.Split('/')[1];
var package = new SimpleTestPackageContext()
{
Id = id,
Version = version
};
package.Files.Clear();
package.AddFile($"lib/netcoreapp2.0/{id}.dll");
package.AddFile($"ref/netcoreapp2.0/{id}.dll");
package.AddFile($"runtimes/win7/lib/netcoreapp2.0/{id}.dll");
return package;
}).ToArray();
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packages);
projectB.AddPackageToAllFrameworks(packages);
projectB.Save();
// Act
r = Util.RestoreSolution(pathContext, 1);
// Assert
r.Success.Should().BeFalse();
Assert.Contains("NU1004", r.Errors);
}
}
[Theory]
[InlineData("netcoreapp2.0", new string[] { "netcoreapp2.0" }, new string[] { "netcoreapp2.2" })]
[InlineData("netcoreapp2.0", new string[] { "netcoreapp2.0", "netcoreapp2.2" }, new string[] { "netcoreapp2.2" })]
public void RestoreNetCore_PackagesLockFile_WithDependentProjectChangeOfNotCompatibleFrameworksAndLockedMode_FailsRestore(
string mainProjectFramework,
string[] initialFrameworks,
string[] updatedFrameworks)
{
// A project with RestoreLockedMode should fail restore if the frameworks of a dependent project were changed
// with incompatible frameworks between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(mainProjectFramework));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
initialFrameworks.Select(tfm => NuGetFramework.Parse(tfm)).ToArray());
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Setup - change package version
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
projectB.Frameworks = updatedFrameworks.Select(tfm => new SimpleTestProjectFrameworkContext(NuGetFramework.Parse(tfm))).ToList();
projectB.Save();
// Act
r = Util.RestoreSolution(pathContext, 1);
// Assert
r.Success.Should().BeFalse();
Assert.Contains("NU1004", r.Errors);
}
}
[Theory]
[InlineData("netcoreapp2.2", new string[] { "netcoreapp2.2" }, new string[] { "netcoreapp2.0", "netcoreapp2.2" })]
[InlineData("netcoreapp2.2", new string[] { "netcoreapp2.0", "netcoreapp2.2" }, new string[] { "netcoreapp2.2" })]
[InlineData("netcoreapp2.2", new string[] { "netcoreapp2.0" }, new string[] { "netcoreapp2.2" })]
public void RestoreNetCore_PackagesLockFile_WithDependentProjectChangeOfCompatibleFrameworksAndLockedMode_PassRestore(
string mainProjectFramework,
string[] initialFrameworks,
string[] updatedFrameworks)
{
// A project with RestoreLockedMode should pass restore if the frameworks of a dependent project were changed
// with still compatible with main project frameworks between restores.
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(mainProjectFramework));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
initialFrameworks.Select(tfm => NuGetFramework.Parse(tfm)).ToArray());
projectA.AddProjectToAllFrameworks(projectB);
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Setup - change package version
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
projectB.Frameworks = updatedFrameworks.Select(tfm => new SimpleTestProjectFrameworkContext(NuGetFramework.Parse(tfm))).ToList();
projectB.Save();
// Act
r = Util.RestoreSolution(pathContext, 0);
// Assert
r.Success.Should().BeTrue();
}
}
[Fact]
public async void RestoreNetCore_PackagesLockFile_WithReorderedRuntimesInLockFile_PassRestore()
{
// A project with RestoreLockedMode should pass restore if the runtimes in the lock file have been reordered
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projFramework = Frameworks.FrameworkConstants.CommonFrameworks.NetCoreApp21.GetShortFolderName();
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(projFramework));
var runtimeidentifiers = new List<string>() { "win7-x64", "win-x86", "win", "z", "a" };
var ascending = runtimeidentifiers.OrderBy(i => i);
projectA.Properties.Add("RuntimeIdentifiers", string.Join(";", ascending));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
// Set up the package and source
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX.Files.Clear();
packageX.AddFile("lib/netcoreapp2.0/x.dll");
packageX.AddFile("ref/netcoreapp2.0/x.dll");
packageX.AddFile("lib/net461/x.dll");
packageX.AddFile("ref/net461/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
projectA.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
var packagesLockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath);
//Modify the list of target/runtimes so they are reordered in the lock file
//Verify the passed in RIDs are within the lock file
//Verify the RIDS are not the same after reordering.
//Lock file is not ordered based on input RIDs so Validating the reorder here.
var originalTargets = packagesLockFile.Targets.Where(t => t.RuntimeIdentifier != null).Select(t => t.RuntimeIdentifier).ToList();
runtimeidentifiers.ShouldBeEquivalentTo(originalTargets);
//Nuget.exe test so reordering to make it not match. It should still restore correctly
packagesLockFile.Targets = packagesLockFile.Targets.
OrderByDescending(t => t.RuntimeIdentifier == null).
ThenByDescending(i => i.RuntimeIdentifier).ToList();
var reorderedTargets = packagesLockFile.Targets.Where(t => t.RuntimeIdentifier != null).Select(t => t.RuntimeIdentifier).ToList();
//The orders are not equal. Then resave the lock file and project.
//The null RID must be the first one otherwise this fails
Assert.False(originalTargets.SequenceEqual(reorderedTargets));
Assert.True(packagesLockFile.Targets[0].RuntimeIdentifier == null);
PackagesLockFileFormat.Write(projectA.NuGetLockFileOutputPath, packagesLockFile);
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
//Run the restore and it should still properly restore.
var r2 = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
[Theory]
[InlineData("1.0.0;2.0.0", "*", "2.0.0")]
[InlineData("1.0.0;2.0.0", "0.*", "1.0.0")]
public async Task RestoreNetCore_WithFloatingVersion_SelectsCorrectVersion(string availableVersions, string declaredProjectVersion, string expectedVersion)
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var framework = "net472";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(framework));
foreach (string version in availableVersions.Split(';'))
{
// Set up the package and source
var package = new SimpleTestPackageContext()
{
Id = "x",
Version = version
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
package);
}
projectA.AddPackageToAllFrameworks(new SimpleTestPackageContext()
{
Id = "x",
Version = declaredProjectVersion
});
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.Equal(expectedVersion, projectA.AssetsFile.Libraries.Single().Version.ToString());
}
}
[Theory]
[InlineData("1.0.0;2.0.0", "*", "2.0.0")]
[InlineData("1.0.0;2.0.0", "0.*", "1.0.0")]
public async Task RestoreNetCore_PackagesLockFileWithFloatingVersion_LockedModeIsRespected(string availableVersions, string declaredProjectVersion, string expectedVersion)
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var framework = "net472";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(framework));
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
foreach (string version in availableVersions.Split(';'))
{
// Set up the package and source
var package = new SimpleTestPackageContext()
{
Id = "x",
Version = version
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
package);
}
projectA.AddPackageToAllFrameworks(new SimpleTestPackageContext()
{
Id = "x",
Version = declaredProjectVersion
});
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
Assert.Equal(expectedVersion, projectA.AssetsFile.Libraries.Single().Version.ToString());
// Set-up again.
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Save();
// Act
result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
}
}
[Fact]
public async Task RestoreNetCore_PackageReferenceWithAliases_IsReflectedInAssetsFileAsync()
{
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var framework = "net472";
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse(framework));
// Set up the package and source
var package = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0",
Aliases = "Core"
};
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
package);
projectA.AddPackageToAllFrameworks(package);
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var result = Util.RestoreSolution(pathContext);
// Assert
result.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
var library = projectA.AssetsFile.Targets.First(e => e.RuntimeIdentifier == null).Libraries.Single();
library.Should().NotBeNull("The assets file is expect to have a single library");
library.CompileTimeAssemblies.Count.Should().Be(1, because: "The package has only 1 compatible file");
library.CompileTimeAssemblies.Single().Properties.Should().Contain(new KeyValuePair<string, string>(LockFileItem.AliasesProperty, "Core"));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_DirectDependencyCentralVersionChanged_FailsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX200 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
packageX200.Files.Clear();
packageX200.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100, packageX200);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Second Restore
r = Util.RestoreSolution(pathContext);
// Update the cpvm
cpvmFile.UpdatePackageVersion("x", "2.0.0");
cpvmFile.Save();
// Expect exit code 1 on this restore
r = Util.RestoreSolution(pathContext, 1);
Assert.True(r.AllOutput.Contains("NU1004: The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file."));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_TransitiveDependencyCentralVersionChanged_FailsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageY200 = new SimpleTestPackageContext()
{
Id = "y",
Version = "2.0.0"
};
packageY200.Files.Clear();
packageY200.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100, packageY200);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Update the transitive dependency in cpvm
cpvmFile.UpdatePackageVersion("y", "2.0.0");
cpvmFile.Save();
// Expect exit code 1 on this restore
r = Util.RestoreSolution(pathContext, 1);
Assert.True(r.AllOutput.Contains("NU1004: The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file."));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_RemovedCentralDirectDependency_FailsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Update the cpvm
cpvmFile.RemovePackageVersion("x");
cpvmFile.Save();
// Expect exit code 1 on this restore
r = Util.RestoreSolution(pathContext, 1);
Assert.True(r.AllOutput.Contains("NU1004: The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file."));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_RemovedCentralTransitiveDependency_FailsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Update the cpvm
cpvmFile.RemovePackageVersion("y");
cpvmFile.Save();
// Expect exit code 1 on this restore
r = Util.RestoreSolution(pathContext, 1);
Assert.True(r.AllOutput.Contains("NU1004: The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file."));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_MoveTransitiveDependnecyToCentralFile_FailsRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Update the cpvm
cpvmFile.AddPackageVersion("y", "1.0.0");
cpvmFile.Save();
// Expect exit code 1 on this restore
r = Util.RestoreSolution(pathContext, 1);
Assert.True(r.AllOutput.Contains("NU1004: The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file."));
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_AddRemoveNotProjectRelatedEntriesToCentralFile_SuccessRestore()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
NuGetFramework.Parse("net46"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
projectA.Properties.Add("RestoreLockedMode", "true");
projectA.Properties.Add("RestorePackagesWithLockFile", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageX100NullVersion = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
packageX100.Files.Clear();
packageX100.AddFile("lib/net46/x.dll");
var packageY100 = new SimpleTestPackageContext()
{
Id = "y",
Version = "1.0.0"
};
packageY100.Files.Clear();
packageY100.AddFile("lib/net46/y.dll");
packageX100.Dependencies.Add(packageY100);
var packageRandom = new SimpleTestPackageContext()
{
Id = "random",
Version = "1.0.0"
};
packageRandom.Files.Clear();
packageRandom.AddFile("lib/net46/x.dll");
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageY100, packageRandom);
projectA.AddPackageToAllFrameworks(packageX100NullVersion);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "1.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.NuGetLockFileOutputPath));
// Add new package version the cpvm
cpvmFile.AddPackageVersion("random", "1.0.0");
cpvmFile.Save();
// the addition should not impact this restore
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
// Update the cpvm
cpvmFile.RemovePackageVersion("random");
cpvmFile.Save();
// the removal should not impact this restore
r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
}
}
/// <summary>
/// Project A -> PackageX 100
/// -> PackageY 200 -> PackageX 200
/// -> ProjectB -> ProjectC -> PackageX 100
/// All projects CPVM enabled; PackageX 100 and PackageY 200 in cpvm file
/// Expected NU1605
/// </summary>
[Fact]
public async Task RestoreNetCore_CPVMProject_DowngradedByCentralDirectDependencyWithP2P_IsWarningNU1605()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var netcoreapp2 = NuGetFramework.Parse("netcoreapp2.0");
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
netcoreapp2);
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
var projectB = SimpleTestProjectContext.CreateNETCore(
"b",
pathContext.SolutionRoot,
netcoreapp2);
projectB.Properties.Add("ManagePackageVersionsCentrally", "true");
var projectC = SimpleTestProjectContext.CreateNETCore(
"c",
pathContext.SolutionRoot,
netcoreapp2);
projectC.Properties.Add("ManagePackageVersionsCentrally", "true");
var packageX100 = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var packageX200 = new SimpleTestPackageContext()
{
Id = "x",
Version = "2.0.0"
};
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = null
};
var packageY200 = new SimpleTestPackageContext()
{
Id = "y",
Version = "2.0.0"
};
var packageY = new SimpleTestPackageContext()
{
Id = "y",
Version = null
};
packageY200.Dependencies.Add(packageX200);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packageX100, packageX200, packageY200);
projectA.AddPackageToAllFrameworks(packageX);
projectA.AddPackageToAllFrameworks(packageY);
projectA.AddProjectToAllFrameworks(projectB);
projectB.AddProjectToAllFrameworks(projectC);
projectC.AddPackageToAllFrameworks(packageX);
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("x", "1.0.0")
.AddPackageVersion("y", "2.0.0");
solution.Projects.Add(projectA);
solution.Projects.Add(projectB);
solution.Projects.Add(projectC);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
var restoreResult = Util.RestoreSolution(pathContext);
Assert.True(restoreResult.AllOutput.Contains("NU1605"));
}
}
/// <summary>
/// A more complex graph with linked central transitive dependecies
///
/// A -> B 1.0.0 -> C 1.0.0 -> D 1.0.0 -> E 1.0.0
/// -> P 2.0.0
/// -> F 1.0.0 -> C 2.0.0 -> H 2.0.0 -> M 2.0.0 -> N 2.0.0
/// -> G 1.0.0 -> H 1.0.0 -> D 1.0.0
/// -> X 1.0.0 -> Y 1.0.0 -> Z 1.0.0
/// -> T 1.0.0
/// -> U 1.0.0 -> V 1.0.0
/// -> O 1.0.0 -> R 1.0.0 -> S 1.0.0 -> SS 1.0.0
///
/// D has version defined centrally 2.0.0
/// E has version defined centrally 3.0.0
/// M has version defined centrally 2.0.0
/// P has version defined centrally 3.0.0
/// Z has version defined centrally 3.0.0
/// T has version defined centrally 3.0.0
/// R has version defined centrally 3.0.0
/// S has version defined centrally 3.0.0
///
/// D 2.0.0 -> I 2.0.0 -> E 2.0.0
/// M 2.0.0 -> N 2.0.0
/// P 3.0.0 -> H 3.0.0
/// -> Y 3.0.0
/// -> O 3.0.0 -> S 3.0.0 -> SS 3.0.0
/// Z 3.0.0 -> V 3.0.0
/// T 3.0.0 -> W 3.0.0
/// -> C 1.0.0
/// S 3.0.0 -> SS 3.0.0
///
/// D will be rejected (because its parents C 1.0.0, H 1.0.0 are rejected)
/// E will be rejected (because its parent D was rejected)
/// M will be rejected (because its parent lost the dispute with H 3.0.0)
/// T will be rejected (because its parent lost the dispute with Y 3.0.0)
/// Z will be rejected (because its parent lost the dispute with Y 3.0.0)
///
/// P will be accepted (because its parent B is Accepted)
/// S will be accepted (because its parent O 300 is Accepted)
/// </summary>
[Fact(Skip = "https://github.com/NuGet/Home/issues/10133")]
public async Task RestoreNetCore_CPVMProject_MultipleLinkedCentralTransitiveDepenencies()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var version100 = "1.0.0";
var version200 = "2.0.0";
var version300 = "3.0.0";
var packagesForSource = new List<SimpleTestPackageContext>();
var packagesForProject = new List<SimpleTestPackageContext>();
var framework = NuGetFramework.Parse("netcoreapp2.0");
SimpleTestPackageContext createTestPackage(string name, string version, List<SimpleTestPackageContext> source)
{
var result = new SimpleTestPackageContext()
{
Id = name,
Version = version
};
result.Files.Clear();
source.Add(result);
return result;
};
var projectA = SimpleTestProjectContext.CreateNETCore(
"projectA",
pathContext.SolutionRoot,
NuGetFramework.Parse("netcoreapp2.0"));
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
// the package references defined in the project should not have version
var packageBNoVersion = createTestPackage("B", null, packagesForProject);
var packageFNoVersion = createTestPackage("F", null, packagesForProject);
var packageGNoVersion = createTestPackage("G", null, packagesForProject);
var packageUNoVersion = createTestPackage("U", null, packagesForProject);
var packageXNoVersion = createTestPackage("X", null, packagesForProject);
var packageB100 = createTestPackage("B", version100, packagesForSource);
var packageC100 = createTestPackage("C", version100, packagesForSource);
var packageD100 = createTestPackage("D", version100, packagesForSource);
var packageE100 = createTestPackage("E", version100, packagesForSource);
var packageF100 = createTestPackage("F", version100, packagesForSource);
var packageG100 = createTestPackage("G", version100, packagesForSource);
var packageH100 = createTestPackage("H", version100, packagesForSource);
var packageX100 = createTestPackage("X", version100, packagesForSource);
var packageY100 = createTestPackage("Y", version100, packagesForSource);
var packageZ100 = createTestPackage("Z", version100, packagesForSource);
var packageV100 = createTestPackage("V", version100, packagesForSource);
var packageT100 = createTestPackage("T", version100, packagesForSource);
var packageU100 = createTestPackage("U", version100, packagesForSource);
var packageO100 = createTestPackage("O", version100, packagesForSource);
var packageR100 = createTestPackage("R", version100, packagesForSource);
var packageS100 = createTestPackage("S", version100, packagesForSource);
var packageSS100 = createTestPackage("SS", version100, packagesForSource);
var packageC200 = createTestPackage("C", version200, packagesForSource);
var packageD200 = createTestPackage("D", version200, packagesForSource);
var packageE200 = createTestPackage("E", version200, packagesForSource);
var packageI200 = createTestPackage("I", version200, packagesForSource);
var packageH200 = createTestPackage("H", version200, packagesForSource);
var packageM200 = createTestPackage("M", version200, packagesForSource);
var packageN200 = createTestPackage("N", version200, packagesForSource);
var packageP200 = createTestPackage("P", version200, packagesForSource);
var packageE300 = createTestPackage("E", version300, packagesForSource);
var packageP300 = createTestPackage("P", version300, packagesForSource);
var packageH300 = createTestPackage("H", version300, packagesForSource);
var packageZ300 = createTestPackage("Z", version300, packagesForSource);
var packageV300 = createTestPackage("V", version300, packagesForSource);
var packageT300 = createTestPackage("T", version300, packagesForSource);
var packageW300 = createTestPackage("W", version300, packagesForSource);
var packageY300 = createTestPackage("Y", version300, packagesForSource);
var packageO300 = createTestPackage("O", version300, packagesForSource);
var packageR300 = createTestPackage("R", version300, packagesForSource);
var packageS300 = createTestPackage("S", version300, packagesForSource);
var packageSS300 = createTestPackage("SS", version300, packagesForSource);
packageB100.Dependencies.Add(packageC100);
packageC100.Dependencies.Add(packageD100);
packageD100.Dependencies.Add(packageE100);
packageB100.Dependencies.Add(packageP200);
packageF100.Dependencies.Add(packageC200);
packageC200.Dependencies.Add(packageH200);
packageH200.Dependencies.Add(packageM200);
packageM200.Dependencies.Add(packageN200);
packageG100.Dependencies.Add(packageH100);
packageH100.Dependencies.Add(packageD100);
packageX100.Dependencies.Add(packageY100);
packageY100.Dependencies.Add(packageZ100);
packageY100.Dependencies.Add(packageT100);
packageU100.Dependencies.Add(packageV100);
packageU100.Dependencies.Add(packageO100);
packageO100.Dependencies.Add(packageR100);
packageR100.Dependencies.Add(packageS100);
packageS100.Dependencies.Add(packageSS100);
packageD200.Dependencies.Add(packageI200);
packageI200.Dependencies.Add(packageE200);
packageP300.Dependencies.Add(packageH300);
packageP300.Dependencies.Add(packageY300);
packageP300.Dependencies.Add(packageO300);
packageO300.Dependencies.Add(packageS300);
packageS300.Dependencies.Add(packageSS300);
packageZ300.Dependencies.Add(packageV300);
packageT300.Dependencies.Add(packageW300);
packageT300.Dependencies.Add(packageC100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packagesForSource.ToArray());
projectA.AddPackageToAllFrameworks(packagesForProject.ToArray());
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("B", version100)
.AddPackageVersion("F", version100)
.AddPackageVersion("G", version100)
.AddPackageVersion("E", version300)
.AddPackageVersion("D", version200)
.AddPackageVersion("M", version200)
.AddPackageVersion("P", version300)
.AddPackageVersion("Z", version300)
.AddPackageVersion("T", version300)
.AddPackageVersion("X", version100)
.AddPackageVersion("U", version100)
.AddPackageVersion("R", version300)
.AddPackageVersion("S", version300);
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
var assetFileReader = new LockFileFormat();
var assetsFile = assetFileReader.Read(projectA.AssetsFileOutputPath);
var expectedLibraries = new List<string>() { "B.1.0.0", "C.2.0.0", "F.1.0.0", "G.1.0.0", "H.3.0.0", "O.3.0.0", "P.3.0.0", "S.3.0.0", "SS.3.0.0", "U.1.0.0", "V.1.0.0", "X.1.0.0", "Y.3.0.0" };
var libraries = assetsFile.Libraries.Select(l => $"{l.Name}.{l.Version}").OrderBy(n => n).ToList();
Assert.Equal(expectedLibraries, libraries);
var centralfileDependencyGroups = assetsFile
.CentralTransitiveDependencyGroups
.SelectMany(g => g.TransitiveDependencies.Select(t => $"{g.FrameworkName}_{t.LibraryRange.Name}.{t.LibraryRange.VersionRange.OriginalString}")).ToList();
var expectedCentralfileDependencyGroups = new List<string>() { $"{framework.DotNetFrameworkName}_P.[3.0.0, )", $"{framework.DotNetFrameworkName}_S.[3.0.0, )" };
Assert.Equal(expectedCentralfileDependencyGroups, centralfileDependencyGroups);
}
}
[PlatformFact(Platform.Windows)]
public void RestoreNetCore_WithMultipleFrameworksWithPlatformAndAssetTargetFallback_Succeeds()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var net50Windows = "net5.0-windows10.0.10000.1";
var net50Android = "net5.0-android21";
var frameworks = new NuGetFramework[]
{
NuGetFramework.Parse(net50Windows),
NuGetFramework.Parse(net50Android)
};
var projectA = SimpleTestProjectContext.CreateNETCore(
"a",
pathContext.SolutionRoot,
net50Windows,
net50Android
);
projectA.Properties.Add("AssetTargetFallback", "net472");
solution.Projects.Add(projectA);
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
var targets = projectA.AssetsFile.Targets.Where(e => string.IsNullOrEmpty(e.RuntimeIdentifier)).Select(e => e);
targets.Should().HaveCount(2);
foreach (var framework in frameworks)
{
targets.Select(e => e.TargetFramework).Should().Contain(framework);
}
}
}
[PlatformFact(Platform.Windows)]
public async Task RestoreNetCore_WithCustomAliases_WritesConditionWithCorrectAlias()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packageX = new SimpleTestPackageContext()
{
Id = "x",
Version = "1.0.0"
};
var projects = new List<SimpleTestProjectContext>();
var project = SimpleTestProjectContext.CreateNETCoreWithSDK(
"proj",
pathContext.SolutionRoot,
"net5.0-windows",
"net50-android");
// Workaround: Set all the TFM properties ourselves.
// We can't rely on the SDK setting them, as only .NET 5 SDK P8 and later applies these correctly.
var net50windowsTFM = project.Frameworks.Where(f => f.TargetAlias.Equals("net5.0-windows")).Single();
var net50AndroidTFM = project.Frameworks.Where(f => f.TargetAlias.Equals("net50-android")).Single();
net50windowsTFM.Properties.Add("TargetFrameworkMoniker", ".NETCoreApp, Version=v5.0");
net50windowsTFM.Properties.Add("TargetPlatformMoniker", "Windows, Version=7.0");
net50AndroidTFM.Properties.Add("TargetFrameworkMoniker", ".NETCoreApp, Version=v5.0");
net50AndroidTFM.Properties.Add("TargetPlatformMoniker", "Android,Version=21.0");
project.AddPackageToAllFrameworks(packageX);
solution.Projects.Add(project);
solution.Create(pathContext.SolutionRoot);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
PackageSaveMode.Defaultv3,
packageX);
// Act
var r = Util.RestoreSolution(pathContext);
Assert.Equal(0, r.Item1);
Assert.True(File.Exists(project.PropsOutput), r.Item2);
var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput));
var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ItemGroup").ToList();
Assert.Contains("'$(TargetFramework)' == 'net5.0-windows' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim());
Assert.Contains("'$(TargetFramework)' == 'net50-android' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[2].Attribute(XName.Get("Condition")).Value.Trim());
}
}
[Fact]
public async Task RestoreNetCore_CPVMProject_TransitiveDependenciesAreNotPinned()
{
// Arrange
using (var pathContext = new SimpleTestPathContext())
{
// Set up solution, project, and packages
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
var packagesForSource = new List<SimpleTestPackageContext>();
var packagesForProject = new List<SimpleTestPackageContext>();
var framework = FrameworkConstants.CommonFrameworks.NetCoreApp20;
SimpleTestPackageContext createTestPackage(string name, string version, List<SimpleTestPackageContext> source)
{
var result = new SimpleTestPackageContext()
{
Id = name,
Version = version
};
result.Files.Clear();
source.Add(result);
return result;
};
var projectA = SimpleTestProjectContext.CreateNETCore(
"projectA",
pathContext.SolutionRoot,
framework);
projectA.Properties.Add("ManagePackageVersionsCentrally", "true");
// the package references defined in the project should not have version
var packageBNoVersion = createTestPackage("B", null, packagesForProject);
var packageB100 = createTestPackage("B", "1.0.0", packagesForSource);
var packageC100 = createTestPackage("C", "1.0.0", packagesForSource);
var packageC200 = createTestPackage("C", "2.0.0", packagesForSource);
packageB100.Dependencies.Add(packageC100);
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
pathContext.PackageSource,
packagesForSource.ToArray());
projectA.AddPackageToAllFrameworks(packagesForProject.ToArray());
var cpvmFile = CentralPackageVersionsManagementFile.Create(pathContext.SolutionRoot)
.AddPackageVersion("B", "1.0.0")
.AddPackageVersion("C", "2.0.0");
solution.Projects.Add(projectA);
solution.CentralPackageVersionsManagementFile = cpvmFile;
solution.Create(pathContext.SolutionRoot);
// Act
var r = Util.RestoreSolution(pathContext);
// Assert
r.Success.Should().BeTrue();
Assert.True(File.Exists(projectA.AssetsFileOutputPath));
var assetFileReader = new LockFileFormat();
var assetsFile = assetFileReader.Read(projectA.AssetsFileOutputPath);
var expectedLibraries = new List<string>() { "B.1.0.0", "C.1.0.0" };
var libraries = assetsFile.Libraries.Select(l => $"{l.Name}.{l.Version}").OrderBy(n => n).ToList();
Assert.Equal(expectedLibraries, libraries);
var centralfileDependencyGroups = assetsFile
.CentralTransitiveDependencyGroups
.SelectMany(g => g.TransitiveDependencies.Select(t => $"{g.FrameworkName}_{t.LibraryRange.Name}.{t.LibraryRange.VersionRange.OriginalString}")).ToList();
Assert.Equal(0, centralfileDependencyGroups.Count);
}
}
private static byte[] GetTestUtilityResource(string name)
{
return ResourceTestUtility.GetResourceBytes(
$"Test.Utility.compiler.resources.{name}",
typeof(ResourceTestUtility));
}
}
}
| 42.132959 | 301 | 0.537032 | [
"Apache-2.0"
] | 0xced/NuGet.Client | test/NuGet.Clients.Tests/NuGet.CommandLine.Test/RestoreNETCoreTest.cs | 427,481 | C# |
using Aju.Carefree.Dto;
using Aju.Carefree.Entity;
using AutoMapper;
namespace Aju.Carefree.AutoMapperConfig
{
public class CarefreeProfile : Profile, IProfile
{
public CarefreeProfile()
{
CreateMap<Areas, AreasDto>();
CreateMap<AreasDto, Areas>();
}
}
}
| 19.8125 | 52 | 0.624606 | [
"MIT"
] | Fast1804/Aju.Carefree | Aju.Carefree.AutoMapperConfig/CarefreeProfile.cs | 319 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using WinFormsMVC.Controller.Attribute;
namespace WinFormsMVCUnitTest.Test.Controller.BaseController
{
[TestClass]
public class BothAttributeReflectionTest
{
/// *** 以降、GetRuntimeConstructorのテスト *** ///
// 引数2つクラス
public class DualClass1
{
[CalledAsController]
public DualClass1()
{
}
[CalledAsController]
public DualClass1(int x)
{
}
}
// 引数2つクラス
public class DualClass2
{
[CalledAsController]
public DualClass2(int x)
{
}
[CalledAsController]
public DualClass2()
{
}
}
// 可変引数クラス
public class MulpipleClass
{
[CalledAsController]
public MulpipleClass(params int[] array)
{
}
[CalledAsController]
public MulpipleClass()
{
}
}
public void GetRuntimeConstructor<T>() where T : class
{
var ctor = WinFormsMVC.Controller.BaseController.GetRuntimeConstructor(typeof(T));
Assert.IsNull(ctor);
}
[TestMethod]
public void GetRuntimeConstructor()
{
GetRuntimeConstructor<DualClass1>();
GetRuntimeConstructor<DualClass2>();
GetRuntimeConstructor<MulpipleClass>();
}
}
}
| 20.6375 | 95 | 0.488795 | [
"MIT"
] | belre/WinFormsMVC | WinFormsMVCUnitTest/Test/Controller/BaseController/SecondAttributeReflectionTest.cs | 1,705 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenCheckedTests : CSharpTestBase
{
[Fact]
public void CheckedExpression_Signed()
{
var source = @"
class C
{
public static int Add(int a, int b)
{
return checked(a+b);
}
public static int Sub(int a, int b)
{
return checked(a-b);
}
public static int Mul(int a, int b)
{
return checked(a*b);
}
public static int Minus(int a)
{
return checked(-a);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.Sub", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.Mul", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.Minus", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldarg.0
IL_0002: sub.ovf
IL_0003: ret
}
");
}
[Fact]
public void CheckedExpression_Unsigned()
{
var source = @"
class C
{
public static long Add(uint a, uint b)
{
return checked(a+b);
}
public static long Sub(uint a, uint b)
{
return checked(a-b);
}
public static long Mul(uint a, uint b)
{
return checked(a*b);
}
public static long Minus(uint a)
{
return checked(-a);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf.un
IL_0003: conv.u8
IL_0004: ret
}
");
verifier.VerifyIL("C.Sub", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf.un
IL_0003: conv.u8
IL_0004: ret
}
");
verifier.VerifyIL("C.Mul", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul.ovf.un
IL_0003: conv.u8
IL_0004: ret
}
");
verifier.VerifyIL("C.Minus", @"
{
// Code size 6 (0x6)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: conv.i8
IL_0002: ldarg.0
IL_0003: conv.u8
IL_0004: sub.ovf
IL_0005: ret
}
");
}
[Fact]
public void CheckedExpression_Enums()
{
var source = @"
enum E
{
A
}
class C
{
public static E Add1(E a, int b)
{
return checked(a+b);
}
public static E Add2(int a, E b)
{
return checked(a+b);
}
public static E Sub(E a, E b)
{
return (E)checked(a-b);
}
public static E PostInc(E e)
{
return checked(e++);
}
public static E PreInc(E e)
{
return checked(--e);
}
public static E PostDec(E e)
{
return checked(e--);
}
public static E PreDec(E e)
{
return checked(--e);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.Add2", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.Sub", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf
IL_0003: ret
}
");
verifier.VerifyIL("C.PostInc", @"
{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.1
IL_0003: add.ovf
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PostDec", @"
{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.1
IL_0003: sub.ovf
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PreInc", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PreDec", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
}
[Fact]
public void CheckedExpression_Pointers()
{
var source = @"
enum E
{
A
}
unsafe struct C
{
public static C* Add_Int1(C* a, int b)
{
return checked(a+b);
}
public static C* Add_Int2(C* a, int b)
{
return checked(b+a);
}
public static C* Add_UInt1(C* a, uint b)
{
return checked(a+b);
}
public static C* Add_UInt2(C* a, uint b)
{
return checked(b+a);
}
public static C* Add_Long1(C* a, long b)
{
return checked(a+b);
}
public static C* Add_Long2(C* a, long b)
{
return checked(b+a);
}
public static C* Add_ULong1(C* a, ulong b)
{
return checked(a+b);
}
public static C* Add_ULong2(C* a, ulong b)
{
return checked(b+a);
}
public static C* Sub_Int(C* a, int b)
{
return checked(a-b);
}
public static C* Sub_UInt(C* a, uint b)
{
return checked(a-b);
}
public static C* Sub_Long(C* a, long b)
{
return checked(a-b);
}
public static C* Sub_ULong(C* a, ulong b)
{
return checked(a-b);
}
public static long Sub_Ptr(C* a, C* b)
{
return checked(a-b);
}
public static C* PostInc(C* a)
{
return checked(a++);
}
public static C* PostDec(C* a)
{
return checked(a--);
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll);
// NOTE: unsigned addition
verifier.VerifyIL("C.Add_Int1", @"
{
// Code size 12 (0xc)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: conv.i
IL_0003: sizeof ""C""
IL_0009: mul.ovf
IL_000a: add.ovf.un
IL_000b: ret
}");
// NOTE: signed addition
verifier.VerifyIL("C.Add_Int2", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.1
IL_0001: conv.i
IL_0002: sizeof ""C""
IL_0008: mul.ovf
IL_0009: ldarg.0
IL_000a: add.ovf
IL_000b: ret
}");
// NOTE: unsigned addition
verifier.VerifyIL("C.Add_UInt1", @"{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: conv.u8
IL_0003: sizeof ""C""
IL_0009: conv.i8
IL_000a: mul.ovf
IL_000b: conv.i
IL_000c: add.ovf.un
IL_000d: ret
}");
// NOTE: signed addition
verifier.VerifyIL("C.Add_UInt2", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.1
IL_0001: conv.u8
IL_0002: sizeof ""C""
IL_0008: conv.i8
IL_0009: mul.ovf
IL_000a: conv.i
IL_000b: ldarg.0
IL_000c: add.ovf
IL_000d: ret
}");
// NOTE: unsigned addition
verifier.VerifyIL("C.Add_Long1", @"
{
// Code size 13 (0xd)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sizeof ""C""
IL_0008: conv.i8
IL_0009: mul.ovf
IL_000a: conv.i
IL_000b: add.ovf.un
IL_000c: ret
}");
// NOTE: signed addition
verifier.VerifyIL("C.Add_Long2", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.1
IL_0001: sizeof ""C""
IL_0007: conv.i8
IL_0008: mul.ovf
IL_0009: conv.i
IL_000a: ldarg.0
IL_000b: add.ovf
IL_000c: ret
}");
// NOTE: unsigned addition
verifier.VerifyIL("C.Add_ULong1", @"
{
// Code size 13 (0xd)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sizeof ""C""
IL_0008: conv.ovf.u8
IL_0009: mul.ovf.un
IL_000a: conv.u
IL_000b: add.ovf.un
IL_000c: ret
}");
// NOTE: unsigned addition (differs from previous Add_*2's)
verifier.VerifyIL("C.Add_ULong2", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.1
IL_0001: sizeof ""C""
IL_0007: conv.ovf.u8
IL_0008: mul.ovf.un
IL_0009: conv.u
IL_000a: ldarg.0
IL_000b: add.ovf.un
IL_000c: ret
}");
verifier.VerifyIL("C.Sub_Int", @"
{
// Code size 12 (0xc)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: conv.i
IL_0003: sizeof ""C""
IL_0009: mul.ovf
IL_000a: sub.ovf.un
IL_000b: ret
}");
verifier.VerifyIL("C.Sub_UInt", @"
{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: conv.u8
IL_0003: sizeof ""C""
IL_0009: conv.i8
IL_000a: mul.ovf
IL_000b: conv.i
IL_000c: sub.ovf.un
IL_000d: ret
}");
verifier.VerifyIL("C.Sub_Long", @"
{
// Code size 13 (0xd)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sizeof ""C""
IL_0008: conv.i8
IL_0009: mul.ovf
IL_000a: conv.i
IL_000b: sub.ovf.un
IL_000c: ret
}");
verifier.VerifyIL("C.Sub_ULong", @"
{
// Code size 13 (0xd)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sizeof ""C""
IL_0008: conv.ovf.u8
IL_0009: mul.ovf.un
IL_000a: conv.u
IL_000b: sub.ovf.un
IL_000c: ret
}");
verifier.VerifyIL("C.Sub_Ptr", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub
IL_0003: sizeof ""C""
IL_0009: div
IL_000a: conv.i8
IL_000b: ret
}");
verifier.VerifyIL("C.PostInc", @"
{
// Code size 12 (0xc)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: sizeof ""C""
IL_0008: add.ovf.un
IL_0009: starg.s V_0
IL_000b: ret
}");
verifier.VerifyIL("C.PostDec", @"
{
// Code size 12 (0xc)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: sizeof ""C""
IL_0008: sub.ovf.un
IL_0009: starg.s V_0
IL_000b: ret
}");
}
[Fact]
public void CheckedExpression_Optimizer()
{
var source = @"
class C
{
static bool Local()
{
int a = 1;
return checked(-a) != -1;
}
static bool LocalInc()
{
int a = 1;
return checked(-(a++)) != -1;
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Local", @"
{
// Code size 12 (0xc)
.maxstack 2
.locals init (int V_0) //a
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: ldloc.0
IL_0004: sub.ovf
IL_0005: ldc.i4.m1
IL_0006: ceq
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: ret
}
");
verifier.VerifyIL("C.LocalInc", @"
{
// Code size 16 (0x10)
.maxstack 4
.locals init (int V_0) //a
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: ldloc.0
IL_0004: dup
IL_0005: ldc.i4.1
IL_0006: add.ovf
IL_0007: stloc.0
IL_0008: sub.ovf
IL_0009: ldc.i4.m1
IL_000a: ceq
IL_000c: ldc.i4.0
IL_000d: ceq
IL_000f: ret
}
");
}
[Fact]
public void CheckedExpression_IncDec()
{
var source = @"
class C
{
public static int PostInc(int a)
{
return checked(a++);
}
public static int PreInc(int a)
{
return checked(++a);
}
public static int PostDec(int a)
{
return checked(a--);
}
public static int PreDec(int a)
{
return checked(--a);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.PostInc", @"
{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.1
IL_0003: add.ovf
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PreInc", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PostDec", @"
{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.1
IL_0003: sub.ovf
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.PreDec", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
}
[Fact]
public void CheckedExpression_CompoundAssignment()
{
var source = @"
class C
{
public static int Add(int a, int b)
{
return checked(a+=b);
}
public static int Sub(int a, int b)
{
return checked(a-=b);
}
public static int Mul(int a, int b)
{
return checked(a*=b);
}
public static int Div(int a, int b)
{
return checked(a/=b);
}
public static int Rem(int a, int b)
{
return checked(a%=b);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Sub", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Mul", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul.ovf
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
// both checked and unchecked generate the same instruction that checks overflow
verifier.VerifyIL("C.Div", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Rem", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
}
[Fact]
public void Checked_ImplicitConversions_CompoundAssignment()
{
var source = @"
class C
{
public static int Add(short a)
{
return checked(a+=1000);
}
}";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x3e8
IL_0006: add.ovf
IL_0007: conv.ovf.i2
IL_0008: dup
IL_0009: starg.s V_0
IL_000b: ret
}
");
}
[Fact]
public void Checked_ImplicitConversions_IncDec()
{
var source = @"
class C
{
class X
{
public static implicit operator short(X a)
{
return 1;
}
public static implicit operator X(short a)
{
return new X();
}
}
static void PostIncUserDefined(X x)
{
checked { x++; }
}
public static int PostInc(short a)
{
return checked(a++);
}
public static int PreInc(short a)
{
return checked(++a);
}
static short? s = 0;
static short? PostIncNullable()
{
checked { return s++; }
}
}";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.PostIncUserDefined", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""short C.X.op_Implicit(C.X)""
IL_0006: ldc.i4.1
IL_0007: add.ovf
IL_0008: conv.ovf.i2
IL_0009: call ""C.X C.X.op_Implicit(short)""
IL_000e: starg.s V_0
IL_0010: ret
}
");
verifier.VerifyIL("C.PostInc", @"
{
// Code size 8 (0x8)
.maxstack 3
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.1
IL_0003: add.ovf
IL_0004: conv.ovf.i2
IL_0005: starg.s V_0
IL_0007: ret
}
");
verifier.VerifyIL("C.PreInc", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: conv.ovf.i2
IL_0004: dup
IL_0005: starg.s V_0
IL_0007: ret
}
");
verifier.VerifyIL("C.PostIncNullable", @"{
// Code size 48 (0x30)
.maxstack 3
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? C.s""
IL_0005: dup
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""bool short?.HasValue.get""
IL_000e: brtrue.s IL_001b
IL_0010: ldloca.s V_1
IL_0012: initobj ""short?""
IL_0018: ldloc.1
IL_0019: br.s IL_002a
IL_001b: ldloca.s V_0
IL_001d: call ""short short?.GetValueOrDefault()""
IL_0022: ldc.i4.1
IL_0023: add.ovf
IL_0024: conv.ovf.i2
IL_0025: newobj ""short?..ctor(short)""
IL_002a: stsfld ""short? C.s""
IL_002f: ret
}
");
}
[Fact]
public void Checked_ImplicitConversions_ArraySize()
{
var source = @"
class C
{
public static int[] ArraySize(long size)
{
checked
{
return new int[size];
}
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.ArraySize", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i
IL_0002: newarr ""int""
IL_0007: ret
}
");
}
[Fact]
public void Checked_ImplicitConversions_ForEach()
{
var source = @"
class C
{
static void ForEachString()
{
checked
{
foreach (byte b in ""hello"")
{
}
}
}
static void ForEachVector()
{
checked
{
foreach (short b in new int[] {1})
{
}
}
}
static void ForEachMultiDimArray()
{
checked
{
foreach (short b in new int[,] {{1}})
{
}
}
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.ForEachString", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (string V_0,
int V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: br.s IL_0017
IL_000a: ldloc.0
IL_000b: ldloc.1
IL_000c: callvirt ""char string.this[int].get""
IL_0011: conv.ovf.u1.un
IL_0012: pop
IL_0013: ldloc.1
IL_0014: ldc.i4.1
IL_0015: add
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: ldloc.0
IL_0019: callvirt ""int string.Length.get""
IL_001e: blt.s IL_000a
IL_0020: ret
}
");
verifier.VerifyIL("C.ForEachVector", @"
{
// Code size 31 (0x1f)
.maxstack 4
.locals init (int[] V_0,
int V_1)
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: stloc.0
IL_000b: ldc.i4.0
IL_000c: stloc.1
IL_000d: br.s IL_0018
IL_000f: ldloc.0
IL_0010: ldloc.1
IL_0011: ldelem.i4
IL_0012: conv.ovf.i2
IL_0013: pop
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldloc.0
IL_001a: ldlen
IL_001b: conv.i4
IL_001c: blt.s IL_000f
IL_001e: ret
}
");
verifier.VerifyIL("C.ForEachMultiDimArray", @"
{
// Code size 85 (0x55)
.maxstack 5
.locals init (int[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj ""int[*,*]..ctor""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call ""int[*,*].Set""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldc.i4.0
IL_0013: callvirt ""int System.Array.GetUpperBound(int)""
IL_0018: stloc.1
IL_0019: ldloc.0
IL_001a: ldc.i4.1
IL_001b: callvirt ""int System.Array.GetUpperBound(int)""
IL_0020: stloc.2
IL_0021: ldloc.0
IL_0022: ldc.i4.0
IL_0023: callvirt ""int System.Array.GetLowerBound(int)""
IL_0028: stloc.3
IL_0029: br.s IL_0050
IL_002b: ldloc.0
IL_002c: ldc.i4.1
IL_002d: callvirt ""int System.Array.GetLowerBound(int)""
IL_0032: stloc.s V_4
IL_0034: br.s IL_0047
IL_0036: ldloc.0
IL_0037: ldloc.3
IL_0038: ldloc.s V_4
IL_003a: call ""int[*,*].Get""
IL_003f: conv.ovf.i2
IL_0040: pop
IL_0041: ldloc.s V_4
IL_0043: ldc.i4.1
IL_0044: add
IL_0045: stloc.s V_4
IL_0047: ldloc.s V_4
IL_0049: ldloc.2
IL_004a: ble.s IL_0036
IL_004c: ldloc.3
IL_004d: ldc.i4.1
IL_004e: add
IL_004f: stloc.3
IL_0050: ldloc.3
IL_0051: ldloc.1
IL_0052: ble.s IL_002b
IL_0054: ret
}");
}
[Fact]
public void UncheckedExpression_CompoundAssignment()
{
var source = @"
class C
{
public static int Add(int a, int b)
{
return unchecked(a+=b);
}
public static int Sub(int a, int b)
{
return unchecked(a-=b);
}
public static int Mul(int a, int b)
{
return unchecked(a*=b);
}
public static int Div(int a, int b)
{
return unchecked(a/=b);
}
public static int Rem(int a, int b)
{
return unchecked(a%=b);
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.Add", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Sub", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Mul", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
// both checked and unchecked generate the same instruction that checks overflow
verifier.VerifyIL("C.Div", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
verifier.VerifyIL("C.Rem", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem
IL_0003: dup
IL_0004: starg.s V_0
IL_0006: ret
}
");
}
[Fact]
public void CheckedBlock_Conversions()
{
var source = @"
enum E
{
A = 1
}
class C
{
public static uint SByte_UInt(sbyte a)
{
checked { return (uint)a; }
}
public static int UInt_Int(uint a)
{
checked { return (int)a; }
}
public static short Enum_Short(E a)
{
checked { return (short)a; }
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("C.SByte_UInt", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
");
verifier.VerifyIL("C.UInt_Int", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4.un
IL_0002: ret
}
");
verifier.VerifyIL("C.Enum_Short", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
");
}
// Although C# 4.0 specification says that checked context never flows in a lambda,
// the Dev10 compiler implementation always flows the context in, except for
// when the lambda is directly a "parameter" of the checked/unchecked expression.
// For Roslyn we decided to change the spec and always flow the context in.
[Fact]
public void Lambda_Statement()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
checked
{
System.Func<int, int> d1 = delegate(int i)
{
return i + 1; // add_ovf
};
}
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_QueryStmt()
{
var verifier = CompileAndVerify(@"
using System.Linq;
class C
{
static void F()
{
checked
{
var a = from x in new[] { 1 } select x * 2; // mul_ovf
}
}
}
", new[] { SystemCoreRef }).VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: mul.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_QueryExpr()
{
var verifier = CompileAndVerify(@"
using System.Linq;
class C
{
static void F()
{
var a = checked(from x in new[] { 1 } select x * 2); // mul_ovf
}
}
", new[] { SystemCoreRef }).VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: mul.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfAssignment()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d2;
System.Func<int, int> d1 = checked(d2 = delegate(int i)
{
return i + 1; // add_ovf
});
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_Add()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d1 = checked(delegate (int i)
{
return i + 1; // Dev10: add, Roslyn: add_ovf
});
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_Cast()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
var d1 = checked((System.Func<int, int>)delegate (int i)
{
return i + 1; // add_ovf
});
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfCompoundAssignment()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d2 = null;
System.Func<int, int> d1 = checked(d2 += delegate(int i)
{
return i + 1; // add_ovf
});
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfArgument()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(Id(delegate(int i)
{
return i + 1; // add_ovf
}));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfArgument2()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(Id(checked(delegate(int i)
{
return i + 1; // add_ovf
})));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddArgument3()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = unchecked(Id(checked(delegate(int i)
{
return i + 1; // add
})));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfArgument4()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d2;
System.Func<int, int> d1 = unchecked(Id(checked(d2 = checked(delegate(int i)
{
return i + 1; // add_ovf
}))));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfArgument5()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(Id(unchecked(delegate(int i)
{
return i + 1; // add_ovf
})));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddArgument6()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(unchecked(Id(delegate(int i)
{
return i + 1; // add
})));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddArgument7()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(Id(unchecked(Id(delegate(int i)
{
return i + 1; // add
}))));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void Lambda_AddOvfArgument8()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
System.Func<int, int> d1 = checked(Id(unchecked(Id(delegate(int i)
{
return i + 1; // add
}))));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void Lambda_LambdaVsDelegate1()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d1 = checked(delegate(int i) { return i + 1; }); // Dev10: add, Roslyn: add_ovf
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_LambdaVsDelegate2()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d1 = checked(i => { return i + 1; }); // Dev10: add, Roslyn: add_ovf
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_LambdaVsDelegate3()
{
var verifier = CompileAndVerify(@"
class C
{
static void F()
{
System.Func<int, int> d1 = checked(i => i + 1); // Dev10: add, Roslyn: add_ovf
}
}
").VerifyIL("C.<>c.<F>b__0_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void Lambda_NewDelegate1()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
Id(new System.Func<int, int>(i => i + 1));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void Lambda_NewDelegate2()
{
var verifier = CompileAndVerify(@"
class C
{
static System.Func<int, int> Id(System.Func<int, int> x) { return x; }
static void F()
{
Id(checked(new System.Func<int, int>(i => i + 1)));
}
}
").VerifyIL("C.<>c.<F>b__1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ret
}
");
}
[Fact]
public void CheckedOption1()
{
var source = @"
class C
{
public static uint ULong_UInt(ulong a)
{
return (uint)a;
}
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true)).VerifyIL("C.ULong_UInt", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4.un
IL_0002: ret
}
");
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false)).VerifyIL("C.ULong_UInt", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
");
}
[Fact]
public void CheckedOption2()
{
var source = @"
class C
{
public static uint ULong_UInt(ulong a)
{
return unchecked((uint)a);
}
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true)).VerifyIL("C.ULong_UInt", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
");
}
[Fact]
public void CheckedUncheckedNesting()
{
var source = @"
class C
{
public static uint ULong_UInt(ulong a)
{
uint b = (uint)a;
unchecked
{
return b + checked((uint)a - unchecked((uint)a));
}
}
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true)).VerifyIL("C.ULong_UInt", @"
{
// Code size 9 (0x9)
.maxstack 3
IL_0000: ldarg.0
IL_0001: conv.ovf.u4.un
IL_0002: ldarg.0
IL_0003: conv.ovf.u4.un
IL_0004: ldarg.0
IL_0005: conv.u4
IL_0006: sub.ovf.un
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void UncheckedOperatorWithConstantsOfTheSignedIntegralTypes()
{
var source = @"
class Test
{
const int a = unchecked((int)0xFFFFFFFF);
const int b = unchecked((int)0x80000000);
}
";
CompileAndVerify(source);
}
[Fact]
public void UncheckedOperatorInCheckedStatement()
{
// Overflow checking context with use unchecked operator in checked statement
var source = @"
class Program
{
static void Main()
{
int r = 0;
r = int.MaxValue + 1;
checked
{
r = int.MaxValue + 1;
r = unchecked(int.MaxValue + 1);
};
}
}
";
var comp = CreateStandardCompilation(source);
comp.VerifyDiagnostics(
// (7,13): error CS0220: The operation overflows at compile time in checked mode
// r = int.MaxValue + 1;
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (10,17): error CS0220: The operation overflows at compile time in checked mode
// r = int.MaxValue + 1;
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"));
}
[Fact]
public void ExpressionsInUncheckedStatementAreInExplicitlyUncheckedContext()
{
// Expressions which are in unchecked statement are in explicitly unchecked context.
var source = @"
using System;
class Program
{
static void Main()
{
int s2 = int.MaxValue;
int r = 0;
unchecked { r = s2 + 1; };
if (r != int.MinValue)
{
Console.Write(""FAIL"");
}
unchecked { r = int.MaxValue + 1; };
if (r != int.MinValue)
{
Console.Write(""FAIL"");
}
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("Program.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: ldc.i4 0x80000000
IL_000c: beq.s IL_0018
IL_000e: ldstr ""FAIL""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: ldc.i4 0x80000000
IL_001d: ldc.i4 0x80000000
IL_0022: beq.s IL_002e
IL_0024: ldstr ""FAIL""
IL_0029: call ""void System.Console.Write(string)""
IL_002e: ret
}
");
}
[Fact]
public void CheckOnUnaryOperator()
{
var source = @"
class Program
{
static void Main()
{
long test1 = long.MinValue;
long test2 = 0;
try
{
checked
{
test2 = -test1;
}
}
catch (System.OverflowException)
{
System.Console.Write(test2);
}
}
}
";
CompileAndVerify(source, expectedOutput: "0");
}
[Fact]
public void Test_024_16BitSignedInteger()
{
var source = @"
using System;
public class MyClass
{
public static void Main()
{
Int16 f = 0;
var r = checked(f += 32000);
Console.Write(r);
}
}
";
CompileAndVerify(
source,
expectedOutput: "32000");
}
[Fact]
public void AnonymousFunctionExpressionInUncheckedOperator()
{
// Overflow checking context with use anonymous function expression in unchecked operator
var source = @"
class Program
{
delegate int D1(int i);
static void Main()
{
D1 d1;
int r1 = 0;
d1 = unchecked(delegate (int i) { r1 = int.MaxValue + 1; r1++; return checked(int.MaxValue + 1); });
d1 = unchecked(i => int.MaxValue + 1 + checked(0 + 0));
d1 = unchecked(i => 0 + 0 + checked(int.MaxValue + 1));
d1 = unchecked(d1 = delegate (int i) { r1 = int.MaxValue + 1; return checked(int.MaxValue + 1); });
d1 = unchecked(d1 = i => int.MaxValue + 1 + checked(0 + 0));
d1 = unchecked(d1 = i => 0 + 0 + checked(int.MaxValue + 1));
d1 = unchecked(new D1(delegate (int i) { r1 = int.MaxValue + 1; return checked(int.MaxValue + 1); }));
d1 = unchecked(new D1(i => int.MaxValue + 1 + checked(0 + 0)));
d1 = unchecked(new D1(i => 0 + 0 + checked(int.MaxValue + 1)));
}
}
";
var comp = CreateStandardCompilation(source);
comp.VerifyDiagnostics(
// (9,81): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(delegate (int i) { r1 = int.MaxValue + 1; return checked(int.MaxValue + 1); });
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (11,45): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(i => 0 + 0 + checked(int.MaxValue + 1));
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (12,86): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(d1 = delegate (int i) { r1 = int.MaxValue + 1; return checked(int.MaxValue + 1); });
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (14,50): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(d1 = i => 0 + 0 + checked(int.MaxValue + 1));
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (15,88): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(new D1(delegate (int i) { r1 = int.MaxValue + 1; return checked(int.MaxValue + 1); }));
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"),
// (17,52): error CS0220: The operation overflows at compile time in checked mode
// d1 = unchecked(new D1(i => 0 + 0 + checked(int.MaxValue + 1)));
Diagnostic(ErrorCode.ERR_CheckedOverflow, "int.MaxValue + 1"));
}
[WorkItem(648109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/648109")]
[Fact]
public void CheckedExpressionWithDecimal()
{
var source = @"
class M
{
void F()
{
var r = checked(decimal.MaxValue + 1);
// error should be reported regardless checked or not
// decimal math has not concept of ""checked""
var r1 = decimal.MaxValue + 1;
}
}";
var comp = CreateStandardCompilation(source);
comp.VerifyDiagnostics(
// (6,25): error CS0463: Evaluation of the decimal constant expression failed
// var r = checked(decimal.MaxValue + 1);
Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1").WithLocation(6, 25),
// (10,18): error CS0463: Evaluation of the decimal constant expression failed
// var r1 = decimal.MaxValue + 1;
Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1").WithLocation(10, 18)
);
}
[WorkItem(543894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543894"), WorkItem(543924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543924")]
[Fact]
public void CheckedOperatorOnEnumOverflow()
{
var source = @"
using System;
class Test
{
enum Esb { max = int.MaxValue }
static void Main()
{
Esb e = Esb.max;
try
{
var i = checked(e++);
Console.WriteLine(""FAIL"");
}
catch (OverflowException)
{
Console.WriteLine(""PASS"");
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "PASS");
}
[WorkItem(529263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529263")]
[Fact]
public void CheckedOperatorOnLambdaExpr()
{
var source = @"
using System;
class Program
{
static void Main()
{
int max = int.MaxValue;
try
{
Func<int> f1 = checked(() => max + 1);
Console.WriteLine(f1());
Console.WriteLine(""FAIL"");
}
catch (OverflowException)
{
Console.WriteLine(""PASS"");
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "PASS");
}
[Fact, WorkItem(543981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543981")]
public void CheckedOperatorOnUnaryExpression()
{
var source = @"
using System;
class Program
{
static int Main()
{
int result = 0;
int normi = 10;
if (checked(-normi) != -10)
{
result += 1;
}
int maxi = int.MaxValue;
if (checked(-maxi) != int.MinValue + 1)
{
result += 1;
}
try
{
int mini = int.MinValue;
var x = checked(-mini);
result += 1;
}
catch (OverflowException)
{
Console.Write(""OV-"");
}
Console.WriteLine(result);
return result;
}
}
";
CompileAndVerify(
source,
expectedOutput: "OV-0");
}
[Fact, WorkItem(543983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543983")]
public void CheckedStatementWithCompoundAssignment()
{
var source = @"
using System;
public class MyClass
{
public static void Main()
{
short goo = 0;
try
{
for (int i = 0; i < 2; i++)
{
checked { goo += 32000; }
Console.Write(goo);
}
}
catch (OverflowException)
{
Console.WriteLine(""OV"");
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "32000OV");
}
[Fact, WorkItem(546872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546872")]
public void CheckPostIncrementOnBaseProtectedClassMember()
{
var source = @"
using System;
class Base1
{
protected int memberee=0;
protected int xyz {
get;
set;
}
protected int this[int number]
{
get { return 0; }
set { }
}
}
class Derived2 : Base1
{
public void inc()
{
base.memberee++;
base.xyz++;
base[0]++;
}
}
";
var verifier = CompileAndVerify(source);
verifier.VerifyIL("Derived2.inc", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld ""int Base1.memberee""
IL_0007: ldc.i4.1
IL_0008: add
IL_0009: stfld ""int Base1.memberee""
IL_000e: ldarg.0
IL_000f: call ""int Base1.xyz.get""
IL_0014: stloc.0
IL_0015: ldarg.0
IL_0016: ldloc.0
IL_0017: ldc.i4.1
IL_0018: add
IL_0019: call ""void Base1.xyz.set""
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: call ""int Base1.this[int].get""
IL_0025: stloc.0
IL_0026: ldarg.0
IL_0027: ldc.i4.0
IL_0028: ldloc.0
IL_0029: ldc.i4.1
IL_002a: add
IL_002b: call ""void Base1.this[int].set""
IL_0030: ret
}
");
}
[Fact]
public void CheckedConversionsInExpressionTrees_Implicit()
{
// char
CheckedConversionInExpressionTree_Implicit("char", "char", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("char", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("char", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("char", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("char", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("char", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("char", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("char", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("char", "double", ConvertMethod.Convert);
// sbyte
CheckedConversionInExpressionTree_Implicit("sbyte", "sbyte", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("sbyte", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("sbyte", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("sbyte", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("sbyte", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("sbyte", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("sbyte", "double", ConvertMethod.Convert);
// byte
CheckedConversionInExpressionTree_Implicit("byte", "byte", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("byte", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("byte", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("byte", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("byte", "double", ConvertMethod.Convert);
// short
CheckedConversionInExpressionTree_Implicit("short", "short", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("short", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("short", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("short", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("short", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("short", "double", ConvertMethod.Convert);
// ushort
CheckedConversionInExpressionTree_Implicit("ushort", "ushort", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("ushort", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("ushort", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("ushort", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("ushort", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("ushort", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("ushort", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("ushort", "double", ConvertMethod.Convert);
// int
CheckedConversionInExpressionTree_Implicit("int", "int", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("int", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("int", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("int", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("int", "double", ConvertMethod.Convert);
// uint
CheckedConversionInExpressionTree_Implicit("uint", "uint", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("uint", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("uint", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Implicit("uint", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("uint", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("uint", "double", ConvertMethod.Convert);
// long
CheckedConversionInExpressionTree_Implicit("long", "long", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("long", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("long", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("long", "double", ConvertMethod.Convert);
// ulong
CheckedConversionInExpressionTree_Implicit("ulong", "ulong", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("ulong", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("ulong", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("ulong", "double", ConvertMethod.Convert);
// decimal
CheckedConversionInExpressionTree_Implicit("decimal", "decimal", ConvertMethod.None);
// float
CheckedConversionInExpressionTree_Implicit("float", "float", ConvertMethod.None);
CheckedConversionInExpressionTree_Implicit("float", "double", ConvertMethod.Convert);
// double
CheckedConversionInExpressionTree_Implicit("double", "double", ConvertMethod.None);
// object
CheckedConversionInExpressionTree_Implicit("int", "object", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Implicit("string", "object", ConvertMethod.None);
// Nullable<>
CheckedConversionInExpressionTree_Implicit("int", "int?", "arg => F(Convert(arg))");
CheckedConversionInExpressionTree_Implicit("int", "long?", "arg => F(ConvertChecked(ConvertChecked(arg)))");
}
[Fact]
[WorkItem(18459, "https://github.com/dotnet/roslyn/issues/18459")]
public void CheckedConversionsInExpressionTrees_ImplicitTuple()
{
CheckedConversionInExpressionTree_Implicit("(int, int)", "(int, int)?", ConvertMethod.Convert);
}
[Fact]
public void CheckedConversionsInExpressionTrees_Explicit()
{
// char
CheckedConversionInExpressionTree_Explicit("char", "char", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("char", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("char", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("char", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("char", "double", ConvertMethod.Convert);
// sbyte
CheckedConversionInExpressionTree_Explicit("sbyte", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "sbyte", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("sbyte", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("sbyte", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("sbyte", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("sbyte", "double", ConvertMethod.Convert);
// byte
CheckedConversionInExpressionTree_Explicit("byte", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "byte", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("byte", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("byte", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("byte", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("byte", "double", ConvertMethod.Convert);
// short
CheckedConversionInExpressionTree_Explicit("short", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "short", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("short", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("short", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("short", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("short", "double", ConvertMethod.Convert);
// ushort
CheckedConversionInExpressionTree_Explicit("ushort", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "ushort", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ushort", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ushort", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ushort", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ushort", "double", ConvertMethod.Convert);
// int
CheckedConversionInExpressionTree_Explicit("int", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "int", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("int", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("int", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("int", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("int", "double", ConvertMethod.Convert);
// uint
CheckedConversionInExpressionTree_Explicit("uint", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "uint", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("uint", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("uint", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("uint", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("uint", "double", ConvertMethod.Convert);
// long
CheckedConversionInExpressionTree_Explicit("long", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "long", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("long", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("long", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("long", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("long", "double", ConvertMethod.Convert);
// ulong
CheckedConversionInExpressionTree_Explicit("ulong", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("ulong", "ulong", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ulong", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ulong", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("ulong", "double", ConvertMethod.Convert);
// decimal
CheckedConversionInExpressionTree_Explicit("decimal", "char", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "sbyte", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "byte", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "short", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "ushort", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "int", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "uint", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "long", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "ulong", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("decimal", "double", ConvertMethod.Convert);
// float
CheckedConversionInExpressionTree_Explicit("float", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("float", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("float", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("float", "double", ConvertMethod.Convert);
// double
CheckedConversionInExpressionTree_Explicit("double", "char", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "sbyte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "byte", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "short", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "ushort", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "int", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "uint", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "long", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "ulong", ConvertMethod.ConvertChecked);
CheckedConversionInExpressionTree_Explicit("double", "decimal", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("double", "float", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("double", "double", ConvertMethod.Convert);
// enum
CheckedConversionInExpressionTree_Explicit("E", "int", ConvertMethod.ConvertChecked, "enum E { }");
CheckedConversionInExpressionTree_Explicit("int", "E", ConvertMethod.ConvertChecked, "enum E { }");
CheckedConversionInExpressionTree_Explicit("E", "int", ConvertMethod.ConvertChecked, "enum E : short { }");
CheckedConversionInExpressionTree_Explicit("int", "E", ConvertMethod.ConvertChecked, "enum E : short { }");
// object
CheckedConversionInExpressionTree_Explicit("int", "object", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("object", "int", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("string", "object", ConvertMethod.Convert);
CheckedConversionInExpressionTree_Explicit("object", "string", ConvertMethod.Convert);
// Nullable<>
CheckedConversionInExpressionTree_Explicit("int", "byte?", "arg => ConvertChecked(arg)");
CheckedConversionInExpressionTree_Explicit("int", "int?", "arg => ConvertChecked(arg)");
CheckedConversionInExpressionTree_Explicit("int", "long?", "arg => ConvertChecked(ConvertChecked(arg))");
}
[Fact]
public void CheckedConversionsInExpressionTrees_ExplicitTuple()
{
CheckedConversionInExpressionTree_Explicit("(int, int)", "(int, int)?", ConvertMethod.Convert);
}
private enum ConvertMethod
{
None,
Convert,
ConvertChecked,
}
private void CheckedConversionInExpressionTree_Implicit(string fromType, string toType, ConvertMethod expectedMethod, string additionalTypes = "")
{
var source = CheckedConversionInExpressionTree_ImplicitSource(fromType, toType, additionalTypes);
var compilation = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.ReleaseExe, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef });
string expectedOutput;
switch (expectedMethod)
{
default:
expectedOutput = "arg => F(arg)";
break;
case ConvertMethod.Convert:
expectedOutput = "arg => F(Convert(arg))";
break;
case ConvertMethod.ConvertChecked:
expectedOutput = "arg => F(ConvertChecked(arg))";
break;
}
var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
// Since Expression.ConvertChecked can generate a Checked result
// (rather than ConvertChecked), verify the correct method was called.
VerifyConversionInExpressionTreeIL(verifier.TestData.GetMethodData("C.Main").GetMethodIL(), expectedMethod);
}
private void CheckedConversionInExpressionTree_Implicit(string fromType, string toType, string expectedOutput)
{
var source = CheckedConversionInExpressionTree_ImplicitSource(fromType, toType, additionalTypes: "");
var compilation = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
private static string CheckedConversionInExpressionTree_ImplicitSource(string fromType, string toType, string additionalTypes)
{
return
$@"using System;
using System.Linq.Expressions;
{additionalTypes}
class C
{{
static {toType} F({toType} arg) => arg;
static void Main()
{{
Expression<Func<{fromType}, {toType}>> e = arg => checked(F(arg));
Console.WriteLine(e);
}}
}}";
}
private void CheckedConversionInExpressionTree_Explicit(string fromType, string toType, ConvertMethod expectedMethod, string additionalTypes = "")
{
var source = CheckedConversionInExpressionTree_ExplicitSource(fromType, toType, additionalTypes);
var compilation = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.ReleaseExe, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef });
string expectedOutput;
switch (expectedMethod)
{
default:
expectedOutput = "arg => arg";
break;
case ConvertMethod.Convert:
expectedOutput = "arg => Convert(arg)";
break;
case ConvertMethod.ConvertChecked:
expectedOutput = "arg => ConvertChecked(arg)";
break;
}
var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
// Since Expression.ConvertChecked can generate a Checked result
// (rather than ConvertChecked), verify the correct method was called.
VerifyConversionInExpressionTreeIL(verifier.TestData.GetMethodData("C.Main").GetMethodIL(), expectedMethod);
}
private void CheckedConversionInExpressionTree_Explicit(string fromType, string toType, string expectedOutput)
{
var source = CheckedConversionInExpressionTree_ExplicitSource(fromType, toType, additionalTypes: "");
var compilation = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
private static string CheckedConversionInExpressionTree_ExplicitSource(string fromType, string toType, string additionalTypes)
{
return
$@"using System;
using System.Linq.Expressions;
{additionalTypes}
class C
{{
static void Main()
{{
Expression<Func<{fromType}, {toType}>> e = arg => checked(({toType})arg);
Console.WriteLine(e);
}}
}}";
}
private static void VerifyConversionInExpressionTreeIL(string actualIL, ConvertMethod expectedMethod)
{
Assert.Equal(
actualIL.Contains($"System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, "),
expectedMethod == ConvertMethod.Convert);
Assert.Equal(
actualIL.Contains($"System.Linq.Expressions.Expression.ConvertChecked(System.Linq.Expressions.Expression, "),
expectedMethod == ConvertMethod.ConvertChecked);
}
}
}
| 27.851958 | 175 | 0.597714 | [
"Apache-2.0"
] | ElanHasson/roslyn | src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenCheckedTests.cs | 77,514 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/vsstyle.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum BORDER_NOSCROLLSTATES
{
LBPSN_NORMAL = 1,
LBPSN_FOCUSED = 2,
LBPSN_HOT = 3,
LBPSN_DISABLED = 4,
}
}
| 29.375 | 145 | 0.693617 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/vsstyle/BORDER_NOSCROLLSTATES.cs | 472 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class DayOfWeek
{
static void Main()
{
var n =int.Parse(Console.ReadLine());
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
if (n >= 1 && n <=7)
{
Console.WriteLine(days[n-1]);
}
else
{
Console.WriteLine("Invalid Day!");
}
}
} | 21.565217 | 105 | 0.540323 | [
"MIT"
] | V-Uzunov/Soft-Uni-Education | 02.ProgrammingFundamentalsC#/06.ArraysAndList/01.Arrays/01.DayOfWeek/DayOfWeek.cs | 498 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Doraemon.Data.Migrations
{
public partial class RemoveModmailBlockProperty : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsModmailBlocked",
table: "GuildUsers");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsModmailBlocked",
table: "GuildUsers",
type: "boolean",
nullable: false,
defaultValue: false);
}
}
}
| 27.92 | 71 | 0.580229 | [
"MIT"
] | n-Ultima/Doraemon | Doraemon.Data/Migrations/20210925012147_RemoveModmailBlockProperty.cs | 700 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RTS
{
public static class Globals
{
//scroll and camera
public static float ScrollSpeed { get { return 2; } }
public static float RotateSpeed { get { return 200; } }
public static int ScrollWidth { get { return 20; } }
public static float MinCameraHeight { get { return 10; } }
//public static float MaxCameraHeight { get { return 150; } } //default
public static float MaxCameraHeight { get { return 450; } } //testing
public static float RotateAmount { get { return 20; } }
//mouse clicks
private static Vector3 invalidPosition = new Vector3(-99999, -99999, -99999);
public static Vector3 InvalidPosition { get { return invalidPosition; } }
//popmenu
public static float POP_MENU_BUTTON_HEIGHT { get { return 35; } }
public static float POP_MENU_WIDTH { get { return 80; } }
public static float POP_MENU_BUTTON_BORDER { get { return 5; } }
public static float POP_MENU_LIST_WIDTH { get { return 100f; } }
//IconPanel
public static float ICON_PANEL_UNIT_OFFSET { get { return 30; } }
public static float ICON_PANEL_UNIT_WIDTH { get { return 20; } }
public static float ICON_PANEL_BUILDING_OFFSET { get { return 45; } }
public static float ICON_PANEL_BUILDING_WIDTH { get { return 45; } }
//units
public static float UNIT_PREGNANCY_CYCLE_PROGRESS { get { return 0.05f; } }
//public static float UNIT_HUNGER_CYCLE_INCREASE { get { return 0.001f; } } //too low
public static float UNIT_HUNGER_CYCLE_INCREASE { get { return 0.01f; } } //this is a good value with hunger_value = 10f, default
//public static float UNIT_HUNGER_CYCLE_INCREASE { get { return 0.05f; } } //for testing
//public static float UNIT_HUNGER_CYCLE_INCREASE { get { return 0.1f; } } //for testing
//public static float UNIT_HUNGRY_DAMAGE_TAKEN { get { return 0.0f; } } // for testing
public static float UNIT_HUNGRY_DAMAGE_TAKEN { get { return 0.05f; } } // default
//public static float UNIT_HUNGRY_DAMAGE_TAKEN { get { return 0.1f; } } //for testing
//the value of 1 Food in terms of unit hunger
public static float UNIT_FOOD_HUNGER_VALUE { get { return 10f; } }
public static Dictionary<GameTypes.UnitStatType, float> UNIT_DEFAULT_FLOAT_STATS = new Dictionary<GameTypes.UnitStatType, float>()
{
{GameTypes.UnitStatType.InteractionRange, 1f},
{GameTypes.UnitStatType.Attack, 1f},
{GameTypes.UnitStatType.ExchangeSpeed, 1f},
{GameTypes.UnitStatType.MoveSpeed, 3f},
{GameTypes.UnitStatType.RotateSpeed, 3f},
{GameTypes.UnitStatType.ProcreateChance, 10f},
{GameTypes.UnitStatType.ConstructSpeed, 1f},
{GameTypes.UnitStatType.WorkSpeed, 1f}
};
public static Dictionary<GameTypes.UnitStatType, int> UNIT_DEFAULT_INT_STATS = new Dictionary<GameTypes.UnitStatType, int>()
{
{GameTypes.UnitStatType.InventoryCapacity, 10}
};
public static List<GameTypes.EquipmentSlots> DEFAULT_UNIT_EQUIPMENT_SLOTS = new List<GameTypes.EquipmentSlots>()
{
{GameTypes.EquipmentSlots.Head},
{GameTypes.EquipmentSlots.Back},
{GameTypes.EquipmentSlots.Feet},
{GameTypes.EquipmentSlots.HandR},
{GameTypes.EquipmentSlots.HandL},
{GameTypes.EquipmentSlots.Vehicle},
};
//maps
public static int REGION_MAP_WIDTH { get { return 300; } } //default, for now
//public static int REGION_MAP_WIDTH { get { return 900; } } //testing, a bit large
public static Dictionary<Vector2, GameTypes.MapType> DEFAULT_MAP_GRID_START { get {
Dictionary<Vector2,GameTypes.MapType> d = new Dictionary<Vector2,GameTypes.MapType>();
//add the locations and types here
d.Add (new Vector2(0,0), GameTypes.MapType.GrassPlain);
//d.Add (new Vector2(0,-1), GameTypes.MapType.GrassPlain);
return d;
} }
//resources
public static int RESOURCE_DEFAULT_AMOUNT { get { return 1000; } }
//rates that they appear in regions
public static Dictionary<GameTypes.ItemType, float> RESOURCE_REGION_DROP_RATES = new Dictionary<GameTypes.ItemType, float>()
{
{GameTypes.ItemType.Unknown, 0f},
{GameTypes.ItemType.Food, 1f},
{GameTypes.ItemType.Wood, 1f},
{GameTypes.ItemType.Stone, 1f}, //default 0.5f
{GameTypes.ItemType.Copper, 0.2f},
{GameTypes.ItemType.Tin, 0.2f}
};
//number of groups of this resource
public static Dictionary<GameTypes.ItemType, int> RESOURCE_N_GROUPS = new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Unknown, 0},
{GameTypes.ItemType.Food, Mathf.CeilToInt(REGION_MAP_WIDTH / 74f)},
{GameTypes.ItemType.Wood, Mathf.CeilToInt(REGION_MAP_WIDTH / 74f)},
{GameTypes.ItemType.Stone, Mathf.CeilToInt(REGION_MAP_WIDTH / 100f)},
{GameTypes.ItemType.Copper, Mathf.CeilToInt(REGION_MAP_WIDTH / 100f)},
{GameTypes.ItemType.Tin, Mathf.CeilToInt(REGION_MAP_WIDTH / 100f)}
};
//number of resources in a group, scales with region width
public static Dictionary<GameTypes.ItemType, int> RESOURCE_N_PER_GROUPS = new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Unknown, 0},
{GameTypes.ItemType.Food, Mathf.CeilToInt(REGION_MAP_WIDTH / 40f)},
{GameTypes.ItemType.Wood, Mathf.CeilToInt(REGION_MAP_WIDTH / 10f)},
{GameTypes.ItemType.Stone, Mathf.CeilToInt(REGION_MAP_WIDTH / 60f)},
{GameTypes.ItemType.Copper, Mathf.CeilToInt(REGION_MAP_WIDTH / 60f)},
{GameTypes.ItemType.Tin, Mathf.CeilToInt(REGION_MAP_WIDTH / 60f)},
};
//the max spread of the groups of resources
public static Dictionary<GameTypes.ItemType, float> RESOURCE_GROUP_MAX_SPREADS = new Dictionary<GameTypes.ItemType, float>()
{
{GameTypes.ItemType.Unknown, 0f},
{GameTypes.ItemType.Food, REGION_MAP_WIDTH / 15f},
{GameTypes.ItemType.Wood, REGION_MAP_WIDTH / 7f},
{GameTypes.ItemType.Stone, REGION_MAP_WIDTH / 30f},
{GameTypes.ItemType.Copper, REGION_MAP_WIDTH / 30f},
{GameTypes.ItemType.Tin, REGION_MAP_WIDTH / 30f}
};
//Materials needed for Construction types
public static Dictionary<GameTypes.ItemType, int> TOWNHALL_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 50}
}; } }
public static Dictionary<GameTypes.ItemType, int> HOUSE_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 30}
}; } }
public static Dictionary<GameTypes.ItemType, int> STOCKPILE_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 100}
}; }}
public static Dictionary<GameTypes.ItemType, int> FARM_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 30}
}; }}
public static Dictionary<GameTypes.ItemType, int> SPEARWORKSHOP_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 30}
}; }}
public static Dictionary<GameTypes.ItemType, int> HANDCARTWORKSHOP_CONSTRUCTION_MATERIALS { get { return new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 30}
}; }}
//Materials needed for Item Production types
public static Dictionary<GameTypes.ItemType, int> STONESPEAR_PRODUCTION_MATERIALS = new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 1},
{GameTypes.ItemType.Stone, 1}
};
//Materials needed for Item Production types
public static Dictionary<GameTypes.ItemType, int> HANDCART_PRODUCTION_MATERIALS = new Dictionary<GameTypes.ItemType, int>()
{
{GameTypes.ItemType.Wood, 10}
};
//Equip item globals
//the slot that the item goes into
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICHAT_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.Head};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICBOOTS_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.Feet};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICCLUB_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.HandR};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICSWORD_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.HandR};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICHAMMER_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.HandR};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_MAGICBAG_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.Back};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_STONESPEAR_SLOTS = new List<GameTypes.EquipmentSlots>() { GameTypes.EquipmentSlots.HandR};
public static List<GameTypes.EquipmentSlots> EQUIP_ITEM_HANDCART_SLOTS = new List<GameTypes.EquipmentSlots>()
{ GameTypes.EquipmentSlots.Vehicle, GameTypes.EquipmentSlots.HandR, GameTypes.EquipmentSlots.HandL };
//the equip attributes of the item when equipped
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICHAT_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.WorkSpeed, 50} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICCLUB_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.Attack, 50} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICBOOTS_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.MoveSpeed, 50} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICSWORD_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.Attack, 50} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICHAMMER_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.ConstructSpeed, 50} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_MAGICBAG_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.InventoryCapacity, 500} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_STONESPEAR_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{ {GameTypes.UnitStatType.Attack, 4} };
public static Dictionary<GameTypes.UnitStatType, float> EQUIP_ITEM_HANDCART_EQUIP_EFFECTS = new Dictionary<GameTypes.UnitStatType, float>()
{
{GameTypes.UnitStatType.MoveSpeed, -1},
{GameTypes.UnitStatType.InventoryCapacity, 50}
};
//mapping between unit stat type and the display text
public static Dictionary<GameTypes.UnitStatType, string> UNIT_STATS_DISPLAY_TEXT = new Dictionary<GameTypes.UnitStatType, string>()
{
{GameTypes.UnitStatType.Unknown, "Unknw"},
{GameTypes.UnitStatType.InteractionRange, "Rng"},
{GameTypes.UnitStatType.Attack, "Att"},
{GameTypes.UnitStatType.ExchangeSpeed, "ExchSpd"},
{GameTypes.UnitStatType.MoveSpeed, "Spd"},
{GameTypes.UnitStatType.RotateSpeed, "RotSpd"},
{GameTypes.UnitStatType.ProcreateChance, "Sx%"},
{GameTypes.UnitStatType.ConstructSpeed, "ConstrSpd"},
{GameTypes.UnitStatType.InventoryCapacity, "InvCap"},
{GameTypes.UnitStatType.WorkSpeed, "WrkSpd"},
};
//PRODUCTION BUILDING CREATE ITEMS
public static GameTypes.ItemType SPEARWORKSHOP_PRODUCTION_ITEM = GameTypes.ItemType.StoneSpear;
public static GameTypes.ItemType HANDCARTWORKSHOP_PRODUCTION_ITEM = GameTypes.ItemType.HandCart;
}
public static class UI
{
//selection box
private static GUISkin selectBoxSkin;
public static GUISkin SelectBoxSkin { get { return selectBoxSkin; } }
public static void StoreSelectBoxSkin(GUISkin skin)
{
selectBoxSkin = skin;
}
}
public static class ObjectManager
{
//private members
private static GameObjectList mGameObjectList;
//visible entity list
private static List<Entity> mVisibleEntities = new List<Entity>();
public static void addVisibleEntity(Entity ent)
{
foreach (Entity inent in mVisibleEntities)
{
if (inent == ent)
{
Debug.LogError("This entity is already in the visible list.");
return;
}
}
mVisibleEntities.Add(ent);
}
public static void removeVisibleEntity(Entity ent)
{
bool in_list = false;
foreach (Entity inent in mVisibleEntities)
{
if (inent == ent)
in_list = true;
}
if (in_list == false)
{
Debug.LogError("This entity is not in the visible list.");
return;
}
mVisibleEntities.Remove(ent);
}
public static List<Entity> getVisibleEntities()
{
return mVisibleEntities;
}
//get functions
public static void setGameObjectList(GameObjectList objectList)
{
mGameObjectList = objectList;
}
public static GameObject getAction(string act_name)
{
return mGameObjectList.getAction(act_name);
}
public static GameObject getItem(string item_name)
{
return mGameObjectList.getItem(item_name);
}
public static GameObject getMenu(string menu_name)
{
return mGameObjectList.getMenu(menu_name);
}
public static GameObject getResource(string res_name)
{
return mGameObjectList.getResource(res_name);
}
public static GameObject getUnit(string unit_name)
{
return mGameObjectList.getUnit(unit_name);
}
public static GameObject getBuilding(string b_name)
{
GameObject go = mGameObjectList.getBuilding(b_name);
if (!go)
Debug.LogError(string.Format("Building name {0} not found", b_name));
return go;
}
public static GameObject getConstruction(string c_name)
{
return mGameObjectList.getConstruction(c_name);
}
public static GameObject getMap(string m_name)
{
return mGameObjectList.getMap(m_name);
}
public static GameObject getRegion(string r_name)
{
return mGameObjectList.getRegion(r_name);
}
public static GameObject getTown(string t_name)
{
return mGameObjectList.getTown(t_name);
}
//init action functions
public static Attack initAttack(Transform parent)
{
Attack move = GameObject.Instantiate(getAction("Attack"), parent).GetComponent<Attack>();
return move;
}
public static Movement initMove(Transform parent)
{
Movement move = GameObject.Instantiate(getAction("Movement"),parent).GetComponent<Movement>();
return move;
}
public static Wait initWait(Transform parent)
{
Wait wt = GameObject.Instantiate(getAction("Wait"), parent).GetComponent<Wait>();
return wt;
}
public static Exchange initExchange(Transform parent)
{
Exchange ex = GameObject.Instantiate(getAction("Exchange"), parent).GetComponent<Exchange>();
return ex;
}
public static Garrison initGarrison(Transform parent)
{
Garrison gar = GameObject.Instantiate(getAction("Garrison"), parent).GetComponent<Garrison>();
return gar;
}
public static Procreate initProcreate(Transform parent)
{
Procreate proc = GameObject.Instantiate(getAction("Procreate"), parent).GetComponent<Procreate>();
return proc;
}
public static Collect initCollect(Transform parent)
{
Collect coll = GameObject.Instantiate(getAction("Collect"), parent).GetComponent<Collect>();
return coll;
}
public static Construct initConstruct(Transform parent)
{
Construct constr = GameObject.Instantiate(getAction("Construct"), parent).GetComponent<Construct>();
return constr;
}
public static Eat initEat(Transform parent)
{
Eat eat = GameObject.Instantiate(getAction("Eat"), parent).GetComponent<Eat>();
return eat;
}
public static Work initWork(Transform parent)
{
Work wr = GameObject.Instantiate(getAction("Work"), parent).GetComponent<Work>();
return wr;
}
public static Explore initExplore(Transform parent)
{
Explore exp = GameObject.Instantiate(getAction("Explore"),parent).GetComponent<Explore>();
return exp;
}
public static Travel initTravel(Transform parent)
{
Travel trav = GameObject.Instantiate(getAction("Travel"),parent).GetComponent<Travel>();
return trav;
}
//init item function
public static Item initItem(GameTypes.ItemType type, Transform parent)
{
Item item = GameObject.Instantiate(getItem(type.ToString()), parent).GetComponent<Item>();
item.setAmount(0);
item.setType(type);
return item;
}
//init unit functions
public static Unit initUnit( Vector3 pos, GameTypes.GenderType gender, Town town)
{
Unit unit = GameObject.Instantiate(getUnit("Unit"), town.gameObject.transform).GetComponent<Unit>();
unit.setGender(gender);
unit.gameObject.transform.position = pos;
town.addEntity("units", unit);
return unit;
}
//init building functions
public static Building initBuilding(Vector3 pos, GameTypes.BuildingType bt, Town town)
{
Building b = GameObject.Instantiate(getBuilding(bt.ToString()), town.gameObject.transform).GetComponent<Building>();
b.gameObject.transform.position = pos;
b.mType = bt;
town.addEntity("buildings", b);
return b;
}
//init Construction function
public static Construction initConstruction(Vector3 pos, GameTypes.BuildingType bt, Town town)
{
Construction constro = GameObject.Instantiate(getConstruction("Construction"), town.gameObject.transform).GetComponent<Construction>();
constro.gameObject.transform.position = pos;
constro.mType = bt;
town.addEntity("constructions", constro);
return constro;
}
//init map function
public static Map initMap(Vector3 pos, GameTypes.MapType mt, Region reg, int seed)
{
Map map = GameObject.Instantiate(getMap(mt.ToString()), reg.gameObject.transform).GetComponent<Map>();
map.gameObject.transform.position = pos;
map.mType = mt;
reg.addMap(map);
map.mSeed = seed;
return map;
}
//init Region function
public static Region initRegion(Vector2 grid_pos, GameTypes.MapType mt, WorldManager wm, int seed)
{
Region reg = GameObject.Instantiate(getRegion("Region"), wm.gameObject.transform).GetComponent<Region>();
reg.setGridPos(grid_pos);
reg.mType = mt;
reg.mSeed = seed;
//wm.addRegion(reg);
return reg;
}
//init Town function
public static Town initTown(Region reg)
{
Debug.Log(reg.mName);
Town tw = GameObject.Instantiate(getTown("Town"), reg.GetComponentInChildren<Towns>().gameObject.transform).GetComponent<Town>();
//reg.mType = mt;
//reg.mSeed = seed;
//wm.addRegion(reg);
tw._setRegion(reg);
//tw.addEntity("buildings",townhall);
return tw;
}
//init Resource function
public static Resource initResource(Vector3 pos, GameTypes.ItemType type, Region reg)
{
Resource res = GameObject.Instantiate(getResource(type.ToString()), reg.getResourceObject().transform).GetComponent<Resource>();
res.gameObject.transform.position = pos;
res.mType = type;
reg.addEntity("resources",res);
res.mAmount = Globals.RESOURCE_DEFAULT_AMOUNT;
return res;
}
}
public static class GameTypes
{
//unknown must be first
public enum ItemType { Unknown, Food, Wood, Stone, Copper, Tin, MagicHat, MagicBoots, MagicClub, MagicSword, MagicHammer, MagicBag, StoneSpear, HandCart };
//public enum ItemType {Unknown, Food};
//unknown must be first
public enum BuildingType { Unknown, TownHall, House, Stockpile, Farm, SpearWorkshop, HandCartWorkshop };
//unknown must be first
public enum GenderType { Unknown, Male, Female };
//unknown must be first
public enum MapType { Unknown, GrassPlain};
//unknown must be first
public enum IconType { Unknown, Caution};
//unknown must be first
public enum EquipmentSlots { Unknown, Head, Back, Feet, HandR, HandL, Vehicle };
//unknown must be first
public enum UnitStatType { Unknown, InteractionRange, Attack, ExchangeSpeed, MoveSpeed, RotateSpeed, ProcreateChance, ConstructSpeed, InventoryCapacity, WorkSpeed };
}
}
| 41.867446 | 167 | 0.683816 | [
"MIT"
] | kevinkraft/RTS_4 | Assets/Globals/RTS.cs | 21,480 | 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 SteamAppClient.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.483871 | 151 | 0.582788 | [
"MIT"
] | MegaRoks/SteamAppClient | SteamAppClient/Properties/Settings.Designer.cs | 1,071 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
using CollectionAssert = NUnit.Framework.CollectionAssert;
using Description = NUnit.Framework.DescriptionAttribute;
using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext;
using CsQuery;
using CsQuery.HtmlParser;
using CsQuery.Utility;
namespace CsQuery.Tests.HtmlParser
{
[TestFixture, TestClass]
public class Html5Compliance : CsQueryTest
{
[Test, TestMethod]
public void TabsInClassNames()
{
string html = "<html><body><div class=\"class1\tclass2\"></div></body></html>";
var dom = CQ.Create(html);
var div = dom["div"].FirstElement();
Assert.AreEqual(2, div.Classes.Count());
Assert.IsTrue(div.HasClass("class1"));
Assert.IsTrue(div.HasClass("class2"));
}
[Test, TestMethod]
public void NewLinesInClassNames()
{
var html = "<html><body><div class=\"class1" + System.Environment.NewLine + "class2 class3\r\n\t class4\"></div></body></html>";
var dom = CQ.Create(html);
var div = dom["div"].FirstElement();
Assert.AreEqual(4, div.Classes.Count());
Assert.IsTrue(div.HasClass("class1"));
Assert.IsTrue(div.HasClass("class4"));
}
[Test, TestMethod]
public void AutoCloseTwoTagsInARow()
{
var html = @" <table id=table-uda>
<thead>
<tr>
<th>Attribute
<th>Setter Condition
<tbody><tr><td><dfn id=dom-uda-protocol title=dom-uda-protocol><code>protocol</code></dfn>
<td><a href=#url-scheme title=url-scheme><scheme></a>
</tr></table>";
var dom = CQ.Create(html);
Assert.AreEqual(1, dom["tbody"].Length);
Assert.AreEqual("TABLE", dom["tbody"][0].ParentNode.NodeName);
}
[Test, TestMethod]
public void AutoCreateTableTags()
{
var html = @"<table id=table-uda>
<tr>
<th>Attribute
<th>Setter Condition
<tr><td><dfn id=dom-uda-protocol title=dom-uda-protocol><code>protocol</code></dfn>
<td><a href=#url-scheme title=url-scheme><scheme></a>
</tr></table>";
var dom = CQ.Create(html);
// should not create wrapper
Assert.AreEqual(0, dom["body"].Length);
Assert.AreEqual(0, dom["head"].Length);
AutoCreateTests(dom);
dom = CQ.CreateDocument(html);
// should create wrapper
Assert.AreEqual(1, dom["body"].Length);
Assert.AreEqual(1, dom["html"].Length);
Assert.AreEqual(1, dom["head"].Length);
Assert.AreEqual(Arrays.Create("HEAD", "BODY"), dom["html > *"].Select(item => item.NodeName));
AutoCreateTests(dom);
}
protected void AutoCreateTests(CQ dom)
{
Assert.AreEqual(1, dom["tbody"].Length);
Assert.AreEqual(2, dom["th"].Length);
Assert.AreEqual(2, dom["tr"].Length);
Assert.AreEqual("TABLE", dom["tbody"][0].ParentNode.NodeName);
var len = dom["body"].Length > 0 ?
dom["body *"].Length : dom["*"].Length;
Assert.AreEqual(11, len);
}
[Test, TestMethod]
public void AutoCreateHtmlBody()
{
string test = @"<html>
<head>
<script type=""text/javascript"">lf={version: 2064750,baseUrl: '/',helpHtml: '<a class=""email"" href=""mailto:xxxxx@xxxcom"">email</a>',prefs: { pageSize: 0}};
lf.Scripts={""crypt"":{""path"":""/scripts/thirdp/sha512.min.2009762.js"",""nameSpace"":""Sha512""}};
</script><link rel=""icon"" type=""image/x-icon"" href=""/favicon.ico"">
<title>Title</title>
<script type=""text/javascript"" src=""/scripts/thirdp/jquery-1.7.1.min.2009762.js""></script>
<script type=""text/javascript"">var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxx1']);
_gaq.push(['_trackPageview']);
</script>
</head>
<body>
<script type=""text/javascript"">
alert('done');
</script>";
var dom = CQ.CreateDocument(test);
Assert.AreEqual(4, dom["script"].Length);
}
[Test, TestMethod]
public void AutoCreateHead()
{
string test = @"<html>
<script id=script1 type=""text/javascript"" src=""stuff""></script>
<div id=div1>This should be in the body.</div>";
var dom = CQ.CreateDocument(test);
Assert.AreEqual(dom["#script1"][0], dom["head > :first-child"][0]);
Assert.AreEqual(dom["#div1"][0], dom["body > :first-child"][0]);
CollectionAssert.AreEqual(Arrays.String("HEAD", "BODY"), dom["html"].Children().NodeNames());
}
/// <summary>
/// In this test, it's the opposite of AutoCreateHead - b/c the first el is not a metadata tag it should
/// cause BODY to be created not head.
/// </summary>
[Test, TestMethod]
public void AutoCreateBody()
{
string test = @"<html>
<div id=div1>This should be in the body.</div>
<script id=script1 type=""text/javascript"" src=""stuff""></script>";
var dom = CQ.CreateDocument(test);
Assert.AreEqual(0, dom["head"].Children().Length);
Assert.AreEqual(2, dom["body"].Children().Length);
Assert.AreEqual(dom["#div1"][0], dom["body > :first-child"][0]);
CollectionAssert.AreEqual(Arrays.String("HEAD", "BODY"), dom["html"].Children().NodeNames());
}
/// <summary>
/// Issue #16: odd results with non-space whitespace in tag openers
/// </summary>
[Test, TestMethod]
public void NewLinesInTags()
{
string test = @"<table
border
=0 cellspacing=
""2"" cellpadding=""2"" width=""100%""><span"+(char)10+"id=test></span></table>";
var dom = CQ.CreateFragment(test);
// this also tests how the mis-nested span is handled; chrome moves it before the table.
var output = dom.Render();
Assert.AreEqual(
@"<span id=""test""></span><table border=""0"" cellspacing=""2"" cellpadding=""2"" width=""100%""></table>",
output);
}
}
}
| 33.665025 | 172 | 0.550629 | [
"MIT"
] | 842549829/CsQuery | source/CsQuery.Tests/HtmlParser/Html5Compliance.cs | 6,836 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.