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
namespace Aquarius.Weixin.Entity.Pay { /// <summary> /// 场景信息 /// </summary> public class SceneInfo { /// <summary> /// 门店id /// (MaxLength:32) /// </summary> public string id { get; set; } /// <summary> /// 门店名称 /// (MaxLength:64) /// </summary> public string name { get; set; } /// <summary> /// 门店行政区划码 /// (MaxLength:6) /// </summary> public string area_code { get; set; } /// <summary> /// 门店详细地址 /// (MaxLength:128) /// </summary> public string address { get; set; } #region override public override string ToString() { if(string.IsNullOrEmpty(id) && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(area_code) && string.IsNullOrEmpty(address)) { return null; } return $"{{\"id\":\"{id}\",\"name\":\"{name}\",\"area_code\":\"{area_code}\",\"address\":\"{address}\"}}"; } #endregion } }
24.2
138
0.455464
[ "MIT" ]
Weidaicheng/Aquarius.Weixin
src/Aquarius.Weixin/Aquarius.Weixin/Entity/Pay/SceneInfo.cs
1,137
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum CameraState { ORBIT, ORBIT_TO_PLANE, PLANE, PLANE_TO_ORBIT } public class CameraController : MonoBehaviour { public GameObject center; public float acceleration = 1.0f; public float speed = 1.0f; public float EPS = 0.01f; private bool dragX = true; private bool dragY = true; private float speedX = 0.0f; private float speedY = 0.0f; private float angleX = 0.0f; private float angleY = 0.0f; public float limitYMin = -60.0f; public float limitYMax = 60.0f; public float distance = 3.0f; private bool dragZoom = true; public float speedZoom = 0.0f; public float zoomMin = 1.0f; public float zoomMax = 5.0f; public bool planeZoomDrag = true; public float planeZoomAcceleration = 1.0f; public float planeZoomSpeed = 0.0f; public float planeZoom = 3.0f; public float planeZoomMin = 2.0f; public float planeZoomMax = 5.0f; public CameraState state = CameraState.ORBIT; private Vector3 orbitPosition; private Quaternion orbitRotation; private Vector3 planePosition; private Quaternion planeRotation; private Transform parent = null; private float interpolation = 1.0f; public bool lockRotation = true; private Quaternion lockQuaternion; public GameObject light; public float _scrollSensitivity = -400.0f; private float _mouseX; private float _mouseY; public float _mouseXSensitivity = 0.2f; public float _mouseYSensitivity = 0.2f; private bool _rotateToTarget = false; private Vector3 _cameraDir; private Vector3 _beaconDir; private float _prevDot = 0.0f; private float _prevDirX = 30.0f; private float _prevDirY = 30.0f; public void Start() { angleX = transform.eulerAngles.y; angleY = transform.eulerAngles.x; lockQuaternion = center.transform.rotation; } public void Lock() { lockRotation = true; lockQuaternion = center.transform.rotation * lockQuaternion; } public void Unlock() { lockRotation = false; lockQuaternion = Quaternion.Inverse(center.transform.rotation) * lockQuaternion; } public void GotoAirport(Airport airport) { if (lockRotation) { Unlock(); } _beaconDir = new Vector3(0.0f, 0.0f, 0.0f) - airport.Location.ToSphericalCartesian(); _beaconDir.Normalize(); _rotateToTarget = true; } private static float ClampAngle(ref float speed, float angle, float min, float max) { if (angle < -360.0f) angle += 360.0f; if (angle > 360.0f) angle -= 360.0f; if (angle < min) { speed = 0.0f; } if (angle > max) { speed = 0.0f; } return Mathf.Clamp(angle, min, max); } private static float ClampZoom(ref float speed, float zoom, float min, float max) { if (zoom < min) { speed = 0.0f; } if (zoom > max) { speed = 0.0f; } return Mathf.Clamp(zoom, min, max); } private void DragPlane() { if (planeZoomDrag) { if (planeZoomSpeed > EPS) { planeZoomSpeed -= planeZoomAcceleration * Time.deltaTime; } else if (planeZoomSpeed < -EPS) { planeZoomSpeed += planeZoomAcceleration * Time.deltaTime; } else { planeZoomSpeed = 0.0f; } } } private void Drag() { if (dragX) { if (speedX > EPS) { speedX -= acceleration * Time.deltaTime; } else if (speedX < -EPS) { speedX += acceleration * Time.deltaTime; } else { speedX = 0.0f; } } if (dragY) { if (speedY > EPS) { speedY -= acceleration * Time.deltaTime; } else if (speedY < -EPS) { speedY += acceleration * Time.deltaTime; } else { speedY = 0.0f; } } if (dragZoom) { if (speedZoom > EPS) { speedZoom -= acceleration * Time.deltaTime; } else if (speedZoom < -EPS) { speedZoom += acceleration * Time.deltaTime; } else { speedZoom = 0.0f; } } } void ProcessOrbit() { dragX = true; dragY = true; dragZoom = true; if (Input.GetKey(KeyCode.D)) { speedX -= acceleration * Time.deltaTime; dragX = false; } if (Input.GetKey(KeyCode.A)) { speedX += acceleration * Time.deltaTime; dragX = false; } if (Input.GetKey(KeyCode.S)) { speedY -= acceleration * Time.deltaTime; dragY = false; } if (Input.GetKey(KeyCode.W)) { speedY += acceleration * Time.deltaTime; dragY = false; } if (Input.GetKey(KeyCode.Q)) { speedZoom += acceleration * Time.deltaTime; dragZoom = false; } if (Input.GetKey(KeyCode.E)) { speedZoom -= acceleration * Time.deltaTime; dragZoom = false; } if (Input.GetMouseButton(0)) { float dx = Input.mousePosition.x - _mouseX; _mouseX = Input.mousePosition.x; speedX += acceleration * _mouseXSensitivity * Time.deltaTime * dx; if (Mathf.Abs(speedX) > 0.001f) { dragX = false; } } if (Input.GetMouseButton(0)) { float dy = _mouseY - Input.mousePosition.y; _mouseY = Input.mousePosition.y; speedY += acceleration * _mouseYSensitivity * Time.deltaTime * dy; if (Mathf.Abs(speedY) > 0.001f) { dragY = false; } } if (Mathf.Abs(Input.GetAxis("Mouse ScrollWheel")) > 0.0f) { speedZoom += acceleration * _scrollSensitivity * Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime; dragZoom = false; } Drag(); speedX = Mathf.Clamp(speedX, -speed, speed); speedY = Mathf.Clamp(speedY, -speed, speed); speedZoom = Mathf.Clamp(speedZoom, -speed, speed); angleX += speedX; angleY += speedY; distance += speedZoom * Time.deltaTime; angleY = ClampAngle(ref speedY, angleY, limitYMin, limitYMax); if (lockRotation) { orbitRotation = lockQuaternion * Quaternion.Euler(angleY, angleX, 0.0f); } else { orbitRotation = center.transform.rotation * lockQuaternion * Quaternion.Euler(angleY, angleX, 0.0f); } distance = ClampZoom(ref speedZoom, distance, zoomMin, zoomMax); orbitPosition = orbitRotation * new Vector3(0.0f, 0.0f, -distance) + center.transform.position; } void ProcessPlane() { planeZoomDrag = true; if (Input.GetKey(KeyCode.Q)) { planeZoomSpeed += planeZoomAcceleration * Time.deltaTime; planeZoomDrag = false; } if (Input.GetKey(KeyCode.E)) { planeZoomSpeed -= planeZoomAcceleration * Time.deltaTime; planeZoomDrag = false; } DragPlane(); planeZoomSpeed = Mathf.Clamp(planeZoomSpeed, -speed, speed); planeZoom += planeZoomSpeed * Time.deltaTime; planeZoom = ClampZoom(ref planeZoomSpeed, planeZoom, planeZoomMin, planeZoomMax); planeRotation = parent.rotation * Quaternion.Euler(0.0f, -90.0f, 0.0f); planePosition = parent.rotation * Quaternion.Euler(0.0f, 90.0f, 0.0f) * new Vector3(0.0f, 0.0f, planeZoom); } public void LateUpdate() { switch (state) { case CameraState.ORBIT: ProcessOrbit(); transform.rotation = orbitRotation; transform.position = orbitPosition; interpolation = 1.0f; break; case CameraState.ORBIT_TO_PLANE: parent = transform.parent; ProcessOrbit(); ProcessPlane(); interpolation -= Time.deltaTime; if (interpolation <= 0.0f) { state = CameraState.PLANE; } transform.rotation = Quaternion.Slerp(planeRotation, orbitRotation, interpolation); transform.position = Vector3.Lerp(planePosition, orbitPosition, interpolation); break; case CameraState.PLANE: ProcessPlane(); transform.rotation = planeRotation; transform.position = planePosition; interpolation = 1.0f; break; case CameraState.PLANE_TO_ORBIT: ProcessOrbit(); ProcessPlane(); interpolation -= Time.deltaTime; if (interpolation <= 0.0f) { state = CameraState.ORBIT; } transform.rotation = Quaternion.Slerp(orbitRotation, planeRotation, interpolation); transform.position = Vector3.Lerp(orbitPosition, planePosition, interpolation); break; } _mouseX = Input.mousePosition.x; _mouseY = Input.mousePosition.y; _cameraDir = new Vector3(0.0f, 0.0f, 0.0f) - transform.position; _cameraDir.Normalize(); _cameraDir = Quaternion.Inverse(center.transform.rotation) * _cameraDir; if (_rotateToTarget) { float dot = Vector3.Dot(_cameraDir, _beaconDir); Vector3 t0 = new Vector3(_cameraDir.x, 0.0f, _cameraDir.z); Vector3 t1 = new Vector3(_beaconDir.x, 0.0f, _beaconDir.z); t0.Normalize(); t1.Normalize(); float dot2 = Vector3.Dot(t0, t1); Vector3 n = Vector3.Cross(t0, t1); float det = Vector3.Dot(new Vector3(0.0f, 1.0f, 0.0f), n); if (_beaconDir.y > _cameraDir.y + 0.005f) { _prevDirY = -1.0f; } else if (_beaconDir.y < _cameraDir.y - 0.005f) { _prevDirY = 1.0f; } else { _prevDirY = 0.0f; } float angle = Mathf.Atan2(det, dot); if (angle > 0.005f) { _prevDirX = 1.0f; } else if (angle < -0.005f) { _prevDirX = -1.0f; } else { _prevDirX = 0.0f; } if (dot > 0.999f) { _rotateToTarget = false; } else if (dot > 0.995f && dot == _prevDot) { _rotateToTarget = false; } else { angleX += _prevDirX * 30.0f * Time.deltaTime; angleY += _prevDirY * 30.0f * Time.deltaTime; } _prevDot = dot; Debug.Log(Vector3.Dot(_cameraDir, _beaconDir) + " " + angle); } } }
25.989011
115
0.512474
[ "MIT" ]
pavelkouril/ld40
Assets/Scripts/Camera/CameraController.cs
11,827
C#
using System.Reflection; 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("AWSSDK.MediaLive")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.104.3")]
46.875
226
0.752667
[ "Apache-2.0" ]
costleya/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/MediaLive/Properties/AssemblyInfo.cs
1,500
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18052 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AllGreen.Runner.WPF.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; } } } }
35.612903
152
0.567029
[ "MIT" ]
gstamac/AllGreen
src/AllGreen.Runner.WPF/Properties/Settings.Designer.cs
1,106
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 namespace DotNetNuke.Modules.Journal.Controls { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Modules.Journal.Components; using DotNetNuke.Services.Journal; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Tokens; [DefaultProperty("Text")] [ToolboxData("<{0}:JournalListControl runat=server></{0}:JournalListControl>")] public class JournalListControl : WebControl { [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings portalSettings { get { return PortalController.Instance.GetCurrentPortalSettings(); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UserInfo userInfo { get { return UserController.Instance.GetCurrentUserInfo(); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int JournalId { get { if (HttpContext.Current != null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["jid"])) { return Convert.ToInt32(HttpContext.Current.Request.QueryString["jid"]); } return Null.NullInteger; } } public int ProfileId { get; set; } public int ModuleId { get; set; } public int SocialGroupId { get; set; } public int PageSize { get; set; } public int CurrentIndex { get; set; } protected override void Render(HtmlTextWriter output) { if (this.Enabled) { if (this.CurrentIndex < 0) { this.CurrentIndex = 0; } JournalParser jp = new JournalParser(this.portalSettings, this.ModuleId, this.ProfileId, this.SocialGroupId, this.userInfo) { JournalId = this.JournalId }; output.Write(jp.GetList(this.CurrentIndex, this.PageSize)); } } } }
31.122222
171
0.613709
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/Modules/Journal/JournalListControl.cs
2,803
C#
// Copyright (c) CSA, NJUST. All rights reserved. // Licensed under the Mozilla license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseIgnore : MonoBehaviour, ICanvasRaycastFilter { public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) { return false; } // Use this for initialization void Start() { } // Update is called once per frame void Update() { } }
20.259259
105
0.694698
[ "MPL-2.0" ]
NJUST-CSA-Develop-Group/The-11th-TuringCup
src/Project/Assets/Scrpit/UI/MouseIgnore.cs
549
C#
using System; using System.IO; using System.Linq; using Ela; using Ela.Linking; using Elide.CodeEditor.Infrastructure; using Elide.CodeEditor.Views; using Elide.Core; using Elide.ElaCode.ObjectModel; using Elide.Environment; using Ela.Parsing; namespace Elide.ElaCode { public sealed class ElaCodeParser : ICodeParser<ElaAst> { public ElaCodeParser() { } public ElaAst Parse(string source, Document doc, IBuildLogger logger) { try { return InternalParse(source, doc, logger); } catch (ElaException ex) { var msg = new MessageItem(MessageItemType.Error, ex.Message, doc, 0, 0); logger.WriteMessages(new MessageItem[] { msg }, m => true); return null; } } private ElaAst InternalParse(string source, Document doc, IBuildLogger logger) { logger.WriteBuildInfo("Ela", ElaVersionInfo.Version); var parser = new ElaParser(); var res = parser.Parse(new StringBuffer(source));//doc.FileInfo == null ? new ModuleFileInfo(doc.Title) : doc.FileInfo.ToModuleFileInfo()); var messages = res.Messages.Take(100).ToList(); logger.WriteMessages(messages.Select(m => new MessageItem( m.Type == MessageType.Error ? MessageItemType.Error : (m.Type == MessageType.Warning ? MessageItemType.Warning : MessageItemType.Information), String.Format("ELA{0}: {1}", m.Code, m.Message), m.File == null || !new FileInfo(m.File.FullName).Exists ? doc : new VirtualDocument(new FileInfo(m.File.FullName)), m.Line, m.Column) { Tag = m.Code }) , m => true); return res.Success ? new ElaAst(res.Program) : null; } public IApp App { get; set; } } }
34.65
163
0.545455
[ "MIT" ]
vorov2/ela
Elide/Elide.ElaCode/ElaCodeParser.cs
2,081
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using System.Collections; using UnityEngine.UI; namespace HoloToolkit.Examples.Prototyping { /// <summary> /// CycleStatusDisplay shows the current index and array length (i/l) of a CycleBase component /// Works with TextMesh or UI Text /// </summary> public class CycleStatusDisplay : MonoBehaviour { [Tooltip("A GameObject containing a component that impliments ICycle")] public GameObject CycleHost; private ICycle mCycleHost; private TextMesh mTextMesh; private Text mText; // Use this for initialization void Awake() { if(CycleHost == null) { CycleHost = this.gameObject; Debug.Log("CycleHost was set to self by default"); } mTextMesh = GetComponent<TextMesh>(); mText = GetComponent<Text>(); if (mTextMesh == null && mText == null) { Debug.LogError("There are no Text Components on this <GameObject:" + this.gameObject.name + ">"); } mCycleHost = CycleHost.GetComponent<ICycle>(); } /// <summary> /// Update the status of the ICycle component /// </summary> void Update() { if (mTextMesh != null && mCycleHost != null) { mTextMesh.text = (mCycleHost.Index + 1) + "/" + (mCycleHost.GetLastIndex() + 1); } if (mText != null && mCycleHost != null) { mText.text = (mCycleHost.Index + 1) + "/" + (mCycleHost.GetLastIndex() + 1); } } } }
29.967213
112
0.558534
[ "MIT" ]
FlorianJa/BeamLite-Unity
Assets/HoloToolkit-Examples/Prototyping/Scripts/CycleStatusDisplay.cs
1,830
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace toDoList.Class { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
37
113
0.583012
[ "Apache-2.0" ]
ggraur/toDoList
Class/BundleConfig.cs
1,297
C#
using System; namespace OzricEngine.logic { /// <summary> /// A named input or output, with a current value. /// </summary> public class Pin { public string name { get; set; } public ValueType type { get; set; } public Value value { get; set; } public Pin(string name, ValueType type, Value value = null) { this.name = name; this.type = type; this.value = value; } private void SetValue(Scalar scalar) { switch (type) { case ValueType.Scalar: value = scalar; return; case ValueType.Color: value = new ColorRGB(1, 1, 1, scalar.value); return; case ValueType.OnOff: value = new OnOff(scalar.value > 0); return; default: throw new Exception($"Don't know how to assign Scalar to {type}"); } } private void SetValue(ColorValue color) { switch (type) { case ValueType.Scalar: value = new Scalar(color.brightness); return; case ValueType.Color: value = color; return; case ValueType.OnOff: value = new OnOff(color.brightness > 0); return; default: throw new Exception($"Don't know how to assign Color to {type}"); } } private void SetValue(OnOff onOff) { switch (type) { case ValueType.Scalar: value = new Scalar(onOff.value ? 1 : 0); return; case ValueType.Color: value = new ColorRGB(1,1,1, onOff.value ? 1 : 0); return; case ValueType.OnOff: value = onOff; return; default: throw new Exception($"Don't know how to assign Color to {type}"); } } private void SetValue(Mode mode) { switch (type) { case ValueType.Mode: value = mode; return; default: throw new Exception($"Don't know how to assign Mode to {type}"); } } public void SetValue(Value value) { switch (value) { case Scalar scalar: SetValue(scalar); return; case ColorValue Color: SetValue(Color); return; case OnOff onOff: SetValue(onOff); return; case Mode mode: SetValue(mode); return; default: throw new Exception($"Don't know how to assign {value.GetType().Name}"); } } } }
28.601626
93
0.37436
[ "Apache-2.0" ]
jchown/ozric
OzricEngine/nodes/Pin.cs
3,518
C#
using System; using System.Collections.Generic; using System.Text; using Nebula.CoreLibrary.Shared; namespace Nebula.Membership { public class Role : EntityBase { public string Key { get; set; } public string Description { get; set; } public virtual ICollection<UserGroupRole> UserGroupRoles { get; set; } } }
21.8125
78
0.687679
[ "MIT" ]
fatihmert93/NebulaFramework
Nebula.Membership/Role.cs
351
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using System.Xml.Serialization; using System.Xml; [XmlRoot("PartCollection")] public class PartDatabase { [XmlArray("Parts")] [XmlArrayItem("Part")] public List<Part> parts = new List<Part>(); public static PartDatabase LoadPartData() { FileStream fs = new FileStream(Application.dataPath + "/StreamingAssets/XML/data.xml", FileMode.Open); XmlSerializer serializer = new XmlSerializer(typeof(PartDatabase)); PartDatabase parts = serializer.Deserialize(fs) as PartDatabase; fs.Close(); return parts; } }
24.384615
110
0.741325
[ "MIT" ]
Mr-Tibberz/Parker-JR-Project
Parker_DAGD_340/Assets/_scripts/PartDatabase.cs
636
C#
namespace CubularServer.Game { public interface IFood : IID, IPoint3D { } }
14.666667
42
0.647727
[ "MIT" ]
ivanpfeff/cubular
cubular-server/CubularServer/Game/IFood.cs
90
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Net.Http; using Microsoft.TestCommon; namespace System.Web.OData.Formatter { public class ODataMessageWrapperTest { [Fact] public void ResolveUrl_ThrowsArgumentNull_PayloadUri() { var message = new ODataMessageWrapper(); Assert.ThrowsArgumentNull( () => message.ResolveUrl(new Uri("http://localhost"), null), "payloadUri"); } [Fact] public void ResolveUrl_ReturnsNull_IfNoContentIdInUri() { var message = new ODataMessageWrapper(); Uri uri = message.ResolveUrl(new Uri("http://localhost"), new Uri("/values", UriKind.Relative)); Assert.Null(uri); } [Fact] public void ResolveUrl_ReturnsOriginalUri_IfContentIdCannotBeResolved() { StringContent content = new StringContent(String.Empty); var message = new ODataMessageWrapper(new MemoryStream(), content.Headers); Uri uri = message.ResolveUrl(new Uri("http://localhost"), new Uri("$1", UriKind.Relative)); Assert.Equal("$1", uri.OriginalString); } [Fact] public void ResolveUrl_ResolvesUriWithContentId() { StringContent content = new StringContent(String.Empty); Dictionary<string, string> contentIdMapping = new Dictionary<string, string> { {"1", "http://localhost/values(1)"}, {"11", "http://localhost/values(11)"}, }; var message = new ODataMessageWrapper(new MemoryStream(), content.Headers, contentIdMapping); Uri uri = message.ResolveUrl(new Uri("http://localhost"), new Uri("$1", UriKind.Relative)); Assert.Equal("http://localhost/values(1)", uri.OriginalString); } } }
35.017241
133
0.614476
[ "Apache-2.0" ]
Darth-Fx/AspNetMvcStack
OData/test/System.Web.OData.Test/OData/Formatter/ODataMessageWrapperTest.cs
2,033
C#
using UnityEngine; #if UNITY_2021_2_OR_NEWER using UnityEngine.TerrainTools; #else using UnityEngine.Experimental.TerrainAPI; #endif namespace sc.terrain.layersampler { [ExecuteInEditMode] [RequireComponent(typeof(Terrain))] public class TerrainLayerComponent : MonoBehaviour { public TerrainLayerData data; public Terrain terrain; /// <summary> /// Whenever texture painting data changes on the terrain, re-bake the material data. /// </summary> [Tooltip("Whenever texture painting data changes on the terrain, re-bake the material data.")] public bool autoBake = true; void Reset() { terrain = GetComponent<Terrain>(); CreateDataAsset(); Bake(); } private void OnEnable() { TerrainCallbacks.textureChanged += OnSplatmapModified; #if TMS_DEV Bake(); #endif } private void OnDisable() { TerrainCallbacks.textureChanged -= OnSplatmapModified; } private void OnSplatmapModified(Terrain targetTerrain, string textureName, RectInt texelregion, bool synced) { if (autoBake && synced && targetTerrain == terrain) { DataComposer.BakeArea(terrain, data, texelregion); } } /// <summary> /// Create a new (and empty) data asset to bake the material weights to. Use this only at runtime, since the data won't persist. /// Requires calling the "Bake" method afterwards... /// </summary> [ContextMenu("Create data asset (saves with scene)")] public void CreateDataAsset() { data = (TerrainLayerData)ScriptableObject.CreateInstance(typeof(TerrainLayerData)); data.name = this.name + "_LayerData"; } /// <summary> /// Creates a cell for every splatmap texel, and samples the weight of every splatmap channel to an array /// </summary> [ContextMenu("Bake")] public void Bake() { if(data) DataComposer.Bake(terrain, data); } } }
29.972973
136
0.58927
[ "MIT" ]
staggartcreations/UnityTerrainLayerSampler
Runtime/TerrainLayerComponent.cs
2,218
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.imm.Model.V20170906 { public class CreateSetResponse : AcsResponse { private string requestId; private string setId; private string setName; private string createTime; private string modifyTime; private int? faceCount; private int? imageCount; private int? videoCount; private int? videoLength; public string RequestId { get { return requestId; } set { requestId = value; } } public string SetId { get { return setId; } set { setId = value; } } public string SetName { get { return setName; } set { setName = value; } } public string CreateTime { get { return createTime; } set { createTime = value; } } public string ModifyTime { get { return modifyTime; } set { modifyTime = value; } } public int? FaceCount { get { return faceCount; } set { faceCount = value; } } public int? ImageCount { get { return imageCount; } set { imageCount = value; } } public int? VideoCount { get { return videoCount; } set { videoCount = value; } } public int? VideoLength { get { return videoLength; } set { videoLength = value; } } } }
15.503268
63
0.592749
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/CreateSetResponse.cs
2,372
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("MiniRender")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MiniRender")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("2a255ebd-0925-4b24-9a85-8bb8d797c9c1")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.351351
56
0.714286
[ "MIT" ]
asheigithub/MiniRenderer
MiniRender/Properties/AssemblyInfo.cs
1,273
C#
// ====================================================================== // // filename : IImporter.cs // description : // // created by 雪雁 at 2019-09-11 13:51 // 文档官网:https://docs.xin-lai.com // 公众号教程:麦扣聊技术 // QQ群:85318032(编程交流) // Blog:http://www.cnblogs.com/codelove/ // // ====================================================================== using System.Collections.Generic; using System.Threading.Tasks; using Magicodes.ExporterAndImporter.Core.Models; namespace Magicodes.ExporterAndImporter.Core { /// <summary> /// 导入 /// </summary> public interface IImporter { /// <summary> /// 生成导入模板 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> Task<ExportFileInfo> GenerateTemplate<T>(string fileName) where T : class, new(); /// <summary> /// 生成导入模板 /// </summary> /// <typeparam name="T"></typeparam> /// <returns>二进制字节</returns> Task<byte[]> GenerateTemplateBytes<T>() where T : class, new(); /// <summary> /// 导入模型验证数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <param name="labelingFilePath">标注文件路径</param> /// <returns></returns> Task<ImportResult<T>> Import<T>(string filePath, string labelingFilePath = null) where T : class, new(); } }
31.25
112
0.486667
[ "MIT" ]
ExcaliOne/Magicodes.IE
src/Magicodes.ExporterAndImporter.Core/IImporter.cs
1,622
C#
using System; using NAudio.CoreAudioApi; using VoiceRecorder.Model; namespace VoiceRecorder.AudioEngine.MP3RecorderImpl { /// <summary> /// The class Microphone is an adapter on MMDevice. /// </summary> internal class Microphone : IDevice { public Microphone(MMDevice device) { Device = device; } /// <summary> /// The audio device name. /// </summary> public string Name { get => Device.FriendlyName; set => throw new NotImplementedException(); } /// <summary> /// The nested device. /// </summary> public MMDevice Device { get; private set; } } }
22.40625
55
0.550907
[ "MIT" ]
ArgishtyAyvazyan/VoiceRecorder
VoiceRecorder/AudioEngine/MP3RecorderImpl/Microphone.cs
719
C#
// Copyright (c) 2019 Jean-Philippe Bruyère <jp_bruyere@hotmail.com> // // This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) using System; using Vulkan; using static Vulkan.Vk; namespace vke { public class PresentQueue : Queue { public readonly VkSurfaceKHR Surface; public PresentQueue (Device _dev, VkQueueFlags requestedFlags, VkSurfaceKHR _surface, float _priority = 0.0f) { dev = _dev; priority = _priority; Surface = _surface; qFamIndex = searchQFamily (requestedFlags); dev.queues.Add (this); } uint searchQFamily (VkQueueFlags requestedFlags) { //search for dedicated Q for (uint i = 0; i < dev.phy.QueueFamilies.Length; i++) { if (dev.phy.QueueFamilies[i].queueFlags == requestedFlags && dev.phy.GetPresentIsSupported (i, Surface)) return i; } //search Q having flags for (uint i = 0; i < dev.phy.QueueFamilies.Length; i++) { if ((dev.phy.QueueFamilies[i].queueFlags & requestedFlags) == requestedFlags && dev.phy.GetPresentIsSupported (i, Surface)) return i; } throw new Exception (string.Format ("No Queue with flags {0} found", requestedFlags)); } public void Present (VkPresentInfoKHR present) { Utils.CheckResult (vkQueuePresentKHR (handle, ref present)); } public void Present (SwapChain swapChain, VkSemaphore wait) { VkPresentInfoKHR present = VkPresentInfoKHR.New(); uint idx = swapChain.currentImageIndex; VkSwapchainKHR sc = swapChain.Handle; present.swapchainCount = 1; present.pSwapchains = sc.Pin(); present.waitSemaphoreCount = 1; present.pWaitSemaphores = wait.Pin(); present.pImageIndices = idx.Pin(); vkQueuePresentKHR (handle, ref present); sc.Unpin (); wait.Unpin (); idx.Unpin (); } } public class Queue { internal VkQueue handle; internal Device dev; public Device Dev => dev; VkQueueFlags flags => dev.phy.QueueFamilies[qFamIndex].queueFlags; public uint qFamIndex; public uint index;//index in queue family public float priority; protected Queue () { } public Queue (Device _dev, VkQueueFlags requestedFlags, float _priority = 0.0f) { dev = _dev; priority = _priority; qFamIndex = searchQFamily (requestedFlags); dev.queues.Add (this); } /// <summary> /// End command recording, submit, and wait queue idle /// </summary> public void EndSubmitAndWait (PrimaryCommandBuffer cmd, bool freeCommandBuffer = false) { cmd.End (); Submit (cmd); WaitIdle (); if (freeCommandBuffer) cmd.Free (); } public void Submit (PrimaryCommandBuffer cmd, VkSemaphore wait = default, VkSemaphore signal = default, Fence fence = null) { cmd.Submit (handle, wait, signal, fence); } public void WaitIdle () { Utils.CheckResult (vkQueueWaitIdle (handle)); } uint searchQFamily (VkQueueFlags requestedFlags) { //search for dedicated Q for (uint i = 0; i < dev.phy.QueueFamilies.Length; i++) { if (dev.phy.QueueFamilies[i].queueFlags == requestedFlags) return i; } //search Q having flags for (uint i = 0; i < dev.phy.QueueFamilies.Length; i++) { if ((dev.phy.QueueFamilies[i].queueFlags & requestedFlags) == requestedFlags) return i; } throw new Exception (string.Format ("No Queue with flags {0} found", requestedFlags)); } internal void updateHandle () { vkGetDeviceQueue (dev.VkDev, qFamIndex, index, out handle); } } }
34.698276
139
0.589814
[ "MIT" ]
Shawdooow/vke.net
vke/src/base/Queue.cs
4,028
C#
using Heroes.Models; using Heroes.Models.AbilityTalents; using System; using System.IO; using System.Text.Json; namespace Heroes.Icons.DataDocument { /// <summary> /// Base class reader for unit and hero related data. /// </summary> public abstract class UnitDataBase : DataDocumentBase, IDataDocument { /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="jsonDataFilePath">The JSON data to parse.</param> protected UnitDataBase(string jsonDataFilePath) : base(jsonDataFilePath) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="jsonDataFilePath">The JSON data to parse.</param> /// <param name="localization">The <see cref="Localization"/> of the file.</param> protected UnitDataBase(string jsonDataFilePath, Localization localization) : base(jsonDataFilePath, localization) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="jsonData">The JSON data to parse.</param> /// <param name="localization">The <see cref="Localization"/> of the file.</param> protected UnitDataBase(ReadOnlyMemory<byte> jsonData, Localization localization) : base(jsonData, localization) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="jsonDataFilePath">The JSON data to parse.</param> /// <param name="gameStringDocument">Instance of a <see cref="GameStringDocument"/>.</param> protected UnitDataBase(string jsonDataFilePath, GameStringDocument gameStringDocument) : base(jsonDataFilePath, gameStringDocument) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="jsonData">The JSON data to parse.</param> /// <param name="gameStringDocument">Instance of a <see cref="GameStringDocument"/>.</param> protected UnitDataBase(ReadOnlyMemory<byte> jsonData, GameStringDocument gameStringDocument) : base(jsonData, gameStringDocument) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="utf8Json">The JSON data to parse.</param> /// <param name="localization">The <see cref="Localization"/> of the file.</param> /// <param name="isAsync">Value indicating whether to parse the <paramref name="utf8Json"/> as <see langword="async"/>.</param> protected UnitDataBase(Stream utf8Json, Localization localization, bool isAsync = false) : base(utf8Json, localization, isAsync) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="utf8Json">The JSON data to parse.</param> /// <param name="gameStringDocument">Instance of a <see cref="GameStringDocument"/>.</param> /// <param name="isAsync">Value indicating whether to parse the <paramref name="utf8Json"/> as <see langword="async"/>.</param> protected UnitDataBase(Stream utf8Json, GameStringDocument gameStringDocument, bool isAsync = false) : base(utf8Json, gameStringDocument, isAsync) { } /// <summary> /// Initializes a new instance of the <see cref="UnitDataBase"/> class. /// </summary> /// <param name="utf8Json">The JSON data to parse.</param> /// <param name="utf8JsonGameStrings">The JSON gamestring data to parse.</param> /// <param name="isAsync">Value indicating whether to parse the <paramref name="utf8Json"/> as <see langword="async"/>.</param> protected UnitDataBase(Stream utf8Json, Stream utf8JsonGameStrings, bool isAsync = false) : base(utf8Json, utf8JsonGameStrings, isAsync) { } /// <summary> /// Sets the <see cref="Unit"/>'s life data. /// </summary> /// <param name="element">The <see cref="JsonElement"/> to read from.</param> /// <param name="unit">The data to be set from <paramref name="element"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void SetUnitLife(JsonElement element, Unit unit) { if (unit is null) throw new ArgumentNullException(nameof(unit)); if (element.TryGetProperty("life", out JsonElement lifeElement)) { unit.Life.LifeMax = lifeElement.GetProperty("amount").GetDouble(); unit.Life.LifeScaling = lifeElement.GetProperty("scale").GetDouble(); if (lifeElement.TryGetProperty("type", out JsonElement lifeType)) unit.Life.LifeType = lifeType.GetString(); unit.Life.LifeRegenerationRate = lifeElement.GetProperty("regenRate").GetDouble(); unit.Life.LifeRegenerationRateScaling = lifeElement.GetProperty("regenScale").GetDouble(); } } /// <summary> /// Sets the <see cref="Unit"/>'s shield data. /// </summary> /// <param name="element">The <see cref="JsonElement"/> to read from.</param> /// <param name="unit">The data to be set from <paramref name="element"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void SetUnitShield(JsonElement element, Unit unit) { if (unit is null) throw new ArgumentNullException(nameof(unit)); if (element.TryGetProperty("shield", out JsonElement shieldElement)) { unit.Shield.ShieldMax = shieldElement.GetProperty("amount").GetDouble(); unit.Shield.ShieldScaling = shieldElement.GetProperty("scale").GetDouble(); if (shieldElement.TryGetProperty("type", out JsonElement shieldType)) unit.Shield.ShieldType = shieldType.GetString(); unit.Shield.ShieldRegenerationDelay = shieldElement.GetProperty("regenDelay").GetDouble(); unit.Shield.ShieldRegenerationRate = shieldElement.GetProperty("regenRate").GetDouble(); unit.Shield.ShieldRegenerationRateScaling = shieldElement.GetProperty("regenScale").GetDouble(); } } /// <summary> /// Sets the <see cref="Unit"/>'s energy data. /// </summary> /// <param name="element">The <see cref="JsonElement"/> to read from.</param> /// <param name="unit">The data to be set from <paramref name="element"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void SetUnitEnergy(JsonElement element, Unit unit) { if (unit is null) throw new ArgumentNullException(nameof(unit)); if (element.TryGetProperty("energy", out JsonElement energyElement)) { unit.Energy.EnergyMax = energyElement.GetProperty("amount").GetDouble(); if (energyElement.TryGetProperty("type", out JsonElement energyType)) unit.Energy.EnergyType = energyType.GetString(); unit.Energy.EnergyRegenerationRate = energyElement.GetProperty("regenRate").GetDouble(); } } /// <summary> /// Sets the <see cref="Unit"/>'s armor data. /// </summary> /// <param name="element">The <see cref="JsonElement"/> to read from.</param> /// <param name="unit">The data to be set from <paramref name="element"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void SetUnitArmor(JsonElement element, Unit unit) { if (unit is null) throw new ArgumentNullException(nameof(unit)); if (element.TryGetProperty("armor", out JsonElement armorElement)) { foreach (JsonProperty armorProperty in armorElement.EnumerateObject()) { UnitArmor unitArmor = new UnitArmor { Type = armorProperty.Name, BasicArmor = armorProperty.Value.GetProperty("basic").GetInt32(), AbilityArmor = armorProperty.Value.GetProperty("ability").GetInt32(), SplashArmor = armorProperty.Value.GetProperty("splash").GetInt32(), }; unit.Armor.Add(unitArmor); } } } /// <summary> /// Sets the <see cref="Unit"/>'s weapon data. /// </summary> /// <param name="element">The <see cref="JsonElement"/> to read from.</param> /// <param name="unit">The data to be set from <paramref name="element"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void SetUnitWeapons(JsonElement element, Unit unit) { if (unit is null) throw new ArgumentNullException(nameof(unit)); if (element.TryGetProperty("weapons", out JsonElement weapons)) { foreach (JsonElement weaponArrayElement in weapons.EnumerateArray()) { string? weaponIdValue = weaponArrayElement.GetProperty("nameId").GetString(); if (weaponIdValue is null) continue; UnitWeapon unitWeapon = new UnitWeapon { WeaponNameId = weaponIdValue, Range = weaponArrayElement.GetProperty("range").GetDouble(), Period = weaponArrayElement.GetProperty("period").GetDouble(), Damage = weaponArrayElement.GetProperty("damage").GetDouble(), DamageScaling = weaponArrayElement.GetProperty("damageScale").GetDouble(), }; if (weaponArrayElement.TryGetProperty("name", out JsonElement nameElement)) unitWeapon.Name = nameElement.ToString(); // attribute factors if (weaponArrayElement.TryGetProperty("damageFactor", out JsonElement damageFactor)) { foreach (JsonProperty attributeFactorProperty in damageFactor.EnumerateObject()) { WeaponAttributeFactor weaponAttributeFactor = new WeaponAttributeFactor { Type = attributeFactorProperty.Name, Value = attributeFactorProperty.Value.GetDouble(), }; unitWeapon.AttributeFactors.Add(weaponAttributeFactor); } } unit.Weapons.Add(unitWeapon); } } } /// <summary> /// Adds the <see cref="Unit"/>'s abilities. /// </summary> /// <param name="unit">The data to be set from <paramref name="abilitiesElement"/>.</param> /// <param name="abilitiesElement">The <see cref="JsonElement"/> to read from.</param> /// <param name="parentLink">Indicates if the ability is a sub-ability.</param> protected virtual void AddAbilities(Unit unit, JsonElement abilitiesElement, string? parentLink = null) { if (abilitiesElement.TryGetProperty("basic", out JsonElement basicElement)) AddTierAbilities(unit, basicElement, AbilityTiers.Basic, parentLink); if (abilitiesElement.TryGetProperty("heroic", out JsonElement heroicElement)) AddTierAbilities(unit, heroicElement, AbilityTiers.Heroic, parentLink); if (abilitiesElement.TryGetProperty("trait", out JsonElement traitElement)) AddTierAbilities(unit, traitElement, AbilityTiers.Trait, parentLink); if (abilitiesElement.TryGetProperty("mount", out JsonElement mountElement)) AddTierAbilities(unit, mountElement, AbilityTiers.Mount, parentLink); if (abilitiesElement.TryGetProperty("activable", out JsonElement activableElement)) AddTierAbilities(unit, activableElement, AbilityTiers.Activable, parentLink); if (abilitiesElement.TryGetProperty("hearth", out JsonElement hearthElement)) AddTierAbilities(unit, hearthElement, AbilityTiers.Hearth, parentLink); if (abilitiesElement.TryGetProperty("taunt", out JsonElement tauntElement)) AddTierAbilities(unit, tauntElement, AbilityTiers.Taunt, parentLink); if (abilitiesElement.TryGetProperty("dance", out JsonElement danceElement)) AddTierAbilities(unit, danceElement, AbilityTiers.Dance, parentLink); if (abilitiesElement.TryGetProperty("spray", out JsonElement sprayElement)) AddTierAbilities(unit, sprayElement, AbilityTiers.Spray, parentLink); if (abilitiesElement.TryGetProperty("voice", out JsonElement voiceElement)) AddTierAbilities(unit, voiceElement, AbilityTiers.Voice, parentLink); if (abilitiesElement.TryGetProperty("mapMechanic", out JsonElement mapElement)) AddTierAbilities(unit, mapElement, AbilityTiers.MapMechanic, parentLink); if (abilitiesElement.TryGetProperty("interact", out JsonElement interactElement)) AddTierAbilities(unit, interactElement, AbilityTiers.Interact, parentLink); if (abilitiesElement.TryGetProperty("action", out JsonElement actionElement)) AddTierAbilities(unit, actionElement, AbilityTiers.Action, parentLink); if (abilitiesElement.TryGetProperty("hidden", out JsonElement hiddenElement)) AddTierAbilities(unit, hiddenElement, AbilityTiers.Hidden, parentLink); if (abilitiesElement.TryGetProperty("unknown", out JsonElement unkownElement)) AddTierAbilities(unit, unkownElement, AbilityTiers.Unknown, parentLink); } /// <summary> /// Adds the <see cref="Unit"/>'s ability data. /// </summary> /// <param name="unit">The data to be set from <paramref name="tierElement"/>.</param> /// <param name="tierElement">The <see cref="JsonElement"/> to read from.</param> /// <param name="abilityTier">The tier of the ability.</param> /// <param name="parentLink">Indicates if the ability is a sub-ability.</param> /// <exception cref="ArgumentNullException"><paramref name="unit"/> is <see langword="null"/>.</exception> protected virtual void AddTierAbilities(Unit unit, JsonElement tierElement, AbilityTiers abilityTier, string? parentLink) { if (unit is null) throw new ArgumentNullException(nameof(unit)); foreach (JsonElement element in tierElement.EnumerateArray()) { Ability ability = new Ability { Tier = abilityTier, }; if (parentLink != null) { string[] ids = parentLink.Split('|', StringSplitOptions.RemoveEmptyEntries); if (ids.Length >= 2) { ability.ParentLink = new AbilityTalentId(ids[0], ids[1]); if (ids.Length >= 3 && Enum.TryParse(ids[2], true, out AbilityTypes abilityTypes)) ability.ParentLink.AbilityType = abilityTypes; if (ids.Length == 4 && bool.TryParse(ids[3], out bool isPassive)) ability.ParentLink.IsPassive = isPassive; } } SetAbilityTalentBase(ability, element); unit.AddAbility(ability); } } /// <summary> /// Sets the <see cref="AbilityTalentBase"/> data of the <see cref="Ability"/>. /// </summary> /// <param name="abilityTalentBase">The <see cref="AbilityTalentBase"/> data to be set.</param> /// <param name="abilityTalentElement">The <see cref="JsonElement"/> to read from.</param> /// <exception cref="ArgumentNullException"><paramref name="abilityTalentBase"/> is <see langword="null"/>.</exception> protected virtual void SetAbilityTalentBase(AbilityTalentBase abilityTalentBase, JsonElement abilityTalentElement) { if (abilityTalentBase is null) throw new ArgumentNullException(nameof(abilityTalentBase)); abilityTalentBase.AbilityTalentId.ReferenceId = abilityTalentElement.GetProperty("nameId").GetString() ?? string.Empty; if (abilityTalentElement.TryGetProperty("buttonId", out JsonElement buttonElement)) abilityTalentBase.AbilityTalentId.ButtonId = buttonElement.GetString() ?? string.Empty; if (abilityTalentElement.TryGetProperty("name", out JsonElement nameElement)) abilityTalentBase.Name = nameElement.GetString(); if (abilityTalentElement.TryGetProperty("icon", out JsonElement iconElement)) abilityTalentBase.IconFileName = iconElement.GetString(); if (abilityTalentElement.TryGetProperty("toggleCooldown", out JsonElement toggleCooldownElement)) abilityTalentBase.Tooltip.Cooldown.ToggleCooldown = toggleCooldownElement.GetDouble(); if (abilityTalentElement.TryGetProperty("lifeTooltip", out JsonElement lifeTooltipElement)) abilityTalentBase.Tooltip.Life.LifeCostTooltip = SetTooltipDescription(lifeTooltipElement.GetString(), Localization); if (abilityTalentElement.TryGetProperty("energyTooltip", out JsonElement energyTooltipElement)) abilityTalentBase.Tooltip.Energy.EnergyTooltip = SetTooltipDescription(energyTooltipElement.GetString(), Localization); // charges if (abilityTalentElement.TryGetProperty("charges", out JsonElement chargeElement)) { abilityTalentBase.Tooltip.Charges.CountMax = chargeElement.GetProperty("countMax").GetInt32(); if (chargeElement.TryGetProperty("countUse", out JsonElement countUseElement)) abilityTalentBase.Tooltip.Charges.CountUse = countUseElement.GetInt32(); if (chargeElement.TryGetProperty("countStart", out JsonElement countStartElement)) abilityTalentBase.Tooltip.Charges.CountStart = countStartElement.GetInt32(); if (chargeElement.TryGetProperty("hideCount", out JsonElement hideCountElement)) abilityTalentBase.Tooltip.Charges.IsHideCount = hideCountElement.GetBoolean(); if (chargeElement.TryGetProperty("recastCooldown", out JsonElement recastCooldownElement)) abilityTalentBase.Tooltip.Charges.RecastCooldown = recastCooldownElement.GetDouble(); } if (abilityTalentElement.TryGetProperty("cooldownTooltip", out JsonElement cooldownTooltipElement)) abilityTalentBase.Tooltip.Cooldown.CooldownTooltip = SetTooltipDescription(cooldownTooltipElement.GetString(), Localization); if (abilityTalentElement.TryGetProperty("shortTooltip", out JsonElement shortTooltipElement)) abilityTalentBase.Tooltip.ShortTooltip = SetTooltipDescription(shortTooltipElement.GetString(), Localization); if (abilityTalentElement.TryGetProperty("fullTooltip", out JsonElement fullTooltipElement)) abilityTalentBase.Tooltip.FullTooltip = SetTooltipDescription(fullTooltipElement.GetString(), Localization); if (Enum.TryParse(abilityTalentElement.GetProperty("abilityType").GetString(), out AbilityTypes abilityTypes)) abilityTalentBase.AbilityTalentId.AbilityType = abilityTypes; else abilityTalentBase.AbilityTalentId.AbilityType = AbilityTypes.Unknown; if (abilityTalentElement.TryGetProperty("isActive", out JsonElement isActiveElement)) abilityTalentBase.IsActive = isActiveElement.GetBoolean(); if (abilityTalentElement.TryGetProperty("isPassive", out JsonElement isPassiveElement)) abilityTalentBase.AbilityTalentId.IsPassive = isPassiveElement.GetBoolean(); if (abilityTalentElement.TryGetProperty("isQuest", out JsonElement isQuestElement)) abilityTalentBase.IsQuest = isQuestElement.GetBoolean(); } } }
53.835859
141
0.621933
[ "MIT" ]
HeroesToolChest/Heroes.Icons
Heroes.Icons/DataDocument/UnitDataBase.cs
21,321
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using SixLabors.ImageSharp.ColorSpaces; using SixLabors.ImageSharp.ColorSpaces.Conversion; using Xunit; namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion { /// <summary> /// Tests <see cref="CieXyz"/>-<see cref="CieLab"/> conversions. /// </summary> /// <remarks> /// Test data generated using: /// <see href="http://www.brucelindbloom.com/index.html?ColorCalculator.html"/> /// </remarks> public class CieXyzAndCieLabConversionTest { private static readonly ApproximateColorSpaceComparer ColorSpaceComparer = new ApproximateColorSpaceComparer(.0001F); /// <summary> /// Tests conversion from <see cref="CieLab"/> to <see cref="CieXyz"/> (<see cref="Illuminants.D65"/>). /// </summary> [Theory] [InlineData(100, 0, 0, 0.95047, 1, 1.08883)] [InlineData(0, 0, 0, 0, 0, 0)] [InlineData(0, 431.0345, 0, 0.95047, 0, 0)] [InlineData(100, -431.0345, 172.4138, 0, 1, 0)] [InlineData(0, 0, -172.4138, 0, 0, 1.08883)] [InlineData(45.6398, 39.8753, 35.2091, 0.216938, 0.150041, 0.048850)] [InlineData(77.1234, -40.1235, 78.1120, 0.358530, 0.517372, 0.076273)] [InlineData(10, -400, 20, 0, 0.011260, 0)] public void Convert_Lab_to_Xyz(float l, float a, float b, float x, float y, float z) { // Arrange var input = new CieLab(l, a, b, Illuminants.D65); var options = new ColorSpaceConverterOptions { WhitePoint = Illuminants.D65, TargetLabWhitePoint = Illuminants.D65 }; var converter = new ColorSpaceConverter(options); var expected = new CieXyz(x, y, z); Span<CieLab> inputSpan = new CieLab[5]; inputSpan.Fill(input); Span<CieXyz> actualSpan = new CieXyz[5]; // Act var actual = converter.ToCieXyz(input); converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } /// <summary> /// Tests conversion from <see cref="CieXyz"/> (<see cref="Illuminants.D65"/>) to <see cref="CieLab"/>. /// </summary> [Theory] [InlineData(0.95047, 1, 1.08883, 100, 0, 0)] [InlineData(0, 0, 0, 0, 0, 0)] [InlineData(0.95047, 0, 0, 0, 431.0345, 0)] [InlineData(0, 1, 0, 100, -431.0345, 172.4138)] [InlineData(0, 0, 1.08883, 0, 0, -172.4138)] [InlineData(0.216938, 0.150041, 0.048850, 45.6398, 39.8753, 35.2091)] public void Convert_Xyz_to_Lab(float x, float y, float z, float l, float a, float b) { // Arrange var input = new CieXyz(x, y, z); var options = new ColorSpaceConverterOptions { WhitePoint = Illuminants.D65, TargetLabWhitePoint = Illuminants.D65 }; var converter = new ColorSpaceConverter(options); var expected = new CieLab(l, a, b); Span<CieXyz> inputSpan = new CieXyz[5]; inputSpan.Fill(input); Span<CieLab> actualSpan = new CieLab[5]; // Act var actual = converter.ToCieLab(input); converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } }
39.15625
129
0.580474
[ "Apache-2.0" ]
GyleIverson/ImageSharp
tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieLabConversionTest.cs
3,761
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kinesisvideo-2017-09-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.KinesisVideo.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.KinesisVideo.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeImageGenerationConfiguration operation /// </summary> public class DescribeImageGenerationConfigurationResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeImageGenerationConfigurationResponse response = new DescribeImageGenerationConfigurationResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ImageGenerationConfiguration", targetDepth)) { var unmarshaller = ImageGenerationConfigurationUnmarshaller.Instance; response.ImageGenerationConfiguration = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ClientLimitExceededException")) { return ClientLimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgumentException")) { return InvalidArgumentExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonKinesisVideoException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeImageGenerationConfigurationResponseUnmarshaller _instance = new DescribeImageGenerationConfigurationResponseUnmarshaller(); internal static DescribeImageGenerationConfigurationResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeImageGenerationConfigurationResponseUnmarshaller Instance { get { return _instance; } } } }
41.254098
195
0.661037
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/KinesisVideo/Generated/Model/Internal/MarshallTransformations/DescribeImageGenerationConfigurationResponseUnmarshaller.cs
5,033
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class W3PosterStatePosterObserved : CScriptableState { public W3PosterStatePosterObserved(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3PosterStatePosterObserved(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.73913
139
0.756972
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/W3PosterStatePosterObserved.cs
753
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; #if WINDOWS_UWP using Windows.UI.Notifications; #endif namespace Microsoft.Toolkit.Uwp.Notifications { /// <summary> /// Builder class used to create <see cref="ToastContent"/> /// </summary> public partial class ToastContentBuilder { private ToastVisual Visual { get { if (Content.Visual == null) { Content.Visual = new ToastVisual(); Content.Visual.BindingGeneric = new ToastBindingGeneric(); } return Content.Visual; } } private ToastGenericAppLogo AppLogoOverrideUri { get { return Visual.BindingGeneric.AppLogoOverride; } set { Visual.BindingGeneric.AppLogoOverride = value; } } private ToastGenericAttributionText AttributionText { get { return Visual.BindingGeneric.Attribution; } set { Visual.BindingGeneric.Attribution = value; } } private ToastGenericHeroImage HeroImage { get { return Visual.BindingGeneric.HeroImage; } set { Visual.BindingGeneric.HeroImage = value; } } private IList<IToastBindingGenericChild> VisualChildren { get { return Visual.BindingGeneric.Children; } } #if WINDOWS_UWP #if !WINRT /// <summary> /// Create an instance of NotificationData that can be used to update toast that has a progress bar. /// </summary> /// <param name="toast">Instance of ToastContent that contain progress bars that need to be updated</param> /// <param name="index">Index of the progress bar (0-based) that this notification data is updating in the case that toast has multiple progress bars. Default to 0.</param> /// <param name="title">Title of the progress bar.</param> /// <param name="value">Value of the progress bar.</param> /// <param name="valueStringOverride">An optional string to be displayed instead of the default percentage string. If this isn't provided, something like "70%" will be displayed.</param> /// <param name="status"> A status string, which is displayed underneath the progress bar on the left. Default to empty.</param> /// <param name="sequence">A sequence number to prevent out-of-order updates, or assign 0 to indicate "always update".</param> /// <returns>An instance of NotificationData that can be used to update the toast.</returns> public static NotificationData CreateProgressBarData(ToastContent toast, int index = 0, string title = default, double? value = default, string valueStringOverride = default, string status = default, uint sequence = 0) { var progressBar = toast.Visual.BindingGeneric.Children.Where(c => c is AdaptiveProgressBar).ElementAt(index) as AdaptiveProgressBar; if (progressBar == null) { throw new ArgumentException(nameof(toast), "Given toast does not have any progress bar"); } NotificationData data = new NotificationData(); data.SequenceNumber = sequence; // Native C++ doesn't support BindableString if (progressBar.Title is BindableString bindableTitle && title != default) { data.Values[bindableTitle.BindingName] = title; } if (progressBar.Value is BindableProgressBarValue bindableProgressValue && value != default) { data.Values[bindableProgressValue.BindingName] = value.ToString(); } if (progressBar.ValueStringOverride is BindableString bindableValueStringOverride && valueStringOverride != default) { data.Values[bindableValueStringOverride.BindingName] = valueStringOverride; } if (progressBar.Status is BindableString bindableStatus && status != default) { data.Values[bindableStatus.BindingName] = status; } return data; } #endif #endif /// <summary> /// Add an Attribution Text to be displayed on the toast. /// </summary> /// <param name="text">Text to be displayed as Attribution Text</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAttributionText(string text) { return AddAttributionText(text, default); } /// <summary> /// Add an Attribution Text to be displayed on the toast. /// </summary> /// <param name="text">Text to be displayed as Attribution Text</param> /// <param name="language">The target locale of the XML payload, specified as a BCP-47 language tags such as "en-US" or "fr-FR".</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAttributionText(string text, string language) { AttributionText = new ToastGenericAttributionText() { Text = text }; if (language != default) { AttributionText.Language = language; } return this; } #if WINRT /// <summary> /// Override the app logo with custom image of choice that will be displayed on the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAppLogoOverride(Uri uri) { return AddAppLogoOverride(uri, default); } /// <summary> /// Override the app logo with custom image of choice that will be displayed on the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="hintCrop">Specify how the image should be cropped.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAppLogoOverride(Uri uri, ToastGenericAppLogoCrop? hintCrop) { return AddAppLogoOverride(uri, hintCrop, default); } /// <summary> /// Override the app logo with custom image of choice that will be displayed on the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="hintCrop">Specify how the image should be cropped.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAppLogoOverride(Uri uri, ToastGenericAppLogoCrop? hintCrop, string alternateText) { return AddAppLogoOverride(uri, hintCrop, alternateText, default); } #endif /// <summary> /// Override the app logo with custom image of choice that will be displayed on the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="hintCrop">Specify how the image should be cropped.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <param name="addImageQuery">A value whether Windows is allowed to append a query string to the image URI supplied in the Tile notification.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddAppLogoOverride( Uri uri, #if WINRT ToastGenericAppLogoCrop? hintCrop, string alternateText, bool? addImageQuery) #else ToastGenericAppLogoCrop? hintCrop = default, string alternateText = default, bool? addImageQuery = default) #endif { AppLogoOverrideUri = new ToastGenericAppLogo() { Source = uri.OriginalString }; if (hintCrop != default) { AppLogoOverrideUri.HintCrop = hintCrop.Value; } if (alternateText != default) { AppLogoOverrideUri.AlternateText = alternateText; } if (addImageQuery != default) { AppLogoOverrideUri.AddImageQuery = addImageQuery; } return this; } #if WINRT /// <summary> /// Add a hero image to the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddHeroImage(Uri uri) { return AddHeroImage(uri, default); } /// <summary> /// Add a hero image to the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddHeroImage(Uri uri, string alternateText) { return AddHeroImage(uri, alternateText, default); } #endif /// <summary> /// Add a hero image to the toast. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <param name="addImageQuery">A value whether Windows is allowed to append a query string to the image URI supplied in the Tile notification.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddHeroImage( Uri uri, #if WINRT string alternateText, bool? addImageQuery) #else string alternateText = default, bool? addImageQuery = default) #endif { HeroImage = new ToastGenericHeroImage() { Source = uri.OriginalString }; if (alternateText != default) { HeroImage.AlternateText = alternateText; } if (addImageQuery != default) { HeroImage.AddImageQuery = addImageQuery; } return this; } #if WINRT /// <summary> /// Add an image inline with other toast content. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddInlineImage(Uri uri) { return AddInlineImage(uri, default); } /// <summary> /// Add an image inline with other toast content. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddInlineImage(Uri uri, string alternateText) { return AddInlineImage(uri, alternateText, default); } /// <summary> /// Add an image inline with other toast content. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <param name="addImageQuery">A value whether Windows is allowed to append a query string to the image URI supplied in the Tile notification.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddInlineImage(Uri uri, string alternateText, bool? addImageQuery) { return AddInlineImage(uri, alternateText, addImageQuery, default); } #endif #if WINRT /// <summary> /// Add an image inline with other toast content. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <param name="addImageQuery">A value whether Windows is allowed to append a query string to the image URI supplied in the Tile notification.</param> /// <param name="hintCrop">A value whether a margin is removed. images have an 8px margin around them.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddInlineImage( Uri uri, string alternateText, bool? addImageQuery, AdaptiveImageCrop? hintCrop) #else /// <summary> /// Add an image inline with other toast content. /// </summary> /// <param name="uri">The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.</param> /// <param name="alternateText">A description of the image, for users of assistive technologies.</param> /// <param name="addImageQuery">A value whether Windows is allowed to append a query string to the image URI supplied in the Tile notification.</param> /// <param name="hintCrop">A value whether a margin is removed. images have an 8px margin around them.</param> /// <param name="hintRemoveMargin">This property is not used. Setting this has no impact.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddInlineImage( Uri uri, string alternateText = default, bool? addImageQuery = default, AdaptiveImageCrop? hintCrop = default, bool? hintRemoveMargin = default) #endif { var inlineImage = new AdaptiveImage() { Source = uri.OriginalString }; if (hintCrop != null) { inlineImage.HintCrop = hintCrop.Value; } if (alternateText != default) { inlineImage.AlternateText = alternateText; } if (addImageQuery != default) { inlineImage.AddImageQuery = addImageQuery; } return AddVisualChild(inlineImage); } #if !WINRT /// <summary> /// Add a progress bar to the toast. /// </summary> /// <param name="title">Title of the progress bar.</param> /// <param name="value">Value of the progress bar. Default is 0</param> /// <param name="isIndeterminate">Determine if the progress bar value should be indeterminate. Default to false.</param> /// <param name="valueStringOverride">An optional string to be displayed instead of the default percentage string. If this isn't provided, something like "70%" will be displayed.</param> /// <param name="status">A status string which is displayed underneath the progress bar. This string should reflect the status of the operation, like "Downloading..." or "Installing...". Default to empty.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> /// <remarks>More info at: https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/toast-progress-bar </remarks> public ToastContentBuilder AddProgressBar(string title = default, double? value = null, bool isIndeterminate = false, string valueStringOverride = default, string status = default) { int index = VisualChildren.Count(c => c is AdaptiveProgressBar); var progressBar = new AdaptiveProgressBar() { }; if (title == default) { progressBar.Title = new BindableString($"progressBarTitle_{index}"); } else { progressBar.Title = title; } if (isIndeterminate) { progressBar.Value = AdaptiveProgressBarValue.Indeterminate; } else if (value == null) { progressBar.Value = new BindableProgressBarValue($"progressValue_{index}"); } else { progressBar.Value = value.Value; } if (valueStringOverride == default) { progressBar.ValueStringOverride = new BindableString($"progressValueString_{index}"); } else { progressBar.ValueStringOverride = valueStringOverride; } if (status == default) { progressBar.Status = new BindableString($"progressStatus_{index}"); } else { progressBar.Status = status; } return AddVisualChild(progressBar); } #endif #if WINRT /// <summary> /// Add text to the toast. /// </summary> /// <param name="text">Custom text to display on the tile.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> /// <exception cref="InvalidOperationException">Throws when attempting to add/reserve more than 4 lines on a single toast. </exception> /// <remarks>More info at: https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#text-elements</remarks> public ToastContentBuilder AddText(string text) { return AddText(text, default, default); } /// <summary> /// Add text to the toast. /// </summary> /// <param name="text">Custom text to display on the tile.</param> /// <param name="hintMaxLines">The maximum number of lines the text element is allowed to display.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> /// <exception cref="InvalidOperationException">Throws when attempting to add/reserve more than 4 lines on a single toast. </exception> /// <remarks>More info at: https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#text-elements</remarks> public ToastContentBuilder AddText(string text, int? hintMaxLines) { return AddText(text, hintMaxLines, default); } #endif #if WINRT /// <summary> /// Add text to the toast. /// </summary> /// <param name="text">Custom text to display on the tile.</param> /// <param name="hintMaxLines">The maximum number of lines the text element is allowed to display.</param> /// <param name="language"> /// The target locale of the XML payload, specified as a BCP-47 language tags such as "en-US" or "fr-FR". The locale specified here overrides any other specified locale, such as that in binding or visual. /// </param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> /// <exception cref="InvalidOperationException">Throws when attempting to add/reserve more than 4 lines on a single toast. </exception> /// <exception cref="ArgumentOutOfRangeException">Throws when <paramref name="hintMaxLines"/> value is larger than 2. </exception> /// <remarks>More info at: https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#text-elements</remarks> public ToastContentBuilder AddText( string text, int? hintMaxLines, string language) #else /// <summary> /// Add text to the toast. /// </summary> /// <param name="text">Custom text to display on the tile.</param> /// <param name="hintStyle">This property is not used. Setting this has no effect.</param> /// <param name="hintWrap">This property is not used. Setting this has no effect. If you need to disable wrapping, set hintMaxLines to 1.</param> /// <param name="hintMaxLines">The maximum number of lines the text element is allowed to display.</param> /// <param name="hintMinLines">hintMinLines is not used. Setting this has no effect.</param> /// <param name="hintAlign">hintAlign is not used. Setting this has no effect.</param> /// <param name="language"> /// The target locale of the XML payload, specified as a BCP-47 language tags such as "en-US" or "fr-FR". The locale specified here overrides any other specified locale, such as that in binding or visual. /// </param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> /// <exception cref="InvalidOperationException">Throws when attempting to add/reserve more than 4 lines on a single toast. </exception> /// <exception cref="ArgumentOutOfRangeException">Throws when <paramref name="hintMaxLines"/> value is larger than 2. </exception> /// <remarks>More info at: https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#text-elements</remarks> public ToastContentBuilder AddText( string text, AdaptiveTextStyle? hintStyle = null, bool? hintWrap = default, int? hintMaxLines = default, int? hintMinLines = default, AdaptiveTextAlign? hintAlign = null, string language = default) #endif { int lineCount = GetCurrentTextLineCount(); if (GetCurrentTextLineCount() == 4) { // Reached maximum, we can't go further. throw new InvalidOperationException("We have reached max lines allowed (4) per toast"); } AdaptiveText adaptive = new AdaptiveText() { Text = text }; if (hintMaxLines != default) { if (hintMaxLines > 2) { throw new ArgumentOutOfRangeException(nameof(hintMaxLines), "max line can't go more than 2 lines."); } else if ((lineCount + hintMaxLines) > 4) { throw new InvalidOperationException($"Can't exceed more than 4 lines of text per toast. Current line count : {lineCount} | Requesting line count: {lineCount + hintMaxLines}"); } adaptive.HintMaxLines = hintMaxLines; } if (language != default) { adaptive.Language = language; } return AddVisualChild(adaptive); } /// <summary> /// Add a visual element to the toast. /// </summary> /// <param name="child">An instance of a class that implement <see cref="IToastBindingGenericChild"/>.</param> /// <returns>The current instance of <see cref="ToastContentBuilder"/></returns> public ToastContentBuilder AddVisualChild(IToastBindingGenericChild child) { VisualChildren.Add(child); return this; } private int GetCurrentTextLineCount() { if (!VisualChildren.Any(c => c is AdaptiveText)) { return 0; } var textList = VisualChildren.Where(c => c is AdaptiveText).Select(c => c as AdaptiveText).ToList(); // First one is already the header. // https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#text-elements // The default (and maximum) is up to 2 lines of text for the title, and up to 4 lines (combined) for the two additional description elements (the second and third AdaptiveText). AdaptiveText text = textList.First(); int count = 0; count += text.HintMaxLines ?? 2; for (int i = 1; i < textList.Count; i++) { text = textList[i]; count += text.HintMaxLines ?? 1; } return count; } } }
45.043771
226
0.609508
[ "MIT" ]
ArchieCoder/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Visuals.cs
26,756
C#
using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemCreatePanel : MonoBehaviour { [SerializeField] private GameObject _panel; private void Update() { PollToggle(); } private void PollToggle() { if (Input.GetKeyDown(KeyCode.I)) { TogglePanel(); } } public void CreateItem() { CreateItem(IconPanel.SelectedIcon, PropertyPanel.SelectedProperties.ToArray()); } public void CreateItem(Sprite sprite, PropertyBase[] propertyTypes) { ItemBase item = new ItemBase(sprite, propertyTypes); ItemObject obj = ItemObject.Create(item); ItemObjectHandler.HandleItem(obj); _panel.SetActive(false); PropertyPanel.Reset(); } private void TogglePanel() { _panel.SetActive(!_panel.activeInHierarchy); _panel.transform.SetAsLastSibling(); } }
23.581395
88
0.613412
[ "MIT" ]
DanielEverland/Dead-Air-Blueprint-Prototype
Assets/Scripts/UI/ItemCreatePanel.cs
1,016
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Misty { public partial class Misty : Form { public Misty() { InitializeComponent(); } private Task UILogs(string new_string) { status.Text = new_string; status.Refresh(); return (Task.CompletedTask); } private Task boxer(string message, string title, MessageBoxIcon type) { MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBox.Show(message, title, buttons, type); return (Task.CompletedTask); } private int count_char(string str, char c) { int total = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == c) total++; } return (total); } private void exit_Click(object sender, EventArgs e) { Application.Exit(); } private string crop(string message) { if (count_char(message, '\\') >= 3) { return ($"{message.Split('\\')[0]}\\{message.Split('\\')[1]}\\...\\{message.Split('\\')[count_char(message, '\\')]}"); } return (message); } private int get_folder() { directory.ShowDialog(); if (directory.SelectedPath.Length == 0) return (-1); else UILogs(crop(directory.SelectedPath)).Wait(); return (0); } private string get_full_path(string path, int minimum) { string full = ""; int slash = 0; for (int i = 0; i < path.Length; i++) { if (path[i] == '\\') slash++; if (slash >= minimum) full += path[i]; } return (full); } private Task progress_bar(int percent) { int max = 424; int progress = (percent * max) / 100; bar.Size = new Size(progress, 10); bar.Refresh(); return (Task.CompletedTask); } private Task compress(string output) { string[] files = Directory.GetFiles(directory.SelectedPath, "*.*", SearchOption.AllDirectories); Console.WriteLine(files.Length); string name = null; int progress = 0; int total = count_char(directory.SelectedPath, '\\'); Dictionary<string, byte[]> content = new Dictionary<string, byte[]>(); for (int i = 0; i < files.Length; i++) { progress = (i * 100) / files.Length; name = get_full_path(files[i], total); UILogs($"{name}").Wait(); progress_bar(progress).Wait(); content.Add($"{name}", File.ReadAllBytes(files[i])); } settings.DATA_CONTENT new_content = new settings.DATA_CONTENT() { DATA = content }; UILogs("Compressing").Wait(); string json = JsonConvert.SerializeObject(new_content); UILogs($"Writing in {output}").Wait(); File.WriteAllText(output, json); progress_bar(0).Wait(); new_content.DATA = null; return (Task.CompletedTask); } private string clean_path(string path) { string new_path = ""; for (int i = 0; i < path.Length - 1; i++) { new_path += path[i + 1]; } Console.WriteLine(new_path); return (new_path); } private void launch_Click(object sender, EventArgs e) { string dump = "DUMP.mis"; progress_bar(0); if (get_folder() == 0) { dump = $"{directory.SelectedPath.Split('\\')[count_char(directory.SelectedPath, '\\')]}.mis"; compress(dump).Wait(); UILogs($"Files compressed").Wait(); boxer($"Files compressed check: {dump}", "Success", MessageBoxIcon.Information).Wait(); } else { UILogs("Sorry but i can't compress nothing").Wait(); } } private int get_file() { file_mist.ShowDialog(); if (file_mist.FileName.Length == 0) return (-1); else UILogs(crop(file_mist.FileName)).Wait(); return (0); } private Task generate_directory(string key) { int slashes = count_char(key, '\\'); string dir = ""; for (int i = 0; i < (slashes - 1); i++) { dir += $"{key.Split('\\')[i + 1]}\\"; Console.WriteLine(dir); if (Directory.Exists(dir)) { UILogs($"Directory found :: {dir}"); } else { UILogs($"Creating directory :: {dir}"); Directory.CreateDirectory(dir); UILogs($"Directory created :: {dir}"); } } return (Task.CompletedTask); } private Task decompress() { string mist = File.ReadAllText(file_mist.FileName); int progress = 0; settings.DATA_CONTENT content = JsonConvert.DeserializeObject<settings.DATA_CONTENT>(mist); var keys = content.DATA.Keys.ToArray(); var values = content.DATA.Values.ToArray(); int total = keys.Length; for (int i = 0; i < keys.Length; i++) { progress = (i * 100) / keys.Length; progress_bar(progress).Wait(); generate_directory(keys[i]).Wait(); if (File.Exists(keys[i]) == false) { UILogs($"Extracting file :: {keys[i]}").Wait(); File.WriteAllBytes(clean_path(keys[i]), values[i]); UILogs($"File extracted :: {keys[i]}").Wait(); } else { UILogs($"File already present :: {keys[i]}").Wait(); } } progress_bar(0).Wait(); UILogs("Files extracted").Wait(); return (Task.CompletedTask); } private void uncompress_Click(object sender, EventArgs e) { progress_bar(0); if (get_file() == 0) { UILogs($"Uncompressing {file_mist.FileName}").Wait(); decompress().Wait(); boxer("Files extracted", "Success", MessageBoxIcon.Information).Wait(); } else { UILogs("Sorry but i can't uncompress nothing").Wait(); } } private void reduce_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } } }
30.581673
135
0.45766
[ "Apache-2.0" ]
Neotoxic-off/Misty
Misty/Misty/Misty.cs
7,678
C#
using SAPBlazorAnimate.Models; using System; using System.Collections.Generic; using System.Text; namespace SAPBlazorAnimate.Models { #region Attention Seekers public class SAPAttentionSeekersGroup { public string Bounce => $" {AnimateType.bounce} animated "; public string Flash => $" {AnimateType.flash} animated "; public string Pulse => $" {AnimateType.pulse} animated "; public string RubberBand => $" {AnimateType.rubberBand} animated "; public string Shake => $" {AnimateType.shake} animated "; public string Swing => $" {AnimateType.swing} animated "; public string Tada => $" {AnimateType.tada} animated "; public string Wobble => $" {AnimateType.wobble} animated "; public string Jello => $" {AnimateType.jello} animated "; public string HeartBeat => $" {AnimateType.heartBeat} animated "; } #endregion #region Bouncing Entrances public class SAPBouncingEntrancesGroup { public string BounceIn = $" {AnimateType.bounceIn} animated "; public string BounceInDown => $" {AnimateType.bounceInDown} animated "; public string BounceInLeft => $" {AnimateType.bounceInLeft} animated "; public string BounceInRight => $" {AnimateType.bounceInRight} animated "; public string BounceInUp => $" {AnimateType.bounceInUp} animated "; } #endregion #region Bouncing Exits public class SAPBouncingExitsGroup { public string BounceOut => $" {AnimateType.bounceOut} animated "; public string BounceOutDown => $" {AnimateType.bounceOutDown} animated "; public string BounceOutLeft => $" {AnimateType.bounceOutLeft} animated "; public string BounceOutRight => $" {AnimateType.bounceOutRight} animated "; public string BounceOutUp => $" {AnimateType.bounceOutUp} animated "; } #endregion #region Fading Entrances public class SAPFadingEntrancesGroup { public string FadeIn => $" {AnimateType.fadeIn} animated "; public string FadeInDown => $" {AnimateType.fadeInDown} animated "; public string FadeInDownBig => $" {AnimateType.fadeInDownBig} animated "; public string FadeInLeft => $" {AnimateType.fadeInLeft} animated "; public string FadeInLeftBig => $" {AnimateType.fadeInLeftBig} animated "; public string FadeInRight => $" {AnimateType.fadeInRight} animated "; public string FadeInRightBig => $" {AnimateType.fadeInRightBig} animated "; public string FadeInUp => $" {AnimateType.fadeInUp} animated "; public string FadeInUpBig => $" {AnimateType.fadeInUpBig} animated "; } #endregion #region Fading Exits public class SAPFadingExitsGroup { public string FadeOut => $" {AnimateType.fadeOut} animated "; public string FadeOutDown => $" {AnimateType.fadeOutDown} animated "; public string FadeOutDownBig => $" {AnimateType.fadeOutDownBig} animated "; public string FadeOutLeft => $" {AnimateType.fadeOutLeft} animated "; public string FadeOutLeftBig => $" {AnimateType.fadeOutLeftBig} animated "; public string FadeOutRight => $" {AnimateType.fadeOutRight} animated "; public string FadeOutRightBig => $" {AnimateType.fadeOutRightBig} animated "; public string FadeOutUp => $" {AnimateType.fadeOutUp} animated "; public string FadeOutUpBig => $" {AnimateType.fadeOutUpBig} animated "; } #endregion #region Flippers public class SAPFlippersGroup { public string Flip => $" {AnimateType.flip} animated "; public string FlipInX => $" {AnimateType.flipInX} animated "; public string FlipInY => $" {AnimateType.flipInY} animated "; public string FlipOutX => $" {AnimateType.flipOutX} animated "; public string FlipOutY => $" {AnimateType.flipOutY} animated "; } #endregion #region Light Speed public class SAPLightspeedGroup { public string LightSpeedIn => $" {AnimateType.lightSpeedIn} animated "; public string LightSpeedOut => $" {AnimateType.lightSpeedOut} animated "; } #endregion #region Rotating Entrances public class SAPRotatingEntrancesGroup { public string RotateIn => $" {AnimateType.rotateIn} animated "; public string RotateInDownLeft => $" {AnimateType.rotateInDownLeft} animated "; public string RotateInDownRight => $" {AnimateType.rotateInDownRight} animated "; public string RotateInUpLeft => $" {AnimateType.rotateInUpLeft} animated "; public string RotateInUpRight => $" {AnimateType.rotateInUpRight} animated "; } #endregion #region Rotating Exits public class SAPRotatingExitsGroup { public string RotateOut => $" {AnimateType.rotateOut} animated "; public string RotateOutDownLeft => $" {AnimateType.rotateOutDownLeft} animated "; public string RotateOutDownRight => $" {AnimateType.rotateOutDownRight} animated "; public string RotateOutUpLeft => $" {AnimateType.rotateOutUpLeft} animated "; public string RotateOutUpRight => $" {AnimateType.rotateOutUpRight} animated "; } #endregion #region Sliding Entrances public class SAPSlidingEntrancesGroup { public string SlideInUp => $" {AnimateType.slideInUp} animated "; public string SlideInDown => $" {AnimateType.slideInDown} animated "; public string SlideInLeft => $" {AnimateType.slideInLeft} animated "; public string SlideInRight => $" {AnimateType.slideInRight} animated "; } #endregion #region Sliding Exits public class SAPSlidingExitsGroup { public string SlideOutUp => $" {AnimateType.slideOutUp} animated "; public string SlideOutDown => $" {AnimateType.slideOutDown} animated "; public string SlideOutLeft => $" {AnimateType.slideOutLeft} animated "; public string SlideOutRight => $" {AnimateType.slideOutRight} animated "; } #endregion #region Zoom Entrances public class SAPZoomEntrancesGroup { public string ZoomIn => $" {AnimateType.zoomIn} animated "; public string ZoomInDown => $" {AnimateType.zoomInDown} animated "; public string ZoomInLeft => $" {AnimateType.zoomInLeft} animated "; public string ZoomInRight => $" {AnimateType.zoomInRight} animated "; public string ZoomInUp => $" {AnimateType.zoomInUp} animated "; } #endregion #region Zoom Exits public class SAPZoomExitsGroup { public string ZoomOut => $" {AnimateType.zoomOut} animated "; public string ZoomOutDown => $" {AnimateType.zoomOutDown} animated "; public string ZoomOutLeft => $" {AnimateType.zoomOutLeft} animated "; public string ZoomOutRight => $" {AnimateType.zoomOutRight} animated "; public string ZoomOutUp => $" {AnimateType.zoomOutUp} animated "; } #endregion #region Specials public class SAPSpecialsGroup { public string Hinge => $" {AnimateType.hinge} animated "; public string JackInTheBox => $" {AnimateType.jackInTheBox} animated "; public string RollIn => $" {AnimateType.rollIn} animated "; public string RollOut => $" {AnimateType.rollOut} animated "; } #endregion }
36.176471
91
0.666938
[ "MIT" ]
DanielHWe/SAPBlazorAnimate
SAPBlazorAnimate/Models/AnimateBook.cs
7,382
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.Linq.Expressions; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Utilities; #nullable disable namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class KeyAccessExpression : SqlExpression, IAccessExpression { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public KeyAccessExpression(IProperty property, Expression accessExpression) : base(property.ClrType, property.GetTypeMapping()) { Name = property.GetJsonPropertyName(); Property = property; AccessExpression = accessExpression; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string Name { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> #pragma warning disable 109 public new virtual IProperty Property { get; } #pragma warning restore 109 /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual Expression AccessExpression { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override Expression VisitChildren(ExpressionVisitor visitor) { Check.NotNull(visitor, nameof(visitor)); return Update(visitor.Visit(AccessExpression)); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual KeyAccessExpression Update(Expression outerExpression) => outerExpression != AccessExpression ? new KeyAccessExpression(Property, outerExpression) : this; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override void Print(ExpressionPrinter expressionPrinter) { Check.NotNull(expressionPrinter, nameof(expressionPrinter)); expressionPrinter.Append(ToString()); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override string ToString() => Name?.Length > 0 ? $"{AccessExpression}[\"{Name}\"]" // TODO: Remove once __jObject is translated to the access root in a better fashion. // See issue #17670 and related issue #14121. : $"{AccessExpression}"; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override bool Equals(object obj) => obj != null && ( ReferenceEquals(this, obj) || obj is KeyAccessExpression keyAccessExpression && Equals(keyAccessExpression) ); private bool Equals(KeyAccessExpression keyAccessExpression) => base.Equals(keyAccessExpression) && Name == keyAccessExpression.Name && AccessExpression.Equals(keyAccessExpression.AccessExpression); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Name, AccessExpression); } }
58.550725
113
0.668441
[ "Apache-2.0" ]
belav/efcore
src/EFCore.Cosmos/Query/Internal/KeyAccessExpression.cs
8,082
C#
using HPTK.Controllers.Interaction; using HPTK.Helpers; using HPTK.Models.Avatar; using HPTK.Settings; using HPTK.Views.Handlers; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HPTK.Controllers.Avatar { public class AvatarController : AvatarHandler { public AvatarModel model; private void Awake() { model.handler = this; viewModel = new AvatarViewModel(model); } private void Start() { core.model.avatars.Add(model); } private void Update() { if (model.followsCamera && core.model.trackedCamera) { model.headSight.position = core.model.trackedCamera.position; model.headSight.rotation = core.model.trackedCamera.rotation; } } } }
23.648649
77
0.609143
[ "MIT" ]
LudiKha/HPTK
Runtime/Modules/Avatar/AvatarController.cs
877
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WorldCities.Data; using WorldCities.Data.Models; namespace WorldCities.Controllers { [Route("api/[controller]")] [ApiController] public class CountriesController : ControllerBase { private readonly ApplicationDbContext _context; public CountriesController(ApplicationDbContext context) { _context = context; } // GET: api/Cities // GET: api/Countries/?pageIndex=0&pageSize=10 // GET: api/Countries/?pageIndex=0&pageSize=10&sortColumn=name&sortOrder=asc // GET: api/Countries/?pageIndex=0&pageSize=10&sortColumn=name&sortOrder=asc&filterColumn=name&filterQuery=york [HttpGet] public async Task<ActionResult<ApiResult<CountryDTO>>> GetCountries( int pageIndex = 0, int pageSize = 10, string sortColumn = null, string sortOrder = null, string filterColumn = null, string filterQuery = null) { return await ApiResult<CountryDTO>.CreateAsync( _context.Countries .Select(c => new CountryDTO() { Id = c.Id, Name = c.Name, ISO2 = c.ISO2, ISO3 = c.ISO3, TotCities = c.Cities.Count }), pageIndex, pageSize, sortColumn, sortOrder, filterColumn, filterQuery); } //public async Task<ActionResult<ApiResult<dynamic>>> GetCountries( // int pageIndex = 0, // int pageSize = 10, // string sortColumn = null, // string sortOrder = null, // string filterColumn = null, // string filterQuery = null) //{ // return await ApiResult<dynamic>.CreateAsync( // _context.Countries // .Select(c => new // { // Id = c.Id, // Name = c.Name, // ISO2 = c.ISO2, // ISO3 = c.ISO3, // TotCities = c.Cities.Count // }), // pageIndex, // pageSize, // sortColumn, // sortOrder, // filterColumn, // filterQuery); //} //public async Task<ActionResult<ApiResult<Country>>> GetCountries( //int pageIndex = 0, //int pageSize = 10, //string sortColumn = null, //string sortOrder = null, //string filterColumn = null, //string filterQuery = null) //{ // return await ApiResult<Country>.CreateAsync( // _context.Countries // .Select(c => new Country() // { // Id = c.Id, // Name = c.Name, // ISO2 = c.ISO2, // ISO3 = c.ISO3, // TotCities = c.Cities.Count // }), // pageIndex, // pageSize, // sortColumn, // sortOrder, // filterColumn, // filterQuery); //} // GET: api/Countries/5 [HttpGet("{id}")] public async Task<ActionResult<Country>> GetCountry(int id) { var country = await _context.Countries.FindAsync(id); if (country == null) { return NotFound(); } return country; } // PUT: api/Countries/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> PutCountry(int id, Country country) { if (id != country.Id) { return BadRequest(); } _context.Entry(country).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CountryExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Countries // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public async Task<ActionResult<Country>> PostCountry(Country country) { _context.Countries.Add(country); await _context.SaveChangesAsync(); return CreatedAtAction("GetCountry", new { id = country.Id }, country); } // DELETE: api/Countries/5 [HttpDelete("{id}")] public async Task<ActionResult<Country>> DeleteCountry(int id) { var country = await _context.Countries.FindAsync(id); if (country == null) { return NotFound(); } _context.Countries.Remove(country); await _context.SaveChangesAsync(); return NoContent(); } private bool CountryExists(int id) { return _context.Countries.Any(e => e.Id == id); } [HttpPost] [Route("IsDupeField")] public bool IsDupeField( int countryId, string fieldName, string fieldValue) { // Standard approach(using strongly-typed LAMBA expressions) //switch (fieldName) //{ // case "name": // return _context.Countries.Any( // c => c.Name == fieldValue && c.Id != countryId); // case "iso2": // return _context.Countries.Any( // c => c.ISO2 == fieldValue && c.Id != countryId); // case "iso3": // return _context.Countries.Any( // c => c.ISO3 == fieldValue && c.Id != countryId); // default: // return false; //} // Dynamic approach (using System.Linq.Dynamic.Core) return (ApiResult<Country>.IsValidProperty(fieldName, true)) ? _context.Countries.Any( string.Format("{0} == @0 && Id != @1", fieldName), fieldValue, countryId) : false; } } }
32.561644
119
0.459823
[ "MIT" ]
FlorianMeinhart/ASP.NET-Core-5-and-Angular
Chapter_08/WorldCities/Controllers/CountriesController.cs
7,133
C#
using System; using System.Collections.Generic; using Xamarin.Forms; using XamarinEvolve.DataObjects; using XamarinEvolve.Clients.Portable; namespace XamarinEvolve.Clients.UI { public class SpeakerCell: ViewCell { readonly INavigation navigation; string sessionId; public SpeakerCell (string sessionId, INavigation navigation = null) { this.sessionId = sessionId; Height = 60; View = new SpeakerCellView (); StyleId = "disclosure"; this.navigation = navigation; } protected override async void OnTapped() { base.OnTapped(); if (navigation == null) return; var speaker = BindingContext as Speaker; if (speaker == null) return; App.Logger.TrackPage(AppPage.Speaker.ToString(), speaker.FullName); await navigation.PushAsync(new SpeakerDetailsPage(sessionId) { Speaker = speaker }); } } public partial class SpeakerCellView : ContentView { public SpeakerCellView() { InitializeComponent(); } } }
26.265306
80
0.544678
[ "MIT" ]
BeeLabs/app-evolve
src/XamarinEvolve.Clients.UI/Cells/SpeakerCell.xaml.cs
1,289
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers.Text; using System.Collections.Sequences; using System.Text.Http; namespace System.Diagnostics { public abstract class Log { public Level CurrentLevel; public bool IsVerbose { get { return CurrentLevel >= Level.Verbose; } } public abstract void LogMessage(Level level, string message); public virtual void LogMessage(Level level, string format, params object[] args) { LogMessage(level, String.Format(format, args)); } public void LogVerbose(string message) { if (CurrentLevel >= Level.Verbose) { LogMessage(Level.Verbose, message); } } public void LogWarning(string message) { if (CurrentLevel >= Level.Warning) { LogMessage(Level.Warning, message); } } public void LogError(string message) { if (CurrentLevel >= Level.Error) { LogMessage(Level.Error, message); } } public enum Level { Off = -1, Error = 0, Warning = 10, Verbose = 20, } } public class ConsoleLog : Log { object s_lock = new object(); public ConsoleLog(Log.Level level) { CurrentLevel = level; } public override void LogMessage(Level level, string message) { lock(s_lock) { ConsoleColor oldColor = Console.ForegroundColor; switch (level) { case Level.Error: Console.ForegroundColor = ConsoleColor.Red; Console.Write("ERROR: "); break; case Level.Warning: Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("WARNING: "); break; } Console.WriteLine(message); Console.ForegroundColor = oldColor; } } } public static class HttpLogExtensions { public static void LogRequest(this Log log, HttpRequest request) { if (log.IsVerbose) { // TODO: this is much ceremony. We need to do something with this. ReadOnlyBytes.AsUtf8 maybe? log.LogMessage(Log.Level.Verbose, "\tMethod: {0}", request.Verb.ToUtf8String(SymbolTable.InvariantUtf8).ToString()); log.LogMessage(Log.Level.Verbose, "\tRequest-URI: {0}", request.Path.ToUtf8String(SymbolTable.InvariantUtf8).ToString()); log.LogMessage(Log.Level.Verbose, "\tHTTP-Version: {0}", request.Version.ToUtf8String(SymbolTable.InvariantUtf8).ToString()); log.LogMessage(Log.Level.Verbose, "\tHttp Headers:"); var position = Position.First; while(request.Headers.TryGet(ref position, out var header, true)) { log.LogMessage(Log.Level.Verbose, "\t\t{0}: {1}", header.Name.ToUtf8String(SymbolTable.InvariantUtf8).ToString(), header.Value.ToUtf8String(SymbolTable.InvariantUtf8).ToString()); } var body = request.Body.ToString(SymbolTable.InvariantUtf8); log.LogMessage(Log.Level.Verbose, body); } } } }
33.981308
199
0.543454
[ "MIT" ]
maryamariyan/corefxlab
samples/LowAllocationWebServer/LowAllocationWebServerLibrary/Log.cs
3,638
C#
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGame.Extended.NuclexGui.Controls.Desktop { public class GuiButtonControl : GuiPressableControl { /// <summary>Text that will be shown on the button</summary> public string Text; public Texture2D Texture; public Rectangle SourceRectangle; /// <summary>Will be triggered when the button is pressed</summary> public event EventHandler Pressed; /// <summary>Called when the button is pressed</summary> protected override void OnPressed() { if (Pressed != null) Pressed(this, EventArgs.Empty); } public GuiButtonControl() : base() { SourceRectangle = new Rectangle(); } } }
27.633333
75
0.629674
[ "MIT" ]
Acidburn0zzz/MonoGame.Extended
Source/MonoGame.Extended.NuclexGui/Controls/Desktop/GuiButtonControl.cs
831
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Xms.Core; using Xms.Core.Context; using Xms.Core.Data; using Xms.Data.Provider; using Xms.Flow; using Xms.Flow.Core; using Xms.Flow.Domain; using Xms.Infrastructure.Utility; using Xms.Schema.Entity; using Xms.Solution; using Xms.Web.Customize.Models; using Xms.Web.Framework.Context; using Xms.Web.Framework.Models; using Xms.Web.Framework.Mvc; namespace Xms.Web.Customize.Controllers { /// <summary> /// 流程管理控制器 /// </summary> public class FlowController : CustomizeBaseController { private readonly IEntityFinder _entityFinder; private readonly IWorkFlowFinder _workFlowFinder; private readonly IWorkFlowCreater _workFlowCreater; private readonly IWorkFlowUpdater _workFlowUpdater; private readonly IWorkFlowDeleter _workFlowDeleter; private readonly IWorkFlowInstanceService _workFlowInstanceService; private readonly IWorkFlowProcessFinder _workFlowProcessFinder; private readonly IProcessStageService _processStageService; private readonly IWorkFlowStepService _workFlowStepService; private readonly IWorkFlowCanceller _workFlowCanceller; public FlowController(IWebAppContext appContext , IEntityFinder entityFinder , ISolutionService solutionService , IWorkFlowFinder workFlowFinder , IWorkFlowCreater workFlowCreater , IWorkFlowUpdater workFlowUpdater , IWorkFlowDeleter workFlowDeleter , IWorkFlowProcessFinder workFlowProcessFinder , IProcessStageService processStageService , IWorkFlowInstanceService workFlowInstanceService , IWorkFlowStepService workFlowStepService , IWorkFlowCanceller workFlowCanceller) : base(appContext, solutionService) { _entityFinder = entityFinder; _workFlowFinder = workFlowFinder; _workFlowCreater = workFlowCreater; _workFlowUpdater = workFlowUpdater; _workFlowDeleter = workFlowDeleter; _workFlowInstanceService = workFlowInstanceService; _workFlowProcessFinder = workFlowProcessFinder; _processStageService = processStageService; _workFlowStepService = workFlowStepService; _workFlowCanceller = workFlowCanceller; } [Description("流程列表")] public IActionResult Index(WorkFlowModel model) { if (!model.LoadData) { return DynamicResult(model); } FilterContainer<WorkFlow> filter = FilterContainerBuilder.Build<WorkFlow>(); if (model.Name.IsNotEmpty()) { filter.And(n => n.Name.Like(model.Name)); } if (model.GetAll) { model.Page = 1; model.PageSize = WebContext.PlatformSettings.MaxFetchRecords; } else if (!model.PageSizeBySeted && CurrentUser.UserSettings.PagingLimit > 0) { model.PageSize = CurrentUser.UserSettings.PagingLimit; } model.PageSize = model.PageSize > WebContext.PlatformSettings.MaxFetchRecords ? WebContext.PlatformSettings.MaxFetchRecords : model.PageSize; PagedList<WorkFlow> result = _workFlowFinder.QueryPaged(x => x .Page(model.Page, model.PageSize) .Where(filter) .Sort(n => n.OnFile(model.SortBy).ByDirection(model.SortDirection)) , SolutionId.Value, true); model.Items = result.Items; model.TotalItems = result.TotalItems; model.SolutionId = SolutionId.Value; return DynamicResult(model); } [Description("设置流程可用状态")] [HttpPost] public IActionResult SetWorkFlowState([FromBody]SetRecordStateModel model) { if (model.RecordId.IsEmpty()) { return NotSpecifiedRecord(); } return _workFlowUpdater.UpdateState(model.IsEnabled, model.RecordId).UpdateResult(T); } [Description("设置流程权限启用状态")] [HttpPost] public IActionResult SetAuthorizationState([FromBody]SetFlowAuthorizationStateModel model) { if (model.RecordId.IsEmpty()) { return NotSpecifiedRecord(); } return _workFlowUpdater.UpdateAuthorization(model.IsAuthorization, model.RecordId).UpdateResult(T); } #region 审批流程 [Description("新建流程")] public IActionResult CreateWorkFlow() { CreateWorkFlowModel model = new CreateWorkFlowModel { SolutionId = SolutionId.Value }; return View(model); } [Description("新建流程")] [HttpPost] public IActionResult CreateWorkFlow([FromBody]CreateWorkFlowModel model) { if (model.StepData.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { List<WorkFlowStep> steps = new List<WorkFlowStep>(); steps = steps.DeserializeFromJson(model.StepData.UrlDecode()); if (steps.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { var entity = new WorkFlow(); model.CopyTo(entity); entity.WorkFlowId = Guid.NewGuid(); entity.CreatedBy = CurrentUser.SystemUserId; entity.CreatedOn = DateTime.Now; entity.StateCode = RecordState.Enabled; entity.SolutionId = SolutionId.Value; entity.Category = 1; foreach (var item in steps) { item.Conditions = item.Conditions.UrlDecode(); item.WorkFlowId = entity.WorkFlowId; } entity.Steps = steps; _workFlowCreater.Create(entity); _workFlowStepService.CreateMany(steps); return CreateSuccess(new { id = entity.WorkFlowId }); } } return CreateFailure(GetModelErrors()); } [Description("编辑流程")] public IActionResult EditWorkFlow(Guid id) { if (id.Equals(Guid.Empty)) { return NotFound(); } EditWorkFlowModel model = new EditWorkFlowModel(); var entity = _workFlowFinder.FindById(id); if (entity == null) { return NotFound(); } entity.CopyTo(model); model.Steps = _workFlowStepService.Query(n => n.Where(f => f.WorkFlowId == id).Sort(s => s.SortAscending(f => f.StepOrder))); model.StepData = model.Steps.SerializeToJson(); model.EntityMetas = _entityFinder.FindById(entity.EntityId); return View(model); } [Description("编辑流程")] [HttpPost] //[ValidateAntiForgeryToken] public IActionResult EditWorkFlow([FromBody]EditWorkFlowModel model) { if (model.StepData.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { model.StepData = model.StepData.UrlDecode(); List<WorkFlowStep> steps = new List<WorkFlowStep>(); steps = steps.DeserializeFromJson(model.StepData); if (steps.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { var entity = _workFlowFinder.FindById(model.WorkFlowId); model.EntityId = entity.EntityId; model.CopyTo(entity); _workFlowUpdater.Update(entity); //steps var orginalSteps = _workFlowStepService.Query(n => n.Where(f => f.WorkFlowId == model.WorkFlowId).Sort(s => s.SortAscending(f => f.StepOrder))); foreach (var item in steps) { item.Conditions = item.Conditions.UrlDecode(); var old = orginalSteps.Find(n => n.WorkFlowStepId == item.WorkFlowStepId); if (old == null) { item.WorkFlowId = entity.WorkFlowId; _workFlowStepService.Create(item); } else { _workFlowStepService.Update(item); orginalSteps.Remove(old); } } if (orginalSteps.NotEmpty()) { var lostid = orginalSteps.Select(n => n.WorkFlowStepId).ToArray(); _workFlowStepService.DeleteById(lostid); } return UpdateSuccess(); } } return JError(GetModelErrors()); } [Description("删除流程")] [HttpPost] public IActionResult DeleteWorkFlow([FromBody]DeleteManyModel model) { return _workFlowDeleter.DeleteById(model.RecordId).DeleteResult(T); } [Description("流程设计")] public IActionResult FlowDesign() { return View(); } [Description("流程实例")] public IActionResult WorkFlowInstances(WorkFlowInstanceModel model) { FilterContainer<WorkFlowInstance> filter = FilterContainerBuilder.Build<WorkFlowInstance>(); filter.And(n => n.WorkFlowId == model.WorkFlowId); if (model.GetAll) { model.Page = 1; model.PageSize = WebContext.PlatformSettings.MaxFetchRecords; } else if (!model.PageSizeBySeted && CurrentUser.UserSettings.PagingLimit > 0) { model.PageSize = CurrentUser.UserSettings.PagingLimit; } model.PageSize = model.PageSize > WebContext.PlatformSettings.MaxFetchRecords ? WebContext.PlatformSettings.MaxFetchRecords : model.PageSize; PagedList<WorkFlowInstance> result = _workFlowInstanceService.QueryPaged(x => x .Page(model.Page, model.PageSize) .Where(filter) .Sort(n => n.OnFile(model.SortBy).ByDirection(model.SortDirection)) ); model.Items = result.Items; model.TotalItems = result.TotalItems; return DynamicResult(model); } [Description("流程监控")] public IActionResult WorkFlowProcess(WorkFlowProcessModel model) { if (!model.IsSortBySeted) { model.SortBy = "steporder"; model.SortDirection = 0; } FilterContainer<WorkFlowProcess> filter = FilterContainerBuilder.Build<WorkFlowProcess>(); filter.And(n => n.WorkFlowInstanceId == model.WorkFlowInstanceId); if (model.GetAll) { List<WorkFlowProcess> result = _workFlowProcessFinder.Query(x => x .Page(model.Page, model.PageSize) .Where(filter) .Sort(n => n.OnFile(model.SortBy).ByDirection(model.SortDirection)) ); model.Items = result; model.TotalItems = result.Count; } else { PagedList<WorkFlowProcess> result = _workFlowProcessFinder.QueryPaged(x => x .Page(model.Page, model.PageSize) .Where(filter) .Sort(n => n.OnFile(model.SortBy).ByDirection(model.SortDirection)) ); model.Items = result.Items; model.TotalItems = result.TotalItems; } return DynamicResult(model); } [HttpPost] [Description("流程撤销")] public IActionResult Cancel(Guid id) { var instance = _workFlowInstanceService.FindById(id); if (instance != null) { WorkFlowCancellationContext context = new WorkFlowCancellationContext { EntityMetaData = _entityFinder.FindById(instance.EntityId) , ObjectId = instance.ObjectId }; var flag = _workFlowCanceller.Cancel(context); if (flag.IsSuccess) { return JOk(T["operation_success"]); } else { return JError(flag.Message); } } return JError(T["operation_error"]); } #endregion #region 业务流程 [Description("新建业务流程")] public IActionResult CreateBusinessFlow() { CreateBusinessFlowModel model = new CreateBusinessFlowModel { SolutionId = SolutionId.Value }; return View(model); } [Description("新建业务流程")] [HttpPost] //[ValidateAntiForgeryToken] public IActionResult CreateBusinessFlow([FromBody]CreateWorkFlowModel model) { if (model.StepData.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } List<ProcessStage> steps = new List<ProcessStage>(); steps = steps.DeserializeFromJson(model.StepData.UrlDecode()); if (steps.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { var entity = new WorkFlow(); model.CopyTo(entity); entity.WorkFlowId = Guid.NewGuid(); entity.Category = 2; entity.CreatedBy = CurrentUser.SystemUserId; entity.CreatedOn = DateTime.Now; entity.StateCode = Core.RecordState.Enabled; entity.SolutionId = SolutionId.Value; foreach (var item in steps) { item.ProcessStageId = Guid.NewGuid(); item.WorkFlowId = entity.WorkFlowId; } _workFlowCreater.Create(entity); _processStageService.CreateMany(steps); return CreateSuccess(new { id = entity.WorkFlowId }); } return CreateFailure(GetModelErrors()); } [Description("编辑流程")] public IActionResult EditBusinessFlow(Guid id) { if (id.Equals(Guid.Empty)) { return NotFound(); } EditBusinessFlowModel model = new EditBusinessFlowModel(); var entity = _workFlowFinder.FindById(id); if (entity == null) { return NotFound(); } entity.CopyTo(model); model.ProcessStages = _processStageService.Query(n => n.Where(f => f.WorkFlowId == id).Sort(s => s.SortAscending(f => f.StageOrder))); model.StepData = model.ProcessStages.SerializeToJson(); return View(model); } [Description("编辑流程")] [HttpPost] //[ValidateAntiForgeryToken] public IActionResult EditBusinessFlow([FromBody]EditWorkFlowModel model) { string msg = string.Empty; if (model.StepData.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } model.StepData = model.StepData.UrlDecode(); List<ProcessStage> steps = new List<ProcessStage>(); steps = steps.DeserializeFromJson(model.StepData); if (steps.IsEmpty()) { ModelState.AddModelError("", T["workflow_step_empty"]); } if (ModelState.IsValid) { var entity = _workFlowFinder.FindById(model.WorkFlowId); model.EntityId = entity.EntityId; model.StateCode = entity.StateCode; model.CopyTo(entity); _workFlowUpdater.Update(entity); var orginalSteps = _processStageService.Query(n => n.Where(f => f.WorkFlowId == model.WorkFlowId).Sort(s => s.SortAscending(f => f.StageOrder))); foreach (var item in steps) { item.WorkFlowId = entity.WorkFlowId; var old = orginalSteps.Find(n => n.ProcessStageId == item.ProcessStageId); if (old == null) { _processStageService.Create(item); } else { _processStageService.Update(item); orginalSteps.Remove(old); } } if (orginalSteps.NotEmpty()) { var lostid = orginalSteps.Select(n => n.ProcessStageId).ToArray(); _processStageService.DeleteById(lostid); } return UpdateSuccess(); } return UpdateFailure(GetModelErrors()); } #endregion } }
38.139831
164
0.539218
[ "MIT" ]
feilingdeng/xms
Presentation/Xms.Web/Areas/Customize/Controllers/FlowController.cs
18,190
C#
// Copyright (c) 2015 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 Microsoft.Win32; using System.IO; using System.Reflection; using Alachisoft.NCache.Common; using log4net.Appender; using System.Diagnostics; using System.Text; using log4net.Filter; namespace Alachisoft.NCache.Common.Util { /// <summary> /// Summary description for Log. /// </summary> public sealed class Log4net { static string _cacheserver="NCache"; /// <summary>Configuration file folder name</summary> private const string DIRNAME = @"log-files"; private static byte[] log4netXML = Encoding.ASCII.GetBytes("<?xml version=\"1.0\"?> <configuration> <configSections> <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture = neutral, PublicKeyToken=1b44e1d426115821 \"/> </configSections> <log4net> </log4net> </configuration>"); public static log4net.Core.Level criticalInfo = new log4net.Core.Level(5000000, "CRIT", "INFO"); /// <summary>Path of the configuration folder.</summary> static private string s_configDir = ""; static private string path = ""; static object lockObj = new Object(); /// <summary> /// Scans the registry and locates the configuration file. /// </summary> static Log4net() { s_configDir = AppUtil.InstallDir; try { s_configDir = System.IO.Path.Combine(s_configDir, DIRNAME); } catch { } if (s_configDir == null && s_configDir.Length > 0) { s_configDir = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; s_configDir = System.IO.Path.Combine(s_configDir, DIRNAME); } } internal static string GetLogPath() { if (path.Length < 1) { path = s_configDir; } try { log4net.LogManager.GetRepository().LevelMap.Add(criticalInfo); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); } catch (Exception e) { AppUtil.LogEvent(_cacheserver, e.ToString(), System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError); } return path; } /// <summary> /// Start the cache logging functionality. /// </summary> public static string Initialize(IDictionary properties, string partitionID, string cacheName) { return Initialize(properties, partitionID, cacheName, false, false); } /// <summary> /// Start the cache logging functionality. /// </summary> public static string Initialize(IDictionary properties, string partitionID, string cacheName, bool isStartedAsMirror, bool inproc) { lock (lockObj) { MemoryStream logStream = new MemoryStream(log4netXML); log4net.Config.XmlConfigurator.Configure(logStream); string logger_name = ""; try { logger_name = cacheName; if (partitionID != null && partitionID.Length > 0) logger_name += "-" + partitionID; if (isStartedAsMirror) logger_name += "-" + "replica"; if (inproc && !isStartedAsMirror) logger_name += "." + System.Diagnostics.Process.GetCurrentProcess().Id; //Add loggerName to be accessed w.r.t the cache Name if (!LoggingInformation.cacheLogger.Contains(logger_name)) { LoggingInformation.cacheLogger.Add(logger_name, logger_name); string LogExceptions = ""; if (logger_name == "LogExceptions") LogExceptions = "\\LogExceptions"; string fileName = GetLogPath() + LogExceptions + "\\" + logger_name + "_" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".txt"; ; AddAppender(logger_name, CreateBufferAppender(logger_name, fileName)); if (properties != null) { if (properties.Contains("trace-errors")) { if (Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "ERROR"); } } if (properties.Contains("trace-notices")) { if (Convert.ToBoolean(properties["trace-notices"])) { SetLevel(logger_name, "INFO"); } } if (properties.Contains("trace-warnings")) if (Convert.ToBoolean(properties["trace-warnings"])) { SetLevel(logger_name, "WARN"); } if (properties.Contains("trace-debug")) if (Convert.ToBoolean(properties["trace-debug"])) { SetLevel(logger_name, "ALL"); } if (properties.Contains("enabled")) { if (!Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "OFF"); } } } else { SetLevel(logger_name, "WARN"); } return logger_name; } else { if (properties != null) { if (properties.Contains("trace-errors")) { if (Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "ERROR"); } } if (properties.Contains("trace-notices")) { if (Convert.ToBoolean(properties["trace-notices"])) { SetLevel(logger_name, "INFO"); } } if (properties.Contains("trace-warnings")) if (Convert.ToBoolean(properties["trace-warnings"])) { SetLevel(logger_name, "WARN"); } if (properties.Contains("trace-debug")) if (Convert.ToBoolean(properties["trace-debug"])) { SetLevel(logger_name, "ALL"); } if (properties.Contains("enabled")) { if (!Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "OFF"); } } } else { SetLevel(logger_name, "WARN"); } return logger_name; } } catch (Exception e) { AppUtil.LogEvent(_cacheserver, "Failed to open log. " + e, System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError); } return logger_name; } } /// <summary> /// intitializes Known name based log files (will not log License Logs at service Startup /// </summary> /// <param name="loggerName">Enum of Known loggerNames</param> public static void Initialize(NCacheLog.LoggerNames loggerName) { if (loggerName != NCacheLog.LoggerNames.Licence) { Initialize(loggerName, null); } } /// <summary> /// intitializes Known name based log files /// </summary> /// <param name="loggerName">Enum of Known loggerNames</param> /// <param name="cacheName">cacheName use the other override</param> public static void Initialize(NCacheLog.LoggerNames loggerNameEnum, string cacheName) { lock (lockObj) { MemoryStream logStream = new MemoryStream(log4netXML); log4net.Config.XmlConfigurator.Configure(logStream); string logName = loggerNameEnum.ToString(); string filename = logName; if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs && (cacheName != null && cacheName.Length > 0)) { filename = filename + "." + cacheName + "." + System.Diagnostics.Process.GetCurrentProcess().Id; // changing the name here will invalidate static log checks automatically since LoggerName == ClientLogs logName = cacheName + System.Diagnostics.Process.GetCurrentProcess().Id; } else { if (cacheName != null && cacheName.Length > 0) filename = cacheName; } //If Logger is already present, can either be a cache or Client if (LoggingInformation.GetLoggerName(logName) != null) { if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs) return; // clientLogs alread initiated else { if (LoggingInformation.GetStaticLoggerName(logName) != null) return; // Log already initiated else { logName = logName + DateTime.Now; } } } else { if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs) { if (LoggingInformation.GetStaticLoggerName(logName) != null) return; // Log already initiated else { logName = logName + DateTime.Now; } } } filename = filename + "." + Environment.MachineName.ToLower() + "." + DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt"; string filepath = ""; if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath)) { try { DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath); } catch (Exception ex) { throw new Exception("Unable to initialize the log file", ex); } } try { filepath = Path.Combine(filepath, loggerNameEnum.ToString()); if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); filepath = Path.Combine(filepath, filename); LoggingInformation.cacheLogger.Add(logName, logName); if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs) { LoggingInformation.staticCacheLogger.Add(loggerNameEnum.ToString(), logName); } SetLevel(logName, NCacheLog.Level.OFF.ToString()); AddAppender(logName, CreateBufferAppender(logName, filepath)); } catch (Exception) { throw; } } } /// <summary> /// Stop the cache logging functionality. /// </summary> public static void Close(string cacheName) { lock (lockObj) { if (cacheName != null) if (cacheName.Length != 0) { string temploggerName = LoggingInformation.GetLoggerName(cacheName); //called at remove cache if (temploggerName != null) { SetLevel(temploggerName, "OFF"); if (temploggerName != null) { log4net.ILog log = log4net.LogManager.GetLogger(temploggerName); log4net.Core.IAppenderAttachable closingAppenders = (log4net.Core.IAppenderAttachable)log.Logger; AppenderCollection collection = closingAppenders.Appenders; for (int i = 0; i < collection.Count; i++) { if (collection[i] is BufferingForwardingAppender) { //This FLUSH and close the current appenders along with all of its children appenders ((BufferingForwardingAppender)collection[i]).Close(); } } RemoveAllAppender(temploggerName); LoggingInformation.cacheLogger.Remove(cacheName); } } } } } /// <summary> /// Creates Buffer Appender, Responsible for storing all logging events in memory buffer /// and writing them down when by passing the logging events on to the file appender it holds /// when its buffer becomes full /// Can also be made a lossy logger which writes only writes down to a file when a specific crieteria/condition is met /// </summary> /// <param name="cacheName">CacheName used to name the Buffer Appender</param> /// <param name="fileName">File name to log into</param> /// <returns>Returns the created Appender</returns> private static log4net.Appender.IAppender CreateBufferAppender(string cacheName, string fileName) { log4net.Appender.BufferingForwardingAppender appender = new BufferingForwardingAppender(); appender.Name = "BufferingForwardingAppender" + cacheName; //Pick from config int bufferSize = NCacheLog.bufferDefaultSize; NCacheLog.ReadConfig(out bufferSize); if (bufferSize == NCacheLog.bufferDefaultSize) NCacheLog.ReadClientConfig(out bufferSize); if (bufferSize < 1) bufferSize = NCacheLog.bufferDefaultSize; appender.BufferSize = bufferSize; //Threshold is maintained by the logger rather than the appenders appender.Threshold = log4net.Core.Level.All; //Adds the appender to which it will pass on all the logging levels upon filling up the buffer appender.AddAppender(CreateRollingFileAppender(cacheName, fileName)); //necessary to apply the appender property changes appender.ActivateOptions(); return appender; } /// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private static log4net.Appender.IAppender CreateRollingFileAppender(string cacheName, string fileName) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + cacheName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = false; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; //Threshold is maintained by the logger rather than the appenders appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-35logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; } /// <summary> /// Add a desired appender to the logger /// </summary> /// <param name="loggerName">Name of the logger to which the appender is to be added</param> /// <param name="appender">Appender to add to the logger</param> private static void AddAppender(string loggerName, log4net.Appender.IAppender appender) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; l.AddAppender(appender); } private static void RemoveAllAppender(string loggerName) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; l.RemoveAllAppenders(); } /// <summary> /// Set desire level for a specific logger /// </summary> /// <param name="loggerName">Name of the logger</param> /// <param name="levelName">Name of the desire level</param> private static void SetLevel(string loggerName, string levelName) { log4net.Core.Level lvl; switch (levelName.ToLower()) { case "all": lvl = log4net.Core.Level.All; break; case "error": lvl = log4net.Core.Level.Error; break; case "fatal": lvl = log4net.Core.Level.Fatal; break; case "info": lvl = log4net.Core.Level.Info; break; case "debug": lvl = log4net.Core.Level.Debug; break; case "warn": lvl = log4net.Core.Level.Warn; break; case "off": lvl = log4net.Core.Level.Off; break; default: lvl = log4net.Core.Level.All; break; } //If the logger doesnot exist it will create one else fetches one log4net.ILog log = log4net.LogManager.GetLogger(loggerName); //adds the logger as a seperate hierchy, not dependant on any other logger log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; //Applies the logger threshold level l.Level = l.Hierarchy.LevelMap[levelName]; IAppender[] appenderCol = log.Logger.Repository.GetAppenders(); for (int i = 0; i < appenderCol.Length; i++) { IAppender appender = appenderCol[i]; if (appender != null) { if (appender is BufferingForwardingAppender) { ((BufferingForwardingAppender)appender).Threshold = lvl; } if (appender is RollingFileAppender) { ((RollingFileAppender)appender).Threshold = lvl; } } } } private static void EnableFilter(string loggerName, string stringToMatch) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; } /// <summary> /// To find an appender /// </summary> /// <param name="appenderName">name of the appender to find</param> /// <returns> if not found null will be returned</returns> public static log4net.Appender.IAppender FindAppender(string appenderName) { foreach (log4net.Appender.IAppender appender in log4net.LogManager.GetRepository().GetAppenders()) { if (appender.Name == appenderName) { return appender; } } return null; } ~Log4net() { IEnumerator cacheNameEnum = LoggingInformation.cacheLogger.GetEnumerator(); while (cacheNameEnum.MoveNext()) { Close((string)cacheNameEnum.Current); } cacheNameEnum = LoggingInformation.staticCacheLogger.GetEnumerator(); while (cacheNameEnum.MoveNext()) { Close((string)cacheNameEnum.Current); } } } }
39.59401
355
0.491217
[ "Apache-2.0" ]
NCacheDev/NCache
Src/NCCommon/Util/Log4net.cs
23,796
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pinwheel.TextureGraph; namespace Pinwheel.TextureGraph { [TCustomParametersDrawer(typeof(TSharpenNode))] public class TSharpenNodeParamsDrawer : TParametersDrawer { private static readonly GUIContent intensityGUI = new GUIContent("Intensity", "Intensity of the effect"); public override void DrawGUI(TAbstractTextureNode target) { TSharpenNode n = target as TSharpenNode; n.Intensity = TParamGUI.FloatField(intensityGUI, n.Intensity); } } }
30.95
114
0.701131
[ "MIT" ]
Abelark/Project-3---Rocket-Punch
Assets/Polaris - Low Poly Ecosystem/TextureGraph/Core/Editor/Nodes/TSharpenNodeParamsDrawer.cs
619
C#
using BackendAPI.Utils; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BackendAPI.Objects.Implementation.DeckActions.OBS { public class SceneItemVisibilityAction : AbstractDeckAction { public enum ItemVisibility { [Description("OBSDESCRIPTIONVISIBLE")] Visible, [Description("OBSDESCRIPTIONGONE")] Gone } public string SceneName { get; set; } = ""; [ActionPropertyInclude] [ActionPropertyDescription("DESCRIPTIONSCENEITEM")] public String SceneItem { get; set; } = ""; [ActionPropertyInclude] [ActionPropertyDescription("DESCRIPTIONSCENEVISIBILITY")] public ItemVisibility ItemVisibilityStatus { get; set; } public void SceneItemHelper() { var oldSceneName = new String(SceneName.ToCharArray()); var oldScene = new String(SceneItem.ToCharArray()); dynamic form = Activator.CreateInstance(FindType("Forms.ActionHelperForms.OBS.OBSSceneItemVisibilityHelper")) as Form; var execAction = CloneAction() as SceneItemVisibilityAction; execAction.SceneName = SceneName; execAction.SceneItem = SceneItem; form.ModifiableAction = execAction; if (form.ShowDialog() == DialogResult.OK) { SceneName = form.ModifiableAction.SceneName; SceneItem = form.ModifiableAction.SceneItem; } else { SceneName = oldSceneName; SceneItem = oldScene; } } public override AbstractDeckAction CloneAction() { return new SceneItemVisibilityAction(); } public override DeckActionCategory GetActionCategory() { return DeckActionCategory.OBS; } public override string GetActionName() { return Texts.rm.GetString("DECKOBSVISIBILITYSCENE", Texts.cultereinfo); } public override void OnButtonDown(DeckDevice deckDevice) { } public override void OnButtonUp(DeckDevice deckDevice) { if (string.IsNullOrEmpty(SceneItem) || string.IsNullOrEmpty(SceneName)) return; OBSUtils.SetSceneItemVisibility(SceneItem, SceneName, ItemVisibilityStatus == ItemVisibility.Visible); } } }
32.166667
130
0.636509
[ "MIT" ]
brutalzinn/ButtonDeck
BackendAPI/Backend/Objects/Implementation/DeckActions/OBS/SceneItemVisibilityAction.cs
2,511
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; using System.Windows.Threading; namespace SnakeGame_TA18E_Vettik { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { const double CellSize = 60D; const int CellCount = 8; DispatcherTimer timer; Random rnd = new Random(); GameStatus gameStatus; int foodRow; int foodCol; Direction snakeDirection; LinkedList<Rectangle> snakeParts = new LinkedList<Rectangle>(); int points; public MainWindow() { InitializeComponent(); DrawBoardBackground(); InitFood(); InitSnake(); ChangePoints(0); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(0.25); timer.Tick += Timer_Tick; timer.Start(); ChangeGameStatus(GameStatus.Ongoing); } private void DrawBoardBackground() { SolidColorBrush color1 = Brushes.Green; SolidColorBrush color2 = Brushes.YellowGreen; for (int row = 0; row < CellCount; row++) { SolidColorBrush color = row % 2 == 0 ? color1 : color2; for (int col = 0; col < CellCount; col++) { InitRectangle( CellSize, row, col, color, 0); color = color == color1 ? color2 : color1; } } } private void ChangeGameStatus(GameStatus newGameStatus) { gameStatus = newGameStatus; lblGameStatus.Content = $"Status: {gameStatus}"; } private void ChangePoints(int newPoints) { points = newPoints; lblPoints.Content = $"Points: {points}"; } private void InitFood() { foodShape.Height = CellSize; foodShape.Width = CellSize; foodRow = rnd.Next(0, CellCount); foodCol = rnd.Next(0, CellCount); SetShape(foodShape, foodRow, foodCol); } private void InitSnake() { int index = CellCount / 2; for (int i = 0; i < 3; i++) { int row = index; int col = index + i; Rectangle r = InitRectangle( CellSize, row, col, Brushes.IndianRed, 10); snakeParts.AddLast(r); } ChangeSnakeDirection(Direction.Left); } private void ChangeSnakeDirection(Direction direction) { if (snakeDirection == Direction.Left && direction == Direction.Right) { return; } if (snakeDirection == Direction.Right && direction == Direction.Left) { return; } if (snakeDirection == Direction.Up && direction == Direction.Down) { return; } if (snakeDirection == Direction.Down && direction == Direction.Up) { return; } snakeDirection = direction; lblSnakeDirection.Content = $"Direction: {direction}"; } private void MoveSnake() { Rectangle currentHead = snakeParts.First.Value; Location currentHeadLocation = (Location)currentHead.Tag; int newHeadRow = currentHeadLocation.Row; int newHeadCol = currentHeadLocation.Col; switch (snakeDirection) { case Direction.Up: newHeadRow--; break; case Direction.Down: newHeadRow++; break; case Direction.Left: newHeadCol--; break; case Direction.Right: newHeadCol++; break; } bool outOfBoundaries = newHeadRow < 0 || newHeadRow >= CellCount || newHeadCol < 0 || newHeadCol >= CellCount; if (outOfBoundaries) { ChangeGameStatus(GameStatus.GameOver); return; } bool food = newHeadRow == foodRow && newHeadCol == foodCol; foreach (Rectangle r in snakeParts) { if (!food && snakeParts.Last.Value == r) { continue; } Location location = (Location)r.Tag; if (location.Row == newHeadRow && location.Col == newHeadCol) { ChangeGameStatus(GameStatus.GameOver); return; } } if (food) { ChangePoints(points + 1); InitFood(); Rectangle r = InitRectangle( CellSize, newHeadRow, newHeadCol, Brushes.IndianRed, 10); snakeParts.AddFirst(r); } else { Rectangle newHead = snakeParts.Last.Value; newHead.Tag = new Location(newHeadRow, newHeadCol); SetShape(newHead, newHeadRow, newHeadCol); snakeParts.RemoveLast(); snakeParts.AddFirst(newHead); } } private Rectangle InitRectangle( double size, int row, int col, Brush fill, int zIndex) { Rectangle r = new Rectangle(); r.Height = size; r.Width = size; r.Fill = fill; Panel.SetZIndex(r, zIndex); r.Tag = new Location(row, col); SetShape(r, row, col); board.Children.Add(r); return r; } private void SetShape( Shape shape, int row, int col) { double top = row * CellSize; double left = col * CellSize; Canvas.SetTop(shape, top); Canvas.SetLeft(shape, left); } private void Timer_Tick(object sender, EventArgs e) { if (gameStatus != GameStatus.Ongoing) { return; } MoveSnake(); } private void Window_KeyDown( object sender, KeyEventArgs e) { if (gameStatus != GameStatus.Ongoing) { return; } Direction direction; switch (e.Key) { case Key.Up: direction = Direction.Up; break; case Key.Down: direction = Direction.Down; break; case Key.Left: direction = Direction.Left; break; case Key.Right: direction = Direction.Right; break; default: return; } ChangeSnakeDirection(direction); } } }
26.693603
67
0.458628
[ "MIT" ]
Marcus0110/tpt18-project-1
SnakeGame_TA18E_Vettik/SnakeGame_TA18E_Vettik/MainWindow.xaml.cs
7,930
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.ResourceManager.Network.Models { /// <summary> The IpGroups resource information. </summary> public partial class IpGroup : Resource { /// <summary> Initializes a new instance of IpGroup. </summary> public IpGroup() { } /// <summary> Initializes a new instance of IpGroup. </summary> /// <param name="id"> Resource ID. </param> /// <param name="name"> Resource name. </param> /// <param name="type"> Resource type. </param> /// <param name="location"> Resource location. </param> /// <param name="tags"> Resource tags. </param> /// <param name="etag"> A unique read-only string that changes whenever the resource is updated. </param> /// <param name="provisioningState"> The provisioning state of the IpGroups resource. </param> /// <param name="ipAddresses"> IpAddresses/IpAddressPrefixes in the IpGroups resource. </param> /// <param name="firewalls"> List of references to Azure resources that this IpGroups is associated with. </param> internal IpGroup(string id, string name, string type, string location, IDictionary<string, string> tags, string etag, ProvisioningState? provisioningState, IList<string> ipAddresses, IList<SubResource> firewalls) : base(id, name, type, location, tags) { Etag = etag; ProvisioningState = provisioningState; IpAddresses = ipAddresses; Firewalls = firewalls; } /// <summary> A unique read-only string that changes whenever the resource is updated. </summary> public string Etag { get; } /// <summary> The provisioning state of the IpGroups resource. </summary> public ProvisioningState? ProvisioningState { get; } /// <summary> IpAddresses/IpAddressPrefixes in the IpGroups resource. </summary> public IList<string> IpAddresses { get; set; } /// <summary> List of references to Azure resources that this IpGroups is associated with. </summary> public IList<SubResource> Firewalls { get; } } }
47.604167
259
0.65733
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/IpGroup.cs
2,285
C#
using Newtonsoft.Json; using System; namespace Serenity.Services { /// <summary> /// Serialize/deserialize a SortBy object as string</summary> /// <typeparam name="T"> /// Type</typeparam> public class JsonSortByConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object.</summary> /// <param name="writer"> /// The <see cref="JsonWriter"/> to write to.</param> /// <param name="value"> /// The value.</param> /// <param name="serializer"> /// The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var sortBy = (SortBy)value; string s = sortBy.Field ?? string.Empty; if (sortBy.Descending) s += " DESC"; writer.WriteValue(s); } /// <summary> /// Reads the JSON representation of the object.</summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType"> /// Type of the object.</param> /// <param name="existingValue"> /// The existing value of object being read.</param> /// <param name="serializer"> /// The calling serializer.</param> /// <returns> /// The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var sortBy = new SortBy(); if (reader.TokenType != JsonToken.String) throw new JsonSerializationException("Unexpected end when deserializing object."); var field = ((string)reader.Value).TrimToEmpty(); if (field.EndsWith(" DESC", StringComparison.OrdinalIgnoreCase)) { sortBy.Field = field[0..^5].TrimToEmpty(); sortBy.Descending = true; } else sortBy.Field = field; return sortBy; } /// <summary> /// Determines whether this instance can convert the specified object type.</summary> /// <param name="objectType"> /// Type of the object.</param> /// <returns> /// True if this instance can convert the specified object type; otherwise, false.</returns> public override bool CanConvert(Type objectType) { return objectType == typeof(SortBy); } /// <summary> /// Gets a value indicating whether this <see cref="JsonConverter"/> can read JSON.</summary> /// <value> /// True if this <see cref="JsonConverter"/> can write JSON; otherwise, false.</value> public override bool CanRead => true; /// <summary> /// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.</summary> /// <value> /// True if this <see cref="JsonConverter"/> can write JSON; otherwise, false.</value> public override bool CanWrite => true; } }
37.840909
125
0.548649
[ "MIT" ]
JarLob/Serenity
src/Serenity.Net.Services/Json/JsonSortByConverter.cs
3,332
C#
using Microsoft.AspNetCore.Mvc; using WhatSearch.Core; using WhatSearch.Models; using WhatSearch.Services.Interfaces; using WhatSearch.WebAPIs.Filters; namespace WhatSearch.Controllers { //[Route("[controller]")] public class PageController : Controller { //[Route("")] //public IActionResult Index() //{ // return Redirect("/page"); //} SystemConfig config = Ioc.GetConfig(); [Route("")] public IActionResult Index() { return Redirect("/page/"); } [Route("page/{*pathInfo}")] public IActionResult List(string pathInfo) { return View(); } [Route("debug")] public IActionResult Debug() { return View(); } [Route("admin")] [RoleAuthorize("Admin")] public IActionResult Members() { IUserService srv = Ioc.Get<IUserService>(); dynamic model = srv.GetMembers(); return View(model); } [HttpPost] [Route("admin/updateMember")] [RoleAuthorize("Admin")] public dynamic UpdateMember([FromBody]dynamic model) { IUserService srv = Ioc.Get<IUserService>(); Member mem = srv.GetMember((string)model.name); if (mem != null) { MemberStatus newStatus = (MemberStatus)((int)model.status); if (mem.Status != newStatus) { srv.UpdateMemberStatus(mem.Name, newStatus); } string message = string.Format("{0} 狀態為 {1}", mem.DisplayName, newStatus == MemberStatus.Active ? "啟動" : "停用"); return new { Success = 1, Message = message }; } return new { Success = 0 }; } } }
27.616438
75
0.479167
[ "MIT" ]
uni2tw/WhatSearch
WhatSearch/Controllers/PageController.cs
2,032
C#
using IO.Reactivex.Functions; using Java.Util.Concurrent; using System; namespace IO.Reactivex.Internal.Operators.Observable { public sealed partial class ObservableInternalHelper { public sealed partial class FlatMapIntoIterable { Java.Lang.Object IFunction.Apply(Java.Lang.Object p0) { throw new NotImplementedException(); } } } }
24.823529
65
0.64455
[ "MIT" ]
MonkSoul/Xamarin.Android.Bindings
Xamarin.Android.RxJava/src/Xamarin.Android.RxJava/Additions/FlatMapIntoIterable.cs
424
C#
/**** * PMSM calculation - automate PMSM design process * Created 2016 by Ngo Phuong Le * https://github.com/lehn85/pmsm_calculation * All files are provided under the MIT license. ****/ using System; using System.Collections.Generic; using System.Threading; using log4net; using fastJSON; namespace calc_from_geometryOfMotor.motor { public abstract class AbstractAnalyser { protected static readonly ILog log = LogManager.GetLogger("Analyser"); [ExcludeFromMD5Calculation, ExcludeFromParams, JsonIgnore] /// <summary> /// Name of analyser /// </summary> public String AnalysisName { get; set; } [ExcludeFromMD5Calculation, ExcludeFromParams, JsonIgnore] /// <summary> /// Motor attached to analyser /// </summary> public AbstractMotor Motor { get; set; } [ExcludeFromMD5Calculation, ExcludeFromParams, JsonIgnore] /// <summary> /// Results of analysis /// </summary> public AbstractResults Results { get; protected set; } /// <summary> /// Hash MD5 of this analysis configuration /// </summary> /// <returns></returns> public virtual String GetMD5String() { return Utils.CalculateObjectMD5Hash(this); } /// <summary> /// Run analysis synchronously /// </summary> public virtual void RunAnalysis() { //Do nothing } /// <summary> /// Run analysis asynchronously /// </summary> public void StartAnalysis() { (new Thread(RunAnalysis)).Start(); } protected void raiseFinishAnalysisEvent() { OnFinishedAnalysis(this, Results); } /// <summary> /// Event fire when finish analysis /// </summary> /// <param name="sender"></param> /// <param name="results"></param> public delegate void MyEventHandler(object sender, AbstractResults results); public event MyEventHandler OnFinishedAnalysis = new MyEventHandler(delegate(object sender, AbstractResults results) { }); } public abstract class AbstractResults { protected static readonly ILog log = LogManager.GetLogger("ResultsLogger"); [JsonIgnore, ExcludeFromParams, ExcludeFromMD5Calculation] internal AbstractAnalyser Analyser { get; set; } /// <summary> /// MD5 string as hash value for this whole transient config /// </summary> [ExcludeFromParams] public String MD5String { get; set; } /// <summary> /// Build a set of results that can be displayed. UI can call this to get data it needs. /// </summary> /// <returns></returns> public virtual IDictionary<String, object> BuildResultsForDisplay() { return new Dictionary<String, object>(); } } }
29.86
130
0.599129
[ "MIT" ]
lehn85/pmsm_calculation
PMSM_calculation/motor/AbstractAnalyser.cs
2,988
C#
using System.Text.RegularExpressions; namespace LTMCompanyNameFree.YoyoCmsTemplate.Web.Views { public static class UrlChecker { private static readonly Regex UrlWithProtocolRegex = new Regex("^.{1,10}://.*$"); public static bool IsRooted(string url) { if (url.StartsWith("/")) { return true; } if (UrlWithProtocolRegex.IsMatch(url)) { return true; } return false; } } }
21.84
89
0.509158
[ "MIT" ]
cnmediar/YoyoCmsFree.Template
src/aspnet-core/src/LTMCompanyNameFree.YoyoCmsTemplate.Web.Mvc/Views/UrlChecker.cs
546
C#
using System; using System.Windows.Forms; namespace Home_Appliance_Store { static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Какую форму запустить?!! Application.Run( new F_A_Yprav() ); } } }
22.666667
65
0.569328
[ "Apache-2.0" ]
Bulatik-707/Home_Appliance_Store
Program.cs
527
C#
using System; using System.Linq.Expressions; using System.Reflection; namespace OdataToEntity.InMemory { internal sealed class NullPropagationVisitor : ExpressionVisitor { public static String SafeSubstring(String text, int start, int length) { if (start >= text.Length) return ""; if (start + length > text.Length) length = text.Length - start; return text.Substring(start, length); } private static int StringComapreGreater(String? strA, String? strB) { if (strA == null || strB == null) return -1; return String.CompareOrdinal(strA, strB); } private static int StringComapreLess(String? strA, String? strB) { if (strA == null || strB == null) return 1; return String.CompareOrdinal(strA, strB); } protected override Expression VisitMember(MemberExpression node) { if (node.Expression != null) { if (node.Expression.Type.IsClass && node.Expression is MemberExpression) { ConstantExpression ifTrue; Type propertyType = node.Type; if (propertyType.IsClass || propertyType.IsInterface) ifTrue = Expression.Constant(null, node.Type); else { propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType; ifTrue = Expression.Constant(Activator.CreateInstance(propertyType), node.Type); } BinaryExpression test = Expression.Equal(node.Expression, Expression.Constant(null)); return Expression.Condition(test, ifTrue, node); } Expression expression = base.Visit(node.Expression); if (node.Expression != expression) { if (node.Expression.Type != expression.Type) { if (Nullable.GetUnderlyingType(expression.Type) != null) { MethodInfo getValueOrDefault = expression.Type.GetMethod("GetValueOrDefault", Type.EmptyTypes)!; expression = Expression.Call(expression, getValueOrDefault); return node.Update(expression); } return Expression.MakeMemberAccess(expression, node.Member); } return node.Update(expression); } } return base.VisitMember(node); } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Object != null && node.Method.DeclaringType == typeof(String) && node.Method.Name == nameof(String.Substring)) { Func<String, int, int, String> safeSubstring = SafeSubstring; var arguments = new Expression[node.Arguments.Count + 1]; arguments[0] = node.Object; for (int i = 1; i < arguments.Length; i++) arguments[i] = node.Arguments[i - 1]; node = Expression.Call(safeSubstring.Method, arguments); } return base.VisitMethodCall(node); } protected override Expression VisitBinary(BinaryExpression node) { if (node.NodeType == ExpressionType.LessThan || node.NodeType == ExpressionType.LessThanOrEqual) { if (node.Left is MethodCallExpression methodCall && methodCall.Object == null && methodCall.Method.DeclaringType == typeof(String) && methodCall.Method.Name == nameof(String.Compare)) { Func<String, String, int> stringComapreLess = StringComapreLess; methodCall = (MethodCallExpression)base.VisitMethodCall(methodCall); methodCall = Expression.Call(stringComapreLess.Method, methodCall.Arguments); return node.Update(methodCall, node.Conversion, node.Right); } } else if (node.NodeType == ExpressionType.GreaterThan || node.NodeType == ExpressionType.GreaterThanOrEqual) { if (node.Right is MethodCallExpression methodCall && methodCall.Object == null && methodCall.Method.DeclaringType == typeof(String) && methodCall.Method.Name == nameof(String.Compare)) { Func<String, String, int> stringComapreGreater = StringComapreGreater; methodCall = (MethodCallExpression)base.VisitMethodCall(methodCall); methodCall = Expression.Call(stringComapreGreater.Method, methodCall.Arguments); return node.Update(node.Left, node.Conversion, methodCall); } } return base.VisitBinary(node); } protected override Expression VisitUnary(UnaryExpression node) { if (node.NodeType == ExpressionType.Convert) { Type? operandType = Nullable.GetUnderlyingType(node.Operand.Type); if (operandType != null && Nullable.GetUnderlyingType(node.Type) == null) { if (operandType == node.Type) return node.Operand; return Expression.Convert(node.Operand, typeof(Nullable<>).MakeGenericType(node.Type)); } } return base.VisitUnary(node); } } }
43.81203
131
0.542303
[ "MIT" ]
DawidPotgieter/OdataToEntity
source/OdataToEntity/InMemory/NullPropagationVisitor.cs
5,829
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.CodeDom.Compiler; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Xml; using EnvDTE; using Microsoft.Build.Execution; using Microsoft.NodejsTools; using Microsoft.NodejsTools.Diagnostics; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using MSBuild = Microsoft.Build.Evaluation; using MSBuildConstruction = Microsoft.Build.Construction; using MSBuildExecution = Microsoft.Build.Execution; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// Manages the persistent state of the project (References, options, files, etc.) and deals with user interaction via a GUI in the form a hierarchy. /// </summary> internal abstract partial class ProjectNode : HierarchyNode, IVsUIHierarchy, IVsPersistHierarchyItem2, IVsHierarchyDeleteHandler, IVsHierarchyDeleteHandler2, IVsHierarchyDropDataTarget, IVsHierarchyDropDataSource, IVsHierarchyDropDataSource2, IVsGetCfgProvider, IVsProject3, IVsAggregatableProject, IVsProjectFlavorCfgProvider, IPersistFileFormat, IVsBuildPropertyStorage, IVsComponentUser, IVsDependencyProvider, IVsSccProject2, IBuildDependencyUpdate, IVsProjectSpecialFiles, IVsProjectBuildSystem, IOleCommandTarget, IVsReferenceManagerUser { #region nested types [Obsolete("Use ImageMonikers instead")] public enum ImageName { OfflineWebApp = 0, WebReferencesFolder = 1, OpenReferenceFolder = 2, ReferenceFolder = 3, Reference = 4, SDLWebReference = 5, DISCOWebReference = 6, Folder = 7, OpenFolder = 8, ExcludedFolder = 9, OpenExcludedFolder = 10, ExcludedFile = 11, DependentFile = 12, MissingFile = 13, WindowsForm = 14, WindowsUserControl = 15, WindowsComponent = 16, XMLSchema = 17, XMLFile = 18, WebForm = 19, WebService = 20, WebUserControl = 21, WebCustomUserControl = 22, ASPPage = 23, GlobalApplicationClass = 24, WebConfig = 25, HTMLPage = 26, StyleSheet = 27, ScriptFile = 28, TextFile = 29, SettingsFile = 30, Resources = 31, Bitmap = 32, Icon = 33, Image = 34, ImageMap = 35, XWorld = 36, Audio = 37, Video = 38, CAB = 39, JAR = 40, DataEnvironment = 41, PreviewFile = 42, DanglingReference = 43, XSLTFile = 44, Cursor = 45, AppDesignerFolder = 46, Data = 47, Application = 48, DataSet = 49, PFX = 50, SNK = 51, ImageLast = 51 } /// <summary> /// Flags for specifying which events to stop triggering. /// </summary> [Flags] internal enum EventTriggering { TriggerAll = 0, DoNotTriggerHierarchyEvents = 1, DoNotTriggerTrackerEvents = 2, DoNotTriggerTrackerQueryEvents = 4 } #endregion #region constants /// <summary> /// The user file extension. /// </summary> internal const string PerUserFileExtension = ".user"; #endregion #region fields /// <summary> /// List of output groups names and their associated target /// </summary> private static readonly KeyValuePair<string, string>[] OutputGroupNames = { // Name ItemGroup (MSBuild) new KeyValuePair<string, string>("Built", "BuiltProjectOutputGroup"), new KeyValuePair<string, string>("ContentFiles", "ContentFilesProjectOutputGroup"), new KeyValuePair<string, string>("LocalizedResourceDlls", "SatelliteDllsProjectOutputGroup"), new KeyValuePair<string, string>("Documentation", "DocumentationProjectOutputGroup"), new KeyValuePair<string, string>("Symbols", "DebugSymbolsProjectOutputGroup"), new KeyValuePair<string, string>("SourceFiles", "SourceFilesProjectOutputGroup"), new KeyValuePair<string, string>("XmlSerializer", "SGenFilesOutputGroup"), }; private readonly EventSinkCollection hierarchyEventSinks = new EventSinkCollection(); /// <summary>A project will only try to build if it can obtain a lock on this object</summary> private volatile static object BuildLock = new object(); /// <summary>A service provider call back object provided by the IDE hosting the project manager</summary> private IServiceProvider site; private TrackDocumentsHelper tracker; /// <summary> /// MSBuild engine we are going to use /// </summary> private MSBuild.ProjectCollection buildEngine; private MSBuild.Project buildProject; private MSBuild.Project userBuildProject; private MSBuildExecution.ProjectInstance currentConfig; private ConfigProvider configProvider; private TaskProvider taskProvider; private string filename; private Microsoft.VisualStudio.Shell.Url baseUri; private string projectHome; /// <summary> /// Used by OAProject to override the dirty state. /// </summary> internal bool isDirty; private bool projectOpened; private Lazy<string> errorString = new Lazy<string>(() => SR.GetString(SR.Error), isThreadSafe: true); private Lazy<string> warningString = new Lazy<string>(() => SR.GetString(SR.Warning), isThreadSafe: true); private ImageHandler imageHandler; private Guid projectIdGuid; private bool isClosed; private bool isClosing; /// <summary> /// The build dependency list passed to IVsDependencyProvider::EnumDependencies /// </summary> private List<IVsBuildDependency> buildDependencyList = new List<IVsBuildDependency>(); private bool buildInProcess; private string sccProjectName; private string sccLocalPath; private string sccAuxPath; private string sccProvider; /// <summary> /// Flag for controling how many times we register with the Scc manager. /// </summary> private bool isRegisteredWithScc; /// <summary> /// Flag for controling query edit should communicate with the scc manager. /// </summary> private bool disableQueryEdit; /// <summary> /// Member to store output base relative path. Used by OutputBaseRelativePath property /// </summary> private string outputBaseRelativePath = "bin"; /// <summary> /// Used for flavoring to hold the XML fragments /// </summary> private XmlDocument xmlFragments; /// <summary> /// Used to map types to CATID. This provide a generic way for us to do this /// and make it simpler for a project to provide it's CATIDs for the different type of objects /// for which it wants to support extensibility. This also enables us to have multiple /// type mapping to the same CATID if we choose to. /// </summary> private Dictionary<Type, Guid> catidMapping; /// <summary> /// Mapping from item names to their hierarchy nodes for all disk-based nodes. /// </summary> protected readonly ConcurrentDictionary<string, HierarchyNode> DiskNodes = new ConcurrentDictionary<string, HierarchyNode>(StringComparer.OrdinalIgnoreCase); // Has the object been disposed. private bool isDisposed; private IVsHierarchy parentHierarchy; private int parentHierarchyItemId; private List<HierarchyNode> itemsDraggedOrCutOrCopied; private readonly ExtensibilityEventsDispatcher extensibilityEventsDispatcher; private IVsBuildManagerAccessor buildManagerAccessor; #endregion #region abstract properties /// <summary> /// This Guid must match the Guid you registered under /// HKLM\Software\Microsoft\VisualStudio\%version%\Projects. /// Among other things, the Project framework uses this /// guid to find your project and item templates. /// </summary> public abstract Guid ProjectGuid { get; } /// <summary> /// Returns a caption for VSHPROPID_TypeName. /// </summary> /// <returns></returns> public abstract string ProjectType { get; } #endregion #region virtual properties /// <summary> /// Indicates whether or not the project system supports Show All Files. /// /// Subclasses will need to return true here, and will need to handle calls /// </summary> public virtual bool CanShowAllFiles => false; /// <summary> /// Indicates whether or not the project is currently in the mode where its showing all files. /// </summary> public virtual bool IsShowingAllFiles => false; /// <summary> /// Represents the command guid for the project system. This enables /// using CommonConstants.cmdid* commands. /// /// By default these commands are disabled if this isn't overridden /// with the packages command guid. /// </summary> public virtual Guid SharedCommandGuid => CommonConstants.NoSharedCommandsGuid; /// <summary> /// This is the project instance guid that is peristed in the project file /// </summary> [Browsable(false)] public virtual Guid ProjectIDGuid { get { return this.projectIdGuid; } set { if (this.projectIdGuid != value) { this.projectIdGuid = value; if (this.buildProject != null) { this.SetProjectProperty("ProjectGuid", this.projectIdGuid.ToString("B")); } } } } public override bool CanAddFiles => true; #endregion #region properties internal bool IsProjectOpened => this.projectOpened; internal ExtensibilityEventsDispatcher ExtensibilityEventsDispatcher => this.extensibilityEventsDispatcher; /// <summary> /// Folder node in the process of being created. First the hierarchy node /// is added, then the label is edited, and when that completes/cancels /// the folder gets created. /// </summary> internal FolderNode FolderBeingCreated { get; set; } internal IList<HierarchyNode> ItemsDraggedOrCutOrCopied => this.itemsDraggedOrCutOrCopied; public MSBuildExecution.ProjectInstance CurrentConfig => this.currentConfig; #region overridden properties public override bool CanOpenCommandPrompt => true; internal override string FullPathToChildren => this.ProjectHome; public override int MenuCommandId => VsMenus.IDM_VS_CTXT_PROJNODE; public override string Url => this.GetMkDocument(); public override string Caption { get { var project = this.buildProject; if (project == null) { // Project is not available, which probably means we are // in the process of closing return string.Empty; } // Use file name var caption = project.FullPath; if (string.IsNullOrEmpty(caption)) { if (project.GetProperty(ProjectFileConstants.Name) != null) { caption = project.GetProperty(ProjectFileConstants.Name).EvaluatedValue; if (caption == null || caption.Length == 0) { caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include); } } } else { caption = Path.GetFileNameWithoutExtension(caption); } return caption; } } public override Guid ItemTypeGuid => this.ProjectGuid; #pragma warning disable 0618, 0672 // Project subclasses decide whether or not to support using image // monikers, and so we need to keep the ImageIndex overrides in case // they choose not to. public override int ImageIndex => (int)ProjectNode.ImageName.Application; #pragma warning restore 0618, 0672 #endregion #region virtual properties public virtual string ErrorString => this.errorString.Value; public virtual string WarningString => this.warningString.Value; /// <summary> /// Override this property to specify when the project file is dirty. /// </summary> protected virtual bool IsProjectFileDirty { get { var document = this.GetMkDocument(); if (string.IsNullOrEmpty(document)) { return this.isDirty; } return (this.isDirty || !File.Exists(document)); } } /// <summary> /// True if the project uses the Project Designer Editor instead of the property page frame to edit project properties. /// </summary> protected bool SupportsProjectDesigner { get; set; } protected virtual Guid ProjectDesignerEditor => VSConstants.GUID_ProjectDesignerEditor; /// <summary> /// Defines the flag that supports the VSHPROPID.ShowProjInSolutionPage /// </summary> protected virtual bool ShowProjectInSolutionPage { get; set; } = true; /// <summary> /// A space separated list of the project's capabilities. /// </summary> /// <remarks> /// These may be used by extensions to check whether they support this /// project type. In general, this should only contain fundamental /// properties of the project, such as the language name. /// </remarks> protected virtual string ProjectCapabilities => null; #endregion /// <summary> /// Gets or sets the ability of a project filenode to have child nodes (sub items). /// Example would be C#/VB forms having resx and designer files. /// </summary> protected internal bool CanFileNodesHaveChilds { get; set; } /// <summary> /// Gets a service provider object provided by the IDE hosting the project /// </summary> public IServiceProvider Site => this.site; /// <summary> /// Gets an ImageHandler for the project node. /// </summary> [Obsolete("Use ImageMonikers instead")] public ImageHandler ImageHandler { get { if (null == this.imageHandler) { this.imageHandler = new ImageHandler(this.ProjectIconsImageStripStream); } return this.imageHandler; } } protected abstract Stream ProjectIconsImageStripStream { get; } /// <summary> /// Gets the path to the root folder of the project. /// </summary> public string ProjectHome { get { if (this.projectHome == null) { this.projectHome = CommonUtils.GetAbsoluteDirectoryPath( this.ProjectFolder, this.GetProjectProperty(CommonConstants.ProjectHome, resetCache: false)); } Debug.Assert(this.projectHome != null, "ProjectHome should not be null"); return this.projectHome; } } /// <summary> /// Gets the path to the folder containing the project. /// </summary> public string ProjectFolder => Path.GetDirectoryName(this.filename); /// <summary> /// Gets or sets the project filename. /// </summary> public string ProjectFile { get { return Path.GetFileName(this.filename); } set { this.SetEditLabel(value); } } /// <summary> /// Gets the Base Uniform Resource Identifier (URI). /// </summary> public Microsoft.VisualStudio.Shell.Url BaseURI { get { if (this.baseUri == null && this.buildProject != null) { var path = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.buildProject.FullPath)); this.baseUri = new Url(path); } Debug.Assert(this.baseUri != null, "Base URL should not be null. Did you call BaseURI before loading the project?"); return this.baseUri; } } protected void BuildProjectLocationChanged() { this.baseUri = null; this.projectHome = null; } /// <summary> /// Gets whether or not the project is closed. /// </summary> public bool IsClosed => this.isClosed; /// <summary> /// Gets whether or not the project has begun closing. /// </summary> public bool IsClosing => this.isClosing; /// <summary> /// Gets whether or not the project is being built. /// </summary> public bool BuildInProgress => this.buildInProcess; /// <summary> /// Gets or set the relative path to the folder containing the project ouput. /// </summary> public virtual string OutputBaseRelativePath { get { return this.outputBaseRelativePath; } set { if (Path.IsPathRooted(value)) { // TODO: Maybe bring the exception back instead of automatically fixing this? this.outputBaseRelativePath = CommonUtils.GetRelativeDirectoryPath(this.ProjectHome, value); } this.outputBaseRelativePath = value; } } /// <summary> /// Gets a collection of integer ids that maps to project item instances. /// This should be a new instance for each hierarchy. /// </summary> internal HierarchyIdMap ItemIdMap { get; } = new HierarchyIdMap(); /// <summary> /// Get the helper object that track document changes. /// </summary> internal TrackDocumentsHelper Tracker => this.tracker; /// <summary> /// Gets or sets the build logger. /// </summary> protected IDEBuildLogger BuildLogger { get; set; } /// <summary> /// Gets the taskprovider. /// </summary> protected TaskProvider TaskProvider => this.taskProvider; /// <summary> /// Gets the project file name. /// </summary> protected string FileName => this.filename; protected string UserProjectFilename => this.FileName + PerUserFileExtension; /// <summary> /// Gets the configuration provider. /// </summary> protected internal ConfigProvider ConfigProvider { get { if (this.configProvider == null) { this.configProvider = CreateConfigProvider(); } return this.configProvider; } } /// <summary> /// Gets or set whether items can be deleted for this project. /// Enabling this feature can have the potential destructive behavior such as deleting files from disk. /// </summary> protected internal bool CanProjectDeleteItems { get; set; } /// <summary> /// Gets or sets event triggering flags. /// </summary> internal EventTriggering EventTriggeringFlag { get; set; } = EventTriggering.TriggerAll; /// <summary> /// Defines the build project that has loaded the project file. /// </summary> protected internal MSBuild.Project BuildProject { get { return this.buildProject; } set { SetBuildProject(value); } } /// <summary> /// Defines the build engine that is used to build the project file. /// </summary> internal MSBuild.ProjectCollection BuildEngine { get { return this.buildEngine; } set { this.buildEngine = value; } } protected internal MSBuild.Project UserBuildProject => this.userBuildProject; protected bool IsUserProjectFileDirty => this.userBuildProject?.Xml.HasUnsavedChanges == true; #endregion #region ctor protected ProjectNode(IServiceProvider serviceProvider) { this.extensibilityEventsDispatcher = new ExtensibilityEventsDispatcher(this); this.site = serviceProvider; this.Initialize(); this.taskProvider = new TaskProvider(this.site); } #endregion #region overridden methods protected internal override void DeleteFromStorage(string path) { if (File.Exists(path)) { File.Delete(path); } base.DeleteFromStorage(path); } /// <summary> /// Sets the properties for the project node. /// </summary> /// <param name="propid">Identifier of the hierarchy property. For a list of propid values, <see cref="__VSHPROPID"/> </param> /// <param name="value">The value to set. </param> /// <returns>A success or failure value.</returns> public override int SetProperty(int propid, object value) { var id = (__VSHPROPID)propid; switch (id) { case __VSHPROPID.VSHPROPID_ParentHierarchy: this.parentHierarchy = (IVsHierarchy)value; break; case __VSHPROPID.VSHPROPID_ParentHierarchyItemid: this.parentHierarchyItemId = (int)value; break; case __VSHPROPID.VSHPROPID_ShowProjInSolutionPage: this.ShowProjectInSolutionPage = (bool)value; return VSConstants.S_OK; } return base.SetProperty(propid, value); } /// <summary> /// Renames the project node. /// </summary> /// <param name="label">The new name</param> /// <returns>A success or failure value.</returns> public override int SetEditLabel(string label) { // Validate the filename. if (Utilities.IsFileNameInvalid(label)) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label)); } else if (this.ProjectFolder.Length + label.Length + 1 > NativeMethods.MAX_PATH) { throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label)); } // TODO: Take file extension into account? var fileName = Path.GetFileNameWithoutExtension(label); // Nothing to do if the name is the same var oldFileName = Path.GetFileNameWithoutExtension(this.Url); if (StringComparer.Ordinal.Equals(oldFileName, label)) { return VSConstants.S_FALSE; } // Now check whether the original file is still there. It could have been renamed. if (!File.Exists(this.Url)) { throw new InvalidOperationException(SR.GetString(SR.FileOrFolderCannotBeFound, this.ProjectFile)); } // Get the full file name and then rename the project file. var newFile = Path.Combine(this.ProjectFolder, label); var extension = Path.GetExtension(this.Url); // Make sure it has the correct extension if (!StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(newFile), extension)) { newFile += extension; } this.RenameProjectFile(newFile); return VSConstants.S_OK; } /// <summary> /// Gets the automation object for the project node. /// </summary> /// <returns>An instance of an EnvDTE.Project implementation object representing the automation object for the project.</returns> public override object GetAutomationObject() { return new Automation.OAProject(this); } /// <summary> /// Gets the properties of the project node. /// </summary> /// <param name="propId">The __VSHPROPID of the property.</param> /// <returns>A property dependent value. See: <see cref="__VSHPROPID"/> for details.</returns> public override object GetProperty(int propId) { switch ((__VSHPROPID)propId) { case (__VSHPROPID)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker: // really only here for testing so WAP projects load correctly... // But this also impacts the toolbox by filtering what available items there are. return ".NETFramework,Version=v4.0,Profile=Client"; case __VSHPROPID.VSHPROPID_ConfigurationProvider: return this.ConfigProvider; case __VSHPROPID.VSHPROPID_ProjectName: return this.Caption; case __VSHPROPID.VSHPROPID_ProjectDir: return this.ProjectFolder; case __VSHPROPID.VSHPROPID_TypeName: return this.ProjectType; case __VSHPROPID.VSHPROPID_ShowProjInSolutionPage: return this.ShowProjectInSolutionPage; case __VSHPROPID.VSHPROPID_ExpandByDefault: return true; case __VSHPROPID.VSHPROPID_DefaultEnableDeployProjectCfg: return true; case __VSHPROPID.VSHPROPID_DefaultEnableBuildProjectCfg: return true; // Use the same icon as if the folder was closed case __VSHPROPID.VSHPROPID_OpenFolderIconIndex: return GetProperty((int)__VSHPROPID.VSHPROPID_IconIndex); case __VSHPROPID.VSHPROPID_ParentHierarchyItemid: if (this.parentHierarchy != null) { return (IntPtr)this.parentHierarchyItemId; // VS requires VT_I4 | VT_INT_PTR } break; case __VSHPROPID.VSHPROPID_ParentHierarchy: return this.parentHierarchy; } switch ((__VSHPROPID2)propId) { case __VSHPROPID2.VSHPROPID_SupportsProjectDesigner: return this.SupportsProjectDesigner; case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList: return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetConfigurationIndependentPropertyPages()); case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList: return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetConfigurationDependentPropertyPages()); case __VSHPROPID2.VSHPROPID_PriorityPropertyPagesCLSIDList: return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetPriorityProjectDesignerPages()); case __VSHPROPID2.VSHPROPID_Container: return true; default: break; } switch ((__VSHPROPID5)propId) { case __VSHPROPID5.VSHPROPID_ProjectCapabilities: var caps = this.ProjectCapabilities; if (!string.IsNullOrEmpty(caps)) { return caps; } break; } return base.GetProperty(propId); } /// <summary> /// Gets the GUID value of the node. /// </summary> /// <param name="propid">A __VSHPROPID or __VSHPROPID2 value of the guid property</param> /// <param name="guid">The guid to return for the property.</param> /// <returns>A success or failure value.</returns> public override int GetGuidProperty(int propid, out Guid guid) { guid = Guid.Empty; if ((__VSHPROPID)propid == __VSHPROPID.VSHPROPID_ProjectIDGuid) { guid = this.ProjectIDGuid; } else if (propid == (int)__VSHPROPID.VSHPROPID_CmdUIGuid) { guid = this.ProjectGuid; } else if ((__VSHPROPID2)propid == __VSHPROPID2.VSHPROPID_ProjectDesignerEditor && this.SupportsProjectDesigner) { guid = this.ProjectDesignerEditor; } else { base.GetGuidProperty(propid, out guid); } if (guid.CompareTo(Guid.Empty) == 0) { return VSConstants.DISP_E_MEMBERNOTFOUND; } return VSConstants.S_OK; } /// <summary> /// Sets Guid properties for the project node. /// </summary> /// <param name="propid">A __VSHPROPID or __VSHPROPID2 value of the guid property</param> /// <param name="guid">The guid value to set.</param> /// <returns>A success or failure value.</returns> public override int SetGuidProperty(int propid, ref Guid guid) { switch ((__VSHPROPID)propid) { case __VSHPROPID.VSHPROPID_ProjectIDGuid: this.ProjectIDGuid = guid; return VSConstants.S_OK; } return VSConstants.DISP_E_MEMBERNOTFOUND; } /// <summary> /// Removes items from the hierarchy. /// </summary> /// <devdoc>Project overwrites this.</devdoc> public override void Remove(bool removeFromStorage) { // the project will not be deleted from disk, just removed if (removeFromStorage) { return; } // Remove the entire project from the solution var solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution; uint iOption = 1; // SLNSAVEOPT_PromptSave ErrorHandler.ThrowOnFailure(solution.CloseSolutionElement(iOption, this.GetOuterInterface<IVsHierarchy>(), 0)); } /// <summary> /// Gets the moniker for the project node. That is the full path of the project file. /// </summary> /// <returns>The moniker for the project file.</returns> public override string GetMkDocument() { Debug.Assert(!string.IsNullOrEmpty(this.filename)); Debug.Assert(this.BaseURI != null && !string.IsNullOrEmpty(this.BaseURI.AbsoluteUrl)); return CommonUtils.GetAbsoluteFilePath(this.BaseURI.AbsoluteUrl, this.filename); } /// <summary> /// Disposes the project node object. /// </summary> /// <param name="disposing">Flag determining ehether it was deterministic or non deterministic clean up.</param> protected override void Dispose(bool disposing) { if (this.isDisposed) { return; } try { try { UnRegisterProject(); } finally { try { RegisterClipboardNotifications(false); } finally { this.buildEngine = null; } } if (this.buildProject != null) { this.buildProject.ProjectCollection.UnloadProject(this.buildProject); this.buildProject.ProjectCollection.UnloadProject(this.buildProject.Xml); SetBuildProject(null); } if (this.BuildLogger is IDisposable logger) { logger.Dispose(); } this.BuildLogger = null; var tasks = this.taskProvider; this.taskProvider = null; if (tasks != null) { tasks.Dispose(); } this.isClosing = true; this.isClosed = false; if (null != this.imageHandler) { this.imageHandler.Close(); this.imageHandler = null; } this.DiskNodes.Clear(); this.FolderBeingCreated = null; } finally { base.Dispose(disposing); // Note that this isDisposed flag is separate from the base's this.isDisposed = true; this.isClosed = true; this.isClosing = false; this.projectOpened = false; } } /// <summary> /// Handles command status on the project node. If a command cannot be handled then the base should be called. /// </summary> /// <param name="cmdGroup">A unique identifier of the command group. The pguidCmdGroup parameter can be NULL to specify the standard group.</param> /// <param name="cmd">The command to query status for.</param> /// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return the name and/or status information of a single command. Can be NULL to indicate that the caller does not require this information.</param> /// <param name="result">An out parameter specifying the QueryStatusResult of the command.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: case VsCommands.Exit: case VsCommands.ProjectSettings: case VsCommands.UnloadProject: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.CancelBuild: result |= QueryStatusResult.SUPPORTED; if (this.buildInProcess) { result |= QueryStatusResult.ENABLED; } else { result |= QueryStatusResult.INVISIBLE; } return VSConstants.S_OK; case VsCommands.NewFolder: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.SetStartupProject: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { switch ((VsCommands2K)cmd) { case VsCommands2K.ADDREFERENCE: if (GetReferenceContainer() != null) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; } else { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE; } return VSConstants.S_OK; case VsCommands2K.EXCLUDEFROMPROJECT: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE; return VSConstants.S_OK; } } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } /// <summary> /// Handles command execution. /// </summary> /// <param name="cmdGroup">Unique identifier of the command group</param> /// <param name="cmd">The command to be executed.</param> /// <param name="nCmdexecopt">Values describe how the object should execute the command.</param> /// <param name="pvaIn">Pointer to a VARIANTARG structure containing input arguments. Can be NULL</param> /// <param name="pvaOut">VARIANTARG structure to receive command output. Can be NULL.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.UnloadProject: return this.UnloadProject(); case VsCommands.CleanSel: case VsCommands.CleanCtx: return this.CleanProject(); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } /// <summary> /// Get the boolean value for the deletion of a project item /// </summary> /// <param name="deleteOperation">A flag that specifies the type of delete operation (delete from storage or remove from project)</param> /// <returns>true if item can be deleted from project</returns> internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { return true; } return false; } /// <summary> /// Returns a specific Document manager to handle opening and closing of the Project(Application) Designer if projectdesigner is supported. /// </summary> /// <returns>Document manager object</returns> protected internal override DocumentManager GetDocumentManager() { if (this.SupportsProjectDesigner) { return new ProjectDesignerDocumentManager(this); } return null; } #endregion #region virtual methods public virtual IEnumerable<string> GetAvailableItemNames() { IEnumerable<string> itemTypes = new[] { ProjectFileConstants.None, ProjectFileConstants.Compile, ProjectFileConstants.Content }; var items = this.buildProject.GetItems("AvailableItemName"); itemTypes = itemTypes.Union(items.Select(x => x.EvaluatedInclude)); return itemTypes; } /// <summary> /// Creates a reference node for the given file returning the node, or returns null /// if the file doesn't represent a valid file which can be referenced. /// </summary> public virtual ReferenceNode CreateReferenceNodeForFile(string filename) { return null; } /// <summary> /// Executes a wizard. /// </summary> /// <param name="parentNode">The node to which the wizard should add item(s).</param> /// <param name="itemName">The name of the file that the user typed in.</param> /// <param name="wizardToRun">The name of the wizard to run.</param> /// <param name="dlgOwner">The owner of the dialog box.</param> /// <returns>A VSADDRESULT enum value describing success or failure.</returns> public virtual VSADDRESULT RunWizard(HierarchyNode parentNode, string itemName, string wizardToRun, IntPtr dlgOwner) { Debug.Assert(!string.IsNullOrEmpty(itemName), "The Add item dialog was passing in a null or empty item to be added to the hierrachy."); Debug.Assert(!string.IsNullOrEmpty(this.ProjectHome), "ProjectHome is not specified for this project."); Utilities.ArgumentNotNull(nameof(parentNode), parentNode); Utilities.ArgumentNotNullOrEmpty(nameof(itemName), itemName); // We just validate for length, since we assume other validation has been performed by the dlgOwner. if (CommonUtils.GetAbsoluteFilePath(this.ProjectHome, itemName).Length >= NativeMethods.MAX_PATH) { var errorMessage = SR.GetString(SR.PathTooLong, itemName); if (!Utilities.IsInAutomationFunction(this.Site)) { string title = null; var icon = OLEMSGICON.OLEMSGICON_CRITICAL; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; Utilities.ShowMessageBox(this.Site, title, errorMessage, icon, buttons, defaultButton); return VSADDRESULT.ADDRESULT_Failure; } else { throw new InvalidOperationException(errorMessage); } } // Build up the ContextParams safearray // [0] = Wizard type guid (bstr) // [1] = Project name (bstr) // [2] = ProjectItems collection (bstr) // [3] = Local Directory (bstr) // [4] = Filename the user typed (bstr) // [5] = Product install Directory (bstr) // [6] = Run silent (bool) var contextParams = new object[7]; contextParams[0] = EnvDTE.Constants.vsWizardAddItem; contextParams[1] = this.Caption; var automationObject = parentNode.GetAutomationObject(); if (automationObject is EnvDTE.Project) { var project = (EnvDTE.Project)automationObject; contextParams[2] = project.ProjectItems; } else { // This would normally be a folder unless it is an item with subitems var item = (EnvDTE.ProjectItem)automationObject; contextParams[2] = item.ProjectItems; } contextParams[3] = this.ProjectHome; contextParams[4] = itemName; var shell = (IVsShell)this.GetService(typeof(IVsShell)); ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out var objInstallationDir)); var installDir = CommonUtils.NormalizeDirectoryPath((string)objInstallationDir); contextParams[5] = installDir; contextParams[6] = true; var ivsExtensibility = this.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; Debug.Assert(ivsExtensibility != null, "Failed to get IVsExtensibility3 service"); if (ivsExtensibility == null) { return VSADDRESULT.ADDRESULT_Failure; } // Determine if we have the trust to run this wizard. var wizardTrust = this.GetService(typeof(SVsDetermineWizardTrust)) as IVsDetermineWizardTrust; if (wizardTrust != null) { var guidProjectAdding = Guid.Empty; ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardInitiated(wizardToRun, ref guidProjectAdding)); } int wizResultAsInt; try { Array contextParamsAsArray = contextParams; var result = ivsExtensibility.RunWizardFile(wizardToRun, (int)dlgOwner, ref contextParamsAsArray, out wizResultAsInt); if (!ErrorHandler.Succeeded(result) && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } } finally { if (wizardTrust != null) { ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardCompleted()); } } var wizardResult = (EnvDTE.wizardResult)wizResultAsInt; switch (wizardResult) { default: return VSADDRESULT.ADDRESULT_Cancel; case wizardResult.wizardResultSuccess: return VSADDRESULT.ADDRESULT_Success; case wizardResult.wizardResultFailure: return VSADDRESULT.ADDRESULT_Failure; } } /// <summary> /// Shows the Add Reference dialog. /// </summary> /// <returns>S_OK if succeeded. Failure otherwise</returns> public int AddProjectReference() { if (this.GetService(typeof(SVsReferenceManager)) is IVsReferenceManager referenceManager) { var contextGuids = new[] { VSConstants.ProjectReferenceProvider_Guid, VSConstants.FileReferenceProvider_Guid }; referenceManager.ShowReferenceManager( this, SR.GetString(SR.AddReferenceDialogTitle), "VS.ReferenceManager", contextGuids.First(), false); return VSConstants.S_OK; } else { return VSConstants.E_NOINTERFACE; } } #region IVsReferenceManagerUser Members void IVsReferenceManagerUser.ChangeReferences(uint operation, IVsReferenceProviderContext changedContext) { var op = (__VSREFERENCECHANGEOPERATION)operation; __VSREFERENCECHANGEOPERATIONRESULT result; try { if (op == __VSREFERENCECHANGEOPERATION.VSREFERENCECHANGEOPERATION_ADD) { result = this.AddReferences(changedContext); } else { result = this.RemoveReferences(changedContext); } } catch (InvalidOperationException e) { Debug.Fail(e.ToString()); result = __VSREFERENCECHANGEOPERATIONRESULT.VSREFERENCECHANGEOPERATIONRESULT_DENY; } if (result == __VSREFERENCECHANGEOPERATIONRESULT.VSREFERENCECHANGEOPERATIONRESULT_DENY) { throw new InvalidOperationException(); } } Array IVsReferenceManagerUser.GetProviderContexts() { return this.GetProviderContexts(); } #endregion protected virtual Array GetProviderContexts() { var referenceManager = this.GetService(typeof(SVsReferenceManager)) as IVsReferenceManager; var contextProviders = new[] { CreateProjectReferenceProviderContext(referenceManager), CreateFileReferenceProviderContext(referenceManager), }; return contextProviders; } private IVsReferenceProviderContext CreateProjectReferenceProviderContext(IVsReferenceManager mgr) { var context = mgr.CreateProviderContext(VSConstants.ProjectReferenceProvider_Guid) as IVsProjectReferenceProviderContext; context.CurrentProject = this; var referenceContainer = this.GetReferenceContainer(); var references = referenceContainer .EnumReferences() .OfType<ProjectReferenceNode>(); foreach (var reference in references) { var newReference = context.CreateReference() as IVsProjectReference; newReference.Identity = reference.ReferencedProjectGuid.ToString("B"); } return context as IVsReferenceProviderContext; } private IVsReferenceProviderContext CreateFileReferenceProviderContext(IVsReferenceManager mgr) { var context = mgr.CreateProviderContext(VSConstants.FileReferenceProvider_Guid) as IVsFileReferenceProviderContext; context.BrowseFilter = this.AddReferenceExtensions.Replace('|', '\0') + "\0"; return context as IVsReferenceProviderContext; } private __VSREFERENCECHANGEOPERATIONRESULT AddReferences(IVsReferenceProviderContext context) { var addedReferences = this.GetAddedReferences(context); var referenceContainer = this.GetReferenceContainer(); foreach (var selectorData in addedReferences) { referenceContainer.AddReferenceFromSelectorData(selectorData); } return __VSREFERENCECHANGEOPERATIONRESULT.VSREFERENCECHANGEOPERATIONRESULT_ALLOW; } protected virtual IEnumerable<VSCOMPONENTSELECTORDATA> GetAddedReferences(IVsReferenceProviderContext context) { var addedReferences = Enumerable.Empty<VSCOMPONENTSELECTORDATA>(); if (context.ProviderGuid == VSConstants.ProjectReferenceProvider_Guid) { addedReferences = GetAddedReferences(context as IVsProjectReferenceProviderContext); } else if (context.ProviderGuid == VSConstants.FileReferenceProvider_Guid) { addedReferences = GetAddedReferences(context as IVsFileReferenceProviderContext); } return addedReferences; } private __VSREFERENCECHANGEOPERATIONRESULT RemoveReferences(IVsReferenceProviderContext context) { var removedReferences = this.GetRemovedReferences(context); foreach (var refNode in removedReferences) { refNode.Remove(true /* delete from storage*/); } return __VSREFERENCECHANGEOPERATIONRESULT.VSREFERENCECHANGEOPERATIONRESULT_ALLOW; } protected virtual IEnumerable<ReferenceNode> GetRemovedReferences(IVsReferenceProviderContext context) { var removedReferences = Enumerable.Empty<ReferenceNode>(); if (context.ProviderGuid == VSConstants.ProjectReferenceProvider_Guid) { removedReferences = GetRemovedReferences(context as IVsProjectReferenceProviderContext); } else if (context.ProviderGuid == VSConstants.FileReferenceProvider_Guid) { removedReferences = GetRemovedReferences(context as IVsFileReferenceProviderContext); } return removedReferences; } private IEnumerable<VSCOMPONENTSELECTORDATA> GetAddedReferences(IVsProjectReferenceProviderContext context) { var selectedReferences = context .References .OfType<IVsProjectReference>() .Select(reference => new VSCOMPONENTSELECTORDATA() { type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project, bstrTitle = reference.Name, bstrFile = new FileInfo(reference.FullPath).Directory.FullName, bstrProjRef = reference.ReferenceSpecification, }); return selectedReferences; } private IEnumerable<ReferenceNode> GetRemovedReferences(IVsProjectReferenceProviderContext context) { var selectedReferences = context .References .OfType<IVsProjectReference>() .Select(asmRef => new Guid(asmRef.Identity)); var referenceContainer = this.GetReferenceContainer(); var references = referenceContainer .EnumReferences() .OfType<ProjectReferenceNode>() .Where(refNode => selectedReferences.Contains(refNode.ReferencedProjectGuid)); return references; } private IEnumerable<VSCOMPONENTSELECTORDATA> GetAddedReferences(IVsFileReferenceProviderContext context) { var selectedReferences = context .References .OfType<IVsFileReference>() .Select(reference => new VSCOMPONENTSELECTORDATA() { type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File, bstrFile = reference.FullPath, }); return selectedReferences; } private IEnumerable<ReferenceNode> GetRemovedReferences(IVsFileReferenceProviderContext context) { var selectedReferences = context .References .OfType<IVsFileReference>() .Select(fileRef => fileRef.FullPath); var referenceContainer = this.GetReferenceContainer(); var references = referenceContainer .EnumReferences() .OfType<ReferenceNode>() .Where(refNode => selectedReferences.Contains(refNode.Url)); return references; } protected virtual string AddReferenceExtensions => SR.GetString(SR.AddReferenceExtensions); /// <summary> /// Returns the Compiler associated to the project /// </summary> /// <returns>Null</returns> public virtual ICodeCompiler GetCompiler() { return null; } /// <summary> /// Override this method if you have your own project specific /// subclass of ProjectOptions /// </summary> /// <returns>This method returns a new instance of the ProjectOptions base class.</returns> public virtual CompilerParameters CreateProjectOptions() { return new CompilerParameters(); } /// <summary> /// Loads a project file. Called from the factory CreateProject to load the project. /// </summary> /// <param name="fileName">File name of the project that will be created. </param> /// <param name="location">Location where the project will be created.</param> /// <param name="name">If applicable, the name of the template to use when cloning a new project.</param> /// <param name="flags">Set of flag values taken from the VSCREATEPROJFLAGS enumeration.</param> /// <param name="iidProject">Identifier of the interface that the caller wants returned. </param> /// <param name="canceled">An out parameter specifying if the project creation was canceled</param> public virtual void Load(string fileName, string location, string name, uint flags, ref Guid iidProject, out int canceled) { using (new DebugTimer("ProjectLoad")) { this.DiskNodes.Clear(); var successful = false; try { this.disableQueryEdit = true; // set up internal members and icons canceled = 0; this.ProjectMgr = this; if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) { // we need to generate a new guid for the project this.projectIdGuid = Guid.NewGuid(); } else { this.SetProjectGuidFromProjectFile(); } // Ensure we have a valid build engine. this.buildEngine = this.buildEngine ?? MSBuild.ProjectCollection.GlobalProjectCollection; // based on the passed in flags, this either reloads/loads a project, or tries to create a new one // now we create a new project... we do that by loading the template and then saving under a new name // we also need to copy all the associated files with it. if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) { Debug.Assert(File.Exists(fileName), "Invalid filename passed to load the project. A valid filename is expected"); // This should be a very fast operation if the build project is already initialized by the Factory. SetBuildProject(Utilities.ReinitializeMsBuildProject(this.buildEngine, fileName, this.buildProject)); // Compute the file name // We try to solve two problems here. When input comes from a wizzard in case of zipped based projects // the parameters are different. // In that case the filename has the new filename in a temporay path. // First get the extension from the template. // Then get the filename from the name. // Then create the new full path of the project. var extension = Path.GetExtension(fileName); var tempName = string.Empty; // We have to be sure that we are not going to lose data here. If the project name is a.b.c then for a project that was based on a zipped template(the wizard calls us) GetFileNameWithoutExtension will suppress "c". // We are going to check if the parameter "name" is extension based and the extension is the same as the one from the "filename" parameter. var tempExtension = Path.GetExtension(name); if (!string.IsNullOrEmpty(tempExtension) && StringComparer.OrdinalIgnoreCase.Equals(tempExtension, extension)) { tempName = Path.GetFileNameWithoutExtension(name); } // If the tempExtension is not the same as the extension that the project name comes from then assume that the project name is a dotted name. else { tempName = Path.GetFileName(name); } Debug.Assert(!string.IsNullOrEmpty(tempName), "Could not compute project name"); var tempProjectFileName = tempName + extension; this.filename = CommonUtils.GetAbsoluteFilePath(location, tempProjectFileName); // Initialize the common project properties. this.InitializeProjectProperties(); ErrorHandler.ThrowOnFailure(this.Save(this.filename, 1, 0)); var unresolvedProjectHome = this.GetProjectProperty(CommonConstants.ProjectHome); var basePath = CommonUtils.GetAbsoluteDirectoryPath(Path.GetDirectoryName(fileName), unresolvedProjectHome); var baseLocation = CommonUtils.GetAbsoluteDirectoryPath(location, unresolvedProjectHome); if (!CommonUtils.IsSameDirectory(basePath, baseLocation)) { // now we do have the project file saved. we need to create embedded files. foreach (var item in this.BuildProject.Items) { // Ignore the item if it is a reference or folder if (this.FilterItemTypeToBeAddedToHierarchy(item.ItemType)) { continue; } // MSBuilds tasks/targets can create items (such as object files), // such items are not part of the project per say, and should not be displayed. // so ignore those items. if (!IsVisibleItem(item)) { continue; } var strRelFilePath = item.EvaluatedInclude; string strPathToFile; string newFileName; // taking the base name from the project template + the relative pathname, // and you get the filename strPathToFile = CommonUtils.GetAbsoluteFilePath(basePath, strRelFilePath); // the new path should be the base dir of the new project (location) + the rel path of the file newFileName = CommonUtils.GetAbsoluteFilePath(baseLocation, strRelFilePath); // now the copy file AddFileFromTemplate(strPathToFile, newFileName); } FinishProjectCreation(basePath, baseLocation); } } else { this.filename = fileName; } this.DiskNodes[this.filename] = this; // now reload to fix up references this.Reload(); successful = true; } finally { this.disableQueryEdit = false; if (!successful) { this.Close(); } } } } public override void Close() { this.projectOpened = false; this.isClosing = true; if (this.taskProvider != null) { this.taskProvider.Tasks.Clear(); } if (GetAutomationObject() is Automation.OAProject autoObject) { autoObject.Dispose(); } this.configProvider = null; try { // Walk the tree and close all nodes. // This has to be done before the project closes, since we want // state still available for the ProjectMgr on the nodes // when nodes are closing. CloseAllNodes(this); } finally { // HierarchyNode.Close() will also call Dispose on us base.Close(); } } /// <summary> /// Performs any new project initialization after the MSBuild project /// has been constructed and template files copied to the project directory. /// </summary> protected virtual void FinishProjectCreation(string sourceFolder, string destFolder) { } /// <summary> /// Called to add a file to the project from a template. /// Override to do it yourself if you want to customize the file /// </summary> /// <param name="source">Full path of template file</param> /// <param name="target">Full path of file once added to the project</param> public virtual void AddFileFromTemplate(string source, string target) { Utilities.ArgumentNotNullOrEmpty(nameof(source), source); Utilities.ArgumentNotNullOrEmpty(nameof(target), target); try { var directory = Path.GetDirectoryName(target); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.Copy(source, target, true); // best effort to reset the ReadOnly attribute File.SetAttributes(target, File.GetAttributes(target) & ~FileAttributes.ReadOnly); } catch (IOException e) { Trace.WriteLine("Exception : " + e.Message); } catch (UnauthorizedAccessException e) { Trace.WriteLine("Exception : " + e.Message); } catch (ArgumentException e) { Trace.WriteLine("Exception : " + e.Message); } catch (NotSupportedException e) { Trace.WriteLine("Exception : " + e.Message); } } /// <summary> /// Called when the project opens an editor window for the given file /// </summary> public virtual void OnOpenItem(string fullPathToSourceFile) { } /// <summary> /// This add methos adds the "key" item to the hierarchy, potentially adding other subitems in the process /// This method may recurse if the parent is an other subitem /// /// </summary> /// <param name="subitems">List of subitems not yet added to the hierarchy</param> /// <param name="key">Key to retrieve the target item from the subitems list</param> /// <returns>Newly added node</returns> /// <remarks>If the parent node was found we add the dependent item to it otherwise we add the item ignoring the "DependentUpon" metatdata</remarks> protected virtual HierarchyNode AddDependentFileNode(IDictionary<string, MSBuild.ProjectItem> subitems, string key) { Utilities.ArgumentNotNull(nameof(subitems), subitems); var item = subitems[key]; subitems.Remove(key); HierarchyNode newNode; HierarchyNode parent = null; var dependentOf = item.GetMetadataValue(ProjectFileConstants.DependentUpon); Debug.Assert(!StringComparer.OrdinalIgnoreCase.Equals(dependentOf, key), "File dependent upon itself is not valid. Ignoring the DependentUpon metadata"); if (subitems.ContainsKey(dependentOf)) { // The parent item is an other subitem, so recurse into this method to add the parent first parent = AddDependentFileNode(subitems, dependentOf); } else { // See if the parent node already exist in the hierarchy var path = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, dependentOf); if (ErrorHandler.Succeeded(this.ParseCanonicalName(path, out var parentItemID)) && parentItemID != 0) { parent = this.NodeFromItemId(parentItemID); } Debug.Assert(parent != null, "File dependent upon a non existing item or circular dependency. Ignoring the DependentUpon metadata"); } // If the parent node was found we add the dependent item to it otherwise we add the item ignoring the "DependentUpon" metatdata if (parent != null) { newNode = this.AddDependentFileNodeToNode(item, parent); } else { newNode = this.AddIndependentFileNode(item, GetItemParentNode(item)); } return newNode; } /// <summary> /// Do the build by invoking msbuild /// </summary> internal virtual void BuildAsync(uint vsopts, string config, IVsOutputWindowPane output, string target, Action<MSBuildResult, string> uiThreadCallback) { BuildPrelude(output); SetBuildConfigurationProperties(config); DoAsyncMSBuildSubmission(target, uiThreadCallback); } /// <summary> /// Return the value of a project property /// </summary> /// <param name="propertyName">Name of the property to get</param> /// <param name="resetCache">True to avoid using the cache</param> /// <returns>null if property does not exist, otherwise value of the property</returns> public virtual string GetProjectProperty(string propertyName, bool resetCache) { this.Site.GetUIThread().MustBeCalledFromUIThread(); var property = GetMsBuildProperty(propertyName, resetCache); return property?.EvaluatedValue; } /// <summary> /// Return the value of a project property in it's unevalauted form. /// </summary> /// <param name="propertyName">Name of the property to get, or null if the property doesn't exist</param> public virtual string GetUnevaluatedProperty(string propertyName) { this.Site.GetUIThread().MustBeCalledFromUIThread(); var res = this.buildProject.GetProperty(propertyName); if (res != null) { return res.UnevaluatedValue; } return null; } public virtual void MovePropertyToProjectFile(string propertyName) { this.Site.GetUIThread().MustBeCalledFromUIThread(); var prop = this.userBuildProject?.GetProperty(propertyName); if (prop != null) { this.buildProject.SetProperty(prop.Name, prop.UnevaluatedValue); this.userBuildProject.RemoveProperty(prop); } } public virtual void MovePropertyToUserFile(string propertyName) { this.Site.GetUIThread().MustBeCalledFromUIThread(); this.EnsureUserProjectFile(); var prop = this.buildProject.GetProperty(propertyName); if (prop != null) { this.userBuildProject.SetProperty(prop.Name, prop.UnevaluatedValue); this.buildProject.RemoveProperty(prop); } } /// <summary> /// Set value of project property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> public virtual bool SetProjectProperty(string propertyName, string propertyValue) { return this.SetProjectProperty(propertyName, propertyValue, userProjectFile: false); } /// <summary> /// Set value of user project property /// </summary> /// <param name="propertyName">Name of property</param> /// <param name="propertyValue">Value of property</param> public virtual bool SetUserProjectProperty(string propertyName, string propertyValue) { return this.SetProjectProperty(propertyName, propertyValue, userProjectFile: true); } private bool SetProjectProperty(string propertyName, string propertyValue, bool userProjectFile) { Utilities.ArgumentNotNull(nameof(propertyName), propertyName); this.Site.GetUIThread().MustBeCalledFromUIThread(); var oldValue = GetUnevaluatedProperty(propertyName) ?? string.Empty; propertyValue = propertyValue ?? string.Empty; if (StringComparer.Ordinal.Equals(oldValue, propertyValue)) { // Property is unchanged or unspecified, so don't set it. return false; } // Check out the project or user file. var editFile = userProjectFile ? this.UserProjectFilename : this.filename; if (!this.QueryEditFiles(false, editFile)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } if (userProjectFile) { this.EnsureUserProjectFile(); this.UserBuildProject.SetProperty(propertyName, propertyValue); } else { this.buildProject.SetProperty(propertyName, propertyValue); } RaiseProjectPropertyChanged(propertyName, oldValue, propertyValue); // property cache will need to be updated this.currentConfig = null; return true; } private void EnsureUserProjectFile() { if (this.userBuildProject == null) { // user project file doesn't exist yet, create it. var root = Microsoft.Build.Construction.ProjectRootElement.Create(this.BuildProject.ProjectCollection); this.userBuildProject = new MSBuild.Project(root, null, null, this.BuildProject.ProjectCollection); this.userBuildProject.FullPath = this.FileName + PerUserFileExtension; } } /// <summary> /// Get value of user project property /// </summary> /// <param name="propertyName">Name of property</param> public virtual string GetUserProjectProperty(string propertyName) { Utilities.ArgumentNotNull(nameof(propertyName), propertyName); if (this.userBuildProject == null) { return null; } // If user project file exists during project load/reload userBuildProject is initiated return this.userBuildProject.GetPropertyValue(propertyName); } public virtual CompilerParameters GetProjectOptions(string config) { // This needs to be commented out because if you build for Debug the properties from the Debug // config are cached. When you change configurations the old props are still cached, and // building for release the properties from the Debug config are used. This may not be the best // fix as every time you get properties the objects are reloaded, so for perf it is bad, but // for making it work it is necessary (reload props when a config is changed?). ////if(this.options != null) //// return this.options; var options = CreateProjectOptions(); if (config == null) { return options; } options.GenerateExecutable = true; this.SetConfiguration(config); var outputPath = this.GetOutputPath(this.currentConfig); if (!string.IsNullOrEmpty(outputPath)) { // absolutize relative to project folder location outputPath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectHome, outputPath); } // Set some default values options.OutputAssembly = outputPath + GetAssemblyName(config); var outputtype = GetProjectProperty(ProjectFileConstants.OutputType, false); if (!string.IsNullOrEmpty(outputtype)) { outputtype = outputtype.ToLower(CultureInfo.InvariantCulture); } options.MainClass = GetProjectProperty("StartupObject", false); // other settings from CSharp we may want to adopt at some point... // AssemblyKeyContainerName = "" //This is the key file used to sign the interop assembly generated when importing a com object via add reference // AssemblyOriginatorKeyFile = "" // DelaySign = "false" // DefaultClientScript = "JScript" // DefaultHTMLPageLayout = "Grid" // DefaultTargetSchema = "IE50" // PreBuildEvent = "" // PostBuildEvent = "" // RunPostBuildEvent = "OnBuildSuccess" if (GetBoolAttr(this.currentConfig, "DebugSymbols")) { options.IncludeDebugInformation = true; } if (GetBoolAttr(this.currentConfig, "RegisterForComInterop")) { } if (GetBoolAttr(this.currentConfig, "RemoveIntegerChecks")) { } if (GetBoolAttr(this.currentConfig, "TreatWarningsAsErrors")) { options.TreatWarningsAsErrors = true; } var warningLevel = GetProjectProperty("WarningLevel", resetCache: false); if (int.TryParse(warningLevel, out var newLevel)) { options.WarningLevel = newLevel; } return options; } private string GetOutputPath(MSBuildExecution.ProjectInstance properties) { return properties.GetPropertyValue("OutputPath"); } private bool GetBoolAttr(MSBuildExecution.ProjectInstance properties, string name) { var s = properties.GetPropertyValue(name); return (s != null && s.ToUpperInvariant().Trim() == "TRUE"); } public virtual bool GetBoolAttr(string config, string name) { SetConfiguration(config); try { return GetBoolAttr(this.currentConfig, name); } finally { SetCurrentConfiguration(); } } /// <summary> /// Get the assembly name for a given configuration /// </summary> /// <param name="config">the matching configuration in the msbuild file</param> /// <returns>assembly name</returns> public virtual string GetAssemblyName(string config) { SetConfiguration(config); try { var name = this.currentConfig.GetPropertyValue(ProjectFileConstants.AssemblyName) ?? this.Caption; var outputType = this.currentConfig.GetPropertyValue(ProjectFileConstants.OutputType); if ("library".Equals(outputType, StringComparison.OrdinalIgnoreCase)) { name += ".dll"; } else { name += ".exe"; } return name; } finally { SetCurrentConfiguration(); } } /// <summary> /// Determines whether a file is a code file. /// </summary> /// <param name="fileName">Name of the file to be evaluated</param> /// <returns>false by default for any fileName</returns> public virtual bool IsCodeFile(string fileName) { return false; } public virtual IReadOnlyCollection<string> CodeFileExtensions => Array.Empty<string>(); /// <summary> /// Determines whether the given file is a resource file (resx file). /// </summary> /// <param name="fileName">Name of the file to be evaluated.</param> /// <returns>true if the file is a resx file, otherwise false.</returns> public virtual bool IsEmbeddedResource(string fileName) { return StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(fileName), ".ResX"); } /// <summary> /// Create a file node based on an msbuild item. /// </summary> /// <param name="item">msbuild item</param> /// <returns>FileNode added</returns> public abstract FileNode CreateFileNode(ProjectElement item); /// <summary> /// Create a file node based on a string. /// </summary> /// <param name="file">filename of the new filenode</param> /// <returns>File node added</returns> public abstract FileNode CreateFileNode(string file); /// <summary> /// Create dependent file node based on an msbuild item /// </summary> /// <param name="item">msbuild item</param> /// <returns>dependent file node</returns> public virtual DependentFileNode CreateDependentFileNode(MsBuildProjectElement item) { return new DependentFileNode(this, item); } /// <summary> /// Create a dependent file node based on a string. /// </summary> /// <param name="file">filename of the new dependent file node</param> /// <returns>Dependent node added</returns> public virtual DependentFileNode CreateDependentFileNode(string file) { var item = AddFileToMsBuild(file); return this.CreateDependentFileNode(item); } /// <summary> /// Walks the subpaths of a project relative path and checks if the folder nodes hierarchy is already there, if not creates it. /// </summary> /// <param name="strPath">Path of the folder, can be relative to project or absolute</param> public virtual HierarchyNode CreateFolderNodes(string path, bool createOnDisk = true) { Utilities.ArgumentNotNull(nameof(path), path); if (Path.IsPathRooted(path)) { // Ensure we are using a path deeper than ProjectHome if (!CommonUtils.IsSubpathOf(this.ProjectHome, path)) { throw new ArgumentException("The path is not within the project", nameof(path)); } path = CommonUtils.GetRelativeDirectoryPath(this.ProjectHome, path); } // If the folder already exists, return early var strFullPath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectHome, path); if (ErrorHandler.Succeeded(ParseCanonicalName(strFullPath, out var uiItemId)) && uiItemId != 0) { if (this.NodeFromItemId(uiItemId) is FolderNode folder) { // found the folder, return immediately return folder; } } var parts = strFullPath.Substring(this.ProjectHome.Length).Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) { // pointing at the project home, it already exists return this; } path = parts[0]; var fullPath = Path.Combine(this.ProjectHome, path) + "\\"; var relPath = path; HierarchyNode curParent = VerifySubFolderExists(path, fullPath, this, createOnDisk); // now we have an array of subparts.... for (var i = 1; i < parts.Length; i++) { if (parts[i].Length > 0) { fullPath = Path.Combine(fullPath, parts[i]) + "\\"; relPath = Path.Combine(relPath, parts[i]); curParent = VerifySubFolderExists(relPath, fullPath, curParent, createOnDisk); } } return curParent; } /// <summary> /// Defines if Node has Designer. By default we do not support designers for nodes /// </summary> /// <param name="itemPath">Path to item to query for designer support</param> /// <returns>true if node has designer</returns> public virtual bool NodeHasDesigner(string itemPath) { return false; } /// <summary> /// List of Guids of the config independent property pages. It is called by the GetProperty for VSHPROPID_PropertyPagesCLSIDList property. /// </summary> /// <returns></returns> protected virtual Guid[] GetConfigurationIndependentPropertyPages() => Array.Empty<Guid>(); /// <summary> /// Returns a list of Guids of the configuration dependent property pages. It is called by the GetProperty for VSHPROPID_CfgPropertyPagesCLSIDList property. /// </summary> /// <returns></returns> protected virtual Guid[] GetConfigurationDependentPropertyPages() => Array.Empty<Guid>(); /// <summary> /// An ordered list of guids of the prefered property pages. See <see cref="__VSHPROPID.VSHPROPID_PriorityPropertyPagesCLSIDList"/> /// </summary> /// <returns>An array of guids.</returns> protected virtual Guid[] GetPriorityProjectDesignerPages() { return new Guid[] { Guid.Empty }; } /// <summary> /// Takes a path and verifies that we have a node with that name. /// It is meant to be a helper method for CreateFolderNodes(). /// For some scenario it may be useful to override. /// </summary> /// <param name="relativePath">The relative path to the subfolder we want to create, without a trailing \</param> /// <param name="fullPath">the full path to the subfolder we want to verify.</param> /// <param name="parent">the parent node where to add the subfolder if it does not exist.</param> /// <returns>the foldernode correcsponding to the path.</returns> protected virtual FolderNode VerifySubFolderExists(string relativePath, string fullPath, HierarchyNode parent, bool createOnDisk = true) { Debug.Assert(!CommonUtils.HasEndSeparator(relativePath)); FolderNode folderNode = null; if (ErrorHandler.Succeeded(this.ParseCanonicalName(fullPath, out var uiItemId)) && uiItemId != 0) { Debug.Assert(this.NodeFromItemId(uiItemId) is FolderNode, "Not a FolderNode"); folderNode = (FolderNode)this.NodeFromItemId(uiItemId); } if (folderNode == null && fullPath != null && parent != null) { // folder does not exist yet... // We could be in the process of loading so see if msbuild knows about it ProjectElement item = null; var items = this.buildProject.GetItemsByEvaluatedInclude(relativePath); if (items.Count == 0) { items = this.buildProject.GetItemsByEvaluatedInclude(relativePath + "\\"); } if (items.Count != 0) { item = new MsBuildProjectElement(this, items.First()); } else { item = AddFolderToMsBuild(fullPath); } if (createOnDisk) { Directory.CreateDirectory(fullPath); } folderNode = CreateFolderNode(item); parent.AddChild(folderNode); } return folderNode; } /// <summary> /// To support virtual folders, override this method to return your own folder nodes /// </summary> /// <param name="path">Path to store for this folder</param> /// <param name="element">Element corresponding to the folder</param> /// <returns>A FolderNode that can then be added to the hierarchy</returns> protected internal virtual FolderNode CreateFolderNode(ProjectElement element) { return new FolderNode(this, element); } /// <summary> /// Gets the list of selected HierarchyNode objects /// </summary> /// <returns>A list of HierarchyNode objects</returns> protected internal virtual IList<HierarchyNode> GetSelectedNodes() { // Retrieve shell interface in order to get current selection var monitorSelection = this.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection; Utilities.CheckNotNull(monitorSelection); var selectedNodes = new List<HierarchyNode>(); var hierarchyPtr = IntPtr.Zero; var selectionContainer = IntPtr.Zero; try { ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out var itemid, out var multiItemSelect, out selectionContainer)); // We only care if there are one ore more nodes selected in the tree if (itemid != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero) { var hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (itemid != VSConstants.VSITEMID_SELECTION) { // This is a single selection. Compare hirarchy with our hierarchy and get node from itemid if (Utilities.IsSameComObject(this, hierarchy)) { var node = this.NodeFromItemId(itemid); if (node != null) { selectedNodes.Add(node); } } } else if (multiItemSelect != null) { ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out var numberOfSelectedItems, out var isSingleHierarchyInt)); var isSingleHierarchy = (isSingleHierarchyInt != 0); // Now loop all selected items and add to the list only those that are selected within this hierarchy if (!isSingleHierarchy || (isSingleHierarchy && Utilities.IsSameComObject(this, hierarchy))) { Debug.Assert(numberOfSelectedItems > 0, "Bad number of selected itemd"); var vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems]; var flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0; ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections)); foreach (var vsItemSelection in vsItemSelections) { if (isSingleHierarchy || Utilities.IsSameComObject(this, vsItemSelection.pHier)) { var node = this.NodeFromItemId(vsItemSelection.itemid); if (node != null) { selectedNodes.Add(node); } } } } } } } finally { if (hierarchyPtr != IntPtr.Zero) { Marshal.Release(hierarchyPtr); } if (selectionContainer != IntPtr.Zero) { Marshal.Release(selectionContainer); } } return selectedNodes; } /// <summary> /// Recursevily walks the hierarchy nodes and redraws the state icons /// </summary> protected internal override void UpdateSccStateIcons() { if (this.FirstChild == null) { return; } for (var n = this.FirstChild; n != null; n = n.NextSibling) { n.UpdateSccStateIcons(); } } /// <summary> /// Handles the shows all objects command. /// </summary> /// <returns></returns> protected internal virtual int ShowAllFiles() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } /// <summary> /// Unloads the project. /// </summary> /// <returns></returns> protected internal virtual int UnloadProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } /// <summary> /// Handles the clean project command. /// </summary> /// <returns></returns> protected virtual int CleanProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } /// <summary> /// Reload project from project file /// </summary> protected virtual void Reload() { Debug.Assert(this.buildEngine != null, "There is no build engine defined for this project"); try { this.disableQueryEdit = true; this.isClosed = false; this.EventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents | ProjectNode.EventTriggering.DoNotTriggerTrackerEvents; SetBuildProject(Utilities.ReinitializeMsBuildProject(this.buildEngine, this.filename, this.buildProject)); if (File.Exists(this.UserProjectFilename)) { this.userBuildProject = this.BuildProject.ProjectCollection.LoadProject(this.UserProjectFilename); } // Load the guid SetProjectGuidFromProjectFile(); ProcessReferences(); ProcessFolders(); ProcessFiles(); LoadNonBuildInformation(); InitSccInfo(); RegisterSccProject(); } finally { this.isDirty = false; this.EventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll; this.disableQueryEdit = false; } } /// <summary> /// Renames the project file /// </summary> /// <param name="newFile">The full path of the new project file.</param> protected virtual void RenameProjectFile(string newFile) { var shell = GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); // Figure out what the new full name is var oldFile = this.Url; var vsSolution = (IVsSolution)GetService(typeof(SVsSolution)); if (ErrorHandler.Succeeded(vsSolution.QueryRenameProject(GetOuterInterface<IVsProject>(), oldFile, newFile, 0, out var canContinue)) && canContinue != 0) { var isFileSame = CommonUtils.IsSamePath(oldFile, newFile); // If file already exist and is not the same file with different casing if (!isFileSame && File.Exists(newFile)) { // Prompt the user for replace var message = SR.GetString(SR.FileAlreadyExists, newFile); if (!Utilities.IsInAutomationFunction(this.Site)) { if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_WARNING, shell)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } else { throw new InvalidOperationException(message); } // Delete the destination file after making sure it is not read only File.SetAttributes(newFile, FileAttributes.Normal); File.Delete(newFile); } var fileChanges = new SuspendFileChanges(this.Site, this.filename); fileChanges.Suspend(); try { // Actual file rename SaveMSBuildProjectFileAs(newFile); if (!isFileSame) { // Now that the new file name has been created delete the old one. // TODO: Handle source control issues. File.SetAttributes(oldFile, FileAttributes.Normal); File.Delete(oldFile); } OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0); // Update solution ErrorHandler.ThrowOnFailure(vsSolution.OnAfterRenameProject((IVsProject)this, oldFile, newFile, 0)); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); } finally { fileChanges.Resume(); } } else { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } /// <summary> /// Filter items that should not be processed as file items. Example: Folders and References. /// </summary> protected virtual bool FilterItemTypeToBeAddedToHierarchy(string itemType) { return (StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.Reference) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.ProjectReference) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.COMReference) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.Folder) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.WebReference) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.WebReferenceFolder) || StringComparer.OrdinalIgnoreCase.Equals(itemType, ProjectFileConstants.WebPiReference)); } /// <summary> /// Associate window output pane to the build logger /// </summary> /// <param name="output"></param> protected virtual void SetOutputLogger(IVsOutputWindowPane output) { // Create our logger, if it was not specified if (this.BuildLogger == null) { // Create the logger var logger = new IDEBuildLogger(output, this.TaskProvider, GetOuterInterface<IVsHierarchy>()) { ErrorString = this.ErrorString, WarningString = this.WarningString }; this.BuildLogger = logger; } else { this.BuildLogger.OutputWindowPane = output; } this.BuildLogger.RefreshVerbosity(); } /// <summary> /// Set configuration properties for a specific configuration /// </summary> /// <param name="config">configuration name</param> protected virtual void SetBuildConfigurationProperties(string config) { CompilerParameters options = null; if (!string.IsNullOrEmpty(config)) { options = this.GetProjectOptions(config); } if (options != null && this.buildProject != null) { // Make sure the project configuration is set properly this.SetConfiguration(config); } } /// <summary> /// This execute an MSBuild target for a design-time build. /// </summary> /// <param name="target">Name of the MSBuild target to execute</param> /// <returns>Result from executing the target (success/failure)</returns> /// <remarks> /// If you depend on the items/properties generated by the target /// you should be aware that any call to BuildTarget on any project /// will reset the list of generated items/properties /// </remarks> protected virtual MSBuildResult InvokeMsBuild(string target) { this.Site.GetUIThread().MustBeCalledFromUIThread(); var result = MSBuildResult.Failed; // Do the actual Build if (this.buildProject != null) { const bool designTime = true; if (!TryBeginBuild(designTime)) { throw new InvalidOperationException("A build is already in progress."); } BuildSubmission submission = null; try { var targetsToBuild = new string[target != null ? 1 : 0]; if (target != null) { targetsToBuild[0] = target; } this.currentConfig = this.BuildProject.CreateProjectInstance(); var requestData = new BuildRequestData(this.currentConfig, targetsToBuild, this.BuildProject.ProjectCollection.HostServices, BuildRequestDataFlags.ReplaceExistingProjectInstance); submission = BuildManager.DefaultBuildManager.PendBuildRequest(requestData); if (this.buildManagerAccessor != null) { ErrorHandler.ThrowOnFailure(buildManagerAccessor.RegisterLogger(submission.SubmissionId, this.BuildLogger)); } var buildResult = submission.Execute(); result = (buildResult.OverallResult == BuildResultCode.Success) ? MSBuildResult.Successful : MSBuildResult.Failed; } finally { EndBuild(submission, designTime); } } return result; } /// <summary> /// Start MSBuild build submission /// </summary> /// <param name="target">target to build</param> /// <param name="projectInstance">project instance to build; if null, this.BuildProject.CreateProjectInstance() is used to populate</param> /// <param name="uiThreadCallback">callback to be run UI thread </param> /// <returns>A Build submission instance.</returns> protected virtual BuildSubmission DoAsyncMSBuildSubmission(string target, Action<MSBuildResult, string> uiThreadCallback) { const bool designTime = false; if (!TryBeginBuild(designTime)) { if (uiThreadCallback != null) { uiThreadCallback(MSBuildResult.Failed, target); } return null; } var targetsToBuild = new string[target != null ? 1 : 0]; if (target != null) { targetsToBuild[0] = target; } var projectInstance = this.BuildProject.CreateProjectInstance(); projectInstance.SetProperty(GlobalProperty.VisualStudioStyleErrors.ToString(), "true"); projectInstance.SetProperty("UTFOutput", "true"); projectInstance.SetProperty(GlobalProperty.BuildingInsideVisualStudio.ToString(), "true"); this.BuildProject.ProjectCollection.HostServices.SetNodeAffinity(projectInstance.FullPath, NodeAffinity.InProc); var requestData = new BuildRequestData(projectInstance, targetsToBuild, this.BuildProject.ProjectCollection.HostServices, BuildRequestDataFlags.ReplaceExistingProjectInstance); var submission = BuildManager.DefaultBuildManager.PendBuildRequest(requestData); try { if (this.BuildLogger != null) { ErrorHandler.ThrowOnFailure(this.buildManagerAccessor.RegisterLogger(submission.SubmissionId, this.BuildLogger)); } submission.ExecuteAsync(sub => { this.Site.GetUIThread().Invoke(() => { var ideLogger = this.BuildLogger; if (ideLogger != null) { ideLogger.FlushBuildOutput(); } EndBuild(sub, designTime); uiThreadCallback((sub.BuildResult.OverallResult == BuildResultCode.Success) ? MSBuildResult.Successful : MSBuildResult.Failed, target); }); }, null); } catch (Exception e) { Debug.Fail(e.ToString()); EndBuild(submission, designTime); if (uiThreadCallback != null) { uiThreadCallback(MSBuildResult.Failed, target); } throw; } return submission; } /// <summary> /// Initialize common project properties with default value if they are empty /// </summary> /// <remarks>The following common project properties are defaulted to projectName (if empty): /// AssemblyName, Name and RootNamespace. /// If the project filename is not set then no properties are set</remarks> protected virtual void InitializeProjectProperties() { // Get projectName from project filename. Return if not set var projectName = Path.GetFileNameWithoutExtension(this.filename); if (string.IsNullOrEmpty(projectName)) { return; } if (string.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.AssemblyName))) { SetProjectProperty(ProjectFileConstants.AssemblyName, projectName); } if (string.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.Name))) { SetProjectProperty(ProjectFileConstants.Name, projectName); } if (string.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.RootNamespace))) { SetProjectProperty(ProjectFileConstants.RootNamespace, projectName); } } /// <summary> /// Factory method for configuration provider /// </summary> /// <returns>Configuration provider created</returns> protected abstract ConfigProvider CreateConfigProvider(); /// <summary> /// Factory method for reference container node /// </summary> /// <returns>ReferenceContainerNode created</returns> protected virtual ReferenceContainerNode CreateReferenceContainerNode() { return new ReferenceContainerNode(this); } /// <summary> /// Saves the project file on a new name. /// </summary> /// <param name="newFileName">The new name of the project file.</param> /// <returns>Success value or an error code.</returns> protected virtual int SaveAs(string newFileName) { Debug.Assert(!string.IsNullOrEmpty(newFileName), "Cannot save project file for an empty or null file name"); Utilities.ArgumentNotNullOrEmpty(nameof(newFileName), newFileName); newFileName = newFileName.Trim(); var errorMessage = string.Empty; if (newFileName.Length > NativeMethods.MAX_PATH) { errorMessage = SR.GetString(SR.PathTooLong, newFileName); } else { var fileName = string.Empty; try { fileName = Path.GetFileNameWithoutExtension(newFileName); } // We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted. catch (ArgumentException) { errorMessage = SR.GetString(SR.ErrorInvalidFileName, newFileName); } if (errorMessage.Length == 0) { // If there is no filename or it starts with a leading dot issue an error message and quit. // For some reason the save as dialog box allows to save files like "......ext" if (string.IsNullOrEmpty(fileName) || fileName[0] == '.') { errorMessage = SR.GetString(SR.FileNameCannotContainALeadingPeriod); } else if (Utilities.ContainsInvalidFileNameChars(newFileName)) { errorMessage = SR.GetString(SR.ErrorInvalidFileName, newFileName); } } } if (errorMessage.Length > 0) { // If it is not called from an automation method show a dialog box. if (!Utilities.IsInAutomationFunction(this.Site)) { string title = null; var icon = OLEMSGICON.OLEMSGICON_CRITICAL; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; Utilities.ShowMessageBox(this.Site, title, errorMessage, icon, buttons, defaultButton); return VSConstants.OLE_E_PROMPTSAVECANCELLED; } throw new InvalidOperationException(errorMessage); } var oldName = this.filename; var solution = this.Site.GetService(typeof(IVsSolution)) as IVsSolution; Utilities.CheckNotNull(solution, "Could not retrieve the solution form the service provider"); ErrorHandler.ThrowOnFailure(solution.QueryRenameProject(this.GetOuterInterface<IVsProject>(), this.filename, newFileName, 0, out var canRenameContinue)); if (canRenameContinue == 0) { return VSConstants.OLE_E_PROMPTSAVECANCELLED; } var fileChanges = new SuspendFileChanges(this.Site, oldName); fileChanges.Suspend(); try { // Save the project file and project file related properties. this.SaveMSBuildProjectFileAs(newFileName); // TODO: If source control is enabled check out the project file. //Redraw. this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0); ErrorHandler.ThrowOnFailure(solution.OnAfterRenameProject(this, oldName, this.filename, 0)); var shell = this.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); } finally { fileChanges.Resume(); } return VSConstants.S_OK; } /// <summary> /// Saves project file related information to the new file name. It also calls msbuild API to save the project file. /// It is called by the SaveAs method and the SetEditLabel before the project file rename related events are triggered. /// An implementer can override this method to provide specialized semantics on how the project file is renamed in the msbuild file. /// </summary> /// <param name="newFileName">The new full path of the project file</param> protected virtual void SaveMSBuildProjectFileAs(string newFileName) { Debug.Assert(!string.IsNullOrEmpty(newFileName), "Cannot save project file for an empty or null file name"); var newProjectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(newFileName), this.ProjectHome); this.buildProject.SetProperty(CommonConstants.ProjectHome, newProjectHome); this.buildProject.FullPath = newFileName; this.DiskNodes.TryRemove(this.filename, out _); this.filename = newFileName; this.DiskNodes[this.filename] = this; var newFileNameWithoutExtension = Path.GetFileNameWithoutExtension(newFileName); // Refresh solution explorer SetProjectProperty(ProjectFileConstants.Name, newFileNameWithoutExtension); // Saves the project file on disk. SaveMSBuildProjectFile(newFileName); } /// <summary> /// Adds a file to the msbuild project. /// </summary> /// <param name="file">The file to be added.</param> /// <returns>A Projectelement describing the newly added file.</returns> internal virtual MsBuildProjectElement AddFileToMsBuild(string file) { MsBuildProjectElement newItem; var itemPath = CommonUtils.GetRelativeFilePath(this.ProjectHome, file); Debug.Assert(!Path.IsPathRooted(itemPath), "Cannot add item with full path."); if (this.IsCodeFile(itemPath)) { newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.Compile); newItem.SetMetadata(ProjectFileConstants.SubType, ProjectFileAttributeValue.Code); } else if (this.IsEmbeddedResource(itemPath)) { newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.EmbeddedResource); } else { newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.Content); newItem.SetMetadata(ProjectFileConstants.SubType, ProjectFileConstants.Content); } return newItem; } /// <summary> /// Adds a folder to the msbuild project. /// </summary> /// <param name="folder">The folder to be added.</param> /// <returns>A ProjectElement describing the newly added folder.</returns> protected virtual ProjectElement AddFolderToMsBuild(string folder) { ProjectElement newItem; if (Path.IsPathRooted(folder)) { folder = CommonUtils.GetRelativeDirectoryPath(this.ProjectHome, folder); Debug.Assert(!Path.IsPathRooted(folder), "Cannot add item with full path."); } newItem = this.CreateMsBuildFileItem(folder, ProjectFileConstants.Folder); return newItem; } private const int E_CANCEL_FILE_ADD = unchecked((int)0xA0010001); // Severity = Error, Customer Bit set, Facility = 1, Error = 1 /// <summary> /// Checks to see if the user wants to overwrite the specified file name. /// /// Returns: /// E_ABORT if we disallow the user to overwrite the file /// OLECMDERR_E_CANCELED if the user wants to cancel /// S_OK if the user wants to overwrite /// E_CANCEL_FILE_ADD (0xA0010001) if the user doesn't want to overwrite and wants to abort the larger transaction /// </summary> /// <param name="originalFileName"></param> /// <param name="computedNewFileName"></param> /// <param name="canCancel"></param> /// <returns></returns> protected int CanOverwriteExistingItem(string originalFileName, string computedNewFileName, bool inProject = true) { if (string.IsNullOrEmpty(originalFileName) || string.IsNullOrEmpty(computedNewFileName)) { return VSConstants.E_INVALIDARG; } var title = string.Empty; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; // File already exists in project... message box var message = SR.GetString(inProject ? SR.FileAlreadyInProject : SR.FileAlreadyExists, Path.GetFileName(computedNewFileName)); var icon = OLEMSGICON.OLEMSGICON_QUERY; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNO; var msgboxResult = Utilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); if (msgboxResult == NativeMethods.IDCANCEL) { return (int)E_CANCEL_FILE_ADD; } else if (msgboxResult != NativeMethods.IDYES) { return (int)OleConstants.OLECMDERR_E_CANCELED; } return VSConstants.S_OK; } /// <summary> /// Adds a new file node to the hierarchy. /// </summary> /// <param name="parentNode">The parent of the new fileNode</param> /// <param name="fileName">The file name</param> protected virtual void AddNewFileNodeToHierarchy(HierarchyNode parentNode, string fileName) { Utilities.ArgumentNotNull(nameof(parentNode), parentNode); HierarchyNode child; // In the case of subitem, we want to create dependent file node // and set the DependentUpon property if (this.CanFileNodesHaveChilds && (parentNode is FileNode || parentNode is DependentFileNode)) { child = this.CreateDependentFileNode(fileName); child.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, parentNode.ItemNode.GetMetadata(ProjectFileConstants.Include)); // Make sure to set the HasNameRelation flag on the dependent node if it is related to the parent by name if (!child.HasParentNodeNameRelation && StringComparer.OrdinalIgnoreCase.Equals(child.GetRelationalName(), parentNode.GetRelationalName())) { child.HasParentNodeNameRelation = true; } } else { //Create and add new filenode to the project child = this.CreateFileNode(fileName); } parentNode.AddChild(child); // TODO : Revisit the VSADDFILEFLAGS here. Can it be a nested project? this.tracker.OnItemAdded(fileName, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags); } /// <summary> /// Defines whther the current mode of the project is in a supress command mode. /// </summary> /// <returns></returns> protected internal virtual bool IsCurrentStateASuppressCommandsMode() { if (VsShellUtilities.IsSolutionBuilding(this.Site)) { return true; } var dbgMode = VsShellUtilities.GetDebugMode(this.Site) & ~DBGMODE.DBGMODE_EncMask; if (dbgMode == DBGMODE.DBGMODE_Run || dbgMode == DBGMODE.DBGMODE_Break) { return true; } return false; } /// <summary> /// This is the list of output groups that the configuration object should /// provide. /// The first string is the name of the group. /// The second string is the target name (MSBuild) for that group. /// /// To add/remove OutputGroups, simply override this method and edit the list. /// /// To get nice display names and description for your groups, override: /// - GetOutputGroupDisplayName /// - GetOutputGroupDescription /// </summary> /// <returns>List of output group name and corresponding MSBuild target</returns> protected internal virtual IList<KeyValuePair<string, string>> GetOutputGroupNames() { return new List<KeyValuePair<string, string>>(OutputGroupNames); } /// <summary> /// Get the display name of the given output group. /// </summary> /// <param name="canonicalName">Canonical name of the output group</param> /// <returns>Display name</returns> protected internal virtual string GetOutputGroupDisplayName(string canonicalName) { var result = SR.GetString("Output" + canonicalName); if (string.IsNullOrEmpty(result)) { result = canonicalName; } return result; } /// <summary> /// Get the description of the given output group. /// </summary> /// <param name="canonicalName">Canonical name of the output group</param> /// <returns>Description</returns> protected internal virtual string GetOutputGroupDescription(string canonicalName) { var result = SR.GetString("Output" + canonicalName + "Description"); if (string.IsNullOrEmpty(result)) { result = canonicalName; } return result; } /// <summary> /// Set the configuration in MSBuild. /// This does not get persisted and is used to evaluate msbuild conditions /// which are based on the $(Configuration) property. /// </summary> protected internal virtual void SetCurrentConfiguration() { // Can't ask for the active config until the project is opened, so do nothing in that scenario if (!this.IsProjectOpened) { return; } var solutionBuild = (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)); var cfg = new IVsProjectCfg[1]; ErrorHandler.ThrowOnFailure( solutionBuild.FindActiveProjectCfg(IntPtr.Zero, IntPtr.Zero, GetOuterHierarchy(), cfg)); ErrorHandler.ThrowOnFailure(cfg[0].get_CanonicalName(out var name)); SetConfiguration(name); } /// <summary> /// Set the configuration property in MSBuild. /// This does not get persisted and is used to evaluate msbuild conditions /// which are based on the $(Configuration) property. /// </summary> /// <param name="config">Configuration name</param> protected internal virtual void SetConfiguration(string config) { Utilities.ArgumentNotNull(nameof(config), config); // Can't ask for the active config until the project is opened, so do nothing in that scenario if (!this.IsProjectOpened) { return; } var propertiesChanged = this.BuildProject.SetGlobalProperty(ProjectFileConstants.Configuration, config); if (this.currentConfig == null || propertiesChanged) { this.currentConfig = this.BuildProject.CreateProjectInstance(); } } /// <summary> /// Loads reference items from the project file into the hierarchy. /// </summary> protected internal virtual void ProcessReferences() { var container = GetReferenceContainer(); if (null == container) { // Process References var referencesFolder = CreateReferenceContainerNode(); if (null == referencesFolder) { // This project type does not support references or there is a problem // creating the reference container node. // In both cases there is no point to try to process references, so exit. return; } this.AddChild(referencesFolder); container = referencesFolder; } // Load the referernces. container.LoadReferencesFromBuildProject(this.buildProject); } /// <summary> /// Loads folders from the project file into the hierarchy. /// </summary> protected internal virtual void ProcessFolders() { // Process Folders (useful to persist empty folder) foreach (var folder in this.buildProject.GetItems(ProjectFileConstants.Folder).ToArray()) { var strPath = folder.EvaluatedInclude; // We do not need any special logic for assuring that a folder is only added once to the ui hierarchy. // The below method will only add once the folder to the ui hierarchy this.CreateFolderNodes(strPath, false); } } /// <summary> /// Loads file items from the project file into the hierarchy. /// </summary> protected internal virtual void ProcessFiles() { var subitemsKeys = new List<string>(); var subitems = new Dictionary<string, MSBuild.ProjectItem>(); // Define a set for our build items. The value does not really matter here. var items = new Dictionary<string, MSBuild.ProjectItem>(); // Process Files foreach (var item in this.buildProject.Items.ToArray()) // copy the array, we could add folders while enumerating { // Ignore the item if it is a reference or folder if (this.FilterItemTypeToBeAddedToHierarchy(item.ItemType)) { continue; } // Check if the item is imported. If it is we'll only show it in the // project if it is a Visible item meta data. Visible can also be used // to hide non-imported items. if (!IsVisibleItem(item)) { continue; } // If the item is already contained do nothing. // TODO: possibly report in the error list that the the item is already contained in the project file similar to Language projects. if (items.ContainsKey(item.EvaluatedInclude.ToUpperInvariant())) { continue; } // Make sure that we do not want to add the item, dependent, or independent twice to the ui hierarchy items.Add(item.EvaluatedInclude.ToUpperInvariant(), item); var dependentOf = item.GetMetadataValue(ProjectFileConstants.DependentUpon); var link = item.GetMetadataValue(ProjectFileConstants.Link); if (!string.IsNullOrWhiteSpace(link)) { if (Path.IsPathRooted(link)) { // ignore fully rooted link paths. continue; } if (!Path.IsPathRooted(item.EvaluatedInclude)) { var itemPath = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, item.EvaluatedInclude); if (CommonUtils.IsSubpathOf(this.ProjectHome, itemPath)) { // linked file which lives in our directory, don't allow that. continue; } } var linkPath = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, link); if (!CommonUtils.IsSubpathOf(this.ProjectHome, linkPath)) { // relative path outside of project, don't allow that. continue; } } if (!this.CanFileNodesHaveChilds || string.IsNullOrEmpty(dependentOf)) { var parent = GetItemParentNode(item); var itemPath = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, item.EvaluatedInclude); var existingChild = FindNodeByFullPath(itemPath); if (existingChild != null) { if (existingChild.IsLinkFile) { // remove link node. existingChild.Parent.RemoveChild(existingChild); } else { // we have duplicate entries, or this is a link file. continue; } } AddIndependentFileNode(item, parent); } else { // We will process dependent items later. // Note that we use 2 lists as we want to remove elements from // the collection as we loop through it subitemsKeys.Add(item.EvaluatedInclude); subitems.Add(item.EvaluatedInclude, item); } } // Now process the dependent items. if (this.CanFileNodesHaveChilds) { ProcessDependentFileNodes(subitemsKeys, subitems); } } private static bool IsVisibleItem(MSBuild.ProjectItem item) { var isVisibleItem = true; var visible = item.GetMetadataValue(CommonConstants.Visible); if ((item.IsImported && !StringComparer.OrdinalIgnoreCase.Equals(visible, "true")) || StringComparer.OrdinalIgnoreCase.Equals(visible, "false")) { isVisibleItem = false; } return isVisibleItem; } /// <summary> /// Processes dependent filenodes from list of subitems. Multi level supported, but not circular dependencies. /// </summary> /// <param name="subitemsKeys">List of sub item keys </param> /// <param name="subitems"></param> protected internal virtual void ProcessDependentFileNodes(IList<string> subitemsKeys, Dictionary<string, MSBuild.ProjectItem> subitems) { if (subitemsKeys == null || subitems == null) { return; } foreach (var key in subitemsKeys) { // A previous pass could have removed the key so make sure it still needs to be added if (!subitems.ContainsKey(key)) { continue; } AddDependentFileNode(subitems, key); } } /// <summary> /// For flavored projects which implement IPersistXMLFragment, load the information now /// </summary> protected internal virtual void LoadNonBuildInformation() { var outerHierarchy = GetOuterInterface<IPersistXMLFragment>(); if (outerHierarchy != null) { this.LoadXmlFragment(outerHierarchy, null, null); } } /// <summary> /// Used to sort nodes in the hierarchy. /// </summary> internal int CompareNodes(HierarchyNode node1, HierarchyNode node2) { Debug.Assert(node1 != null); Debug.Assert(node2 != null); if (node1.SortPriority == node2.SortPriority) { return StringComparer.CurrentCultureIgnoreCase.Compare(node2.Caption, node1.Caption); } else { return node2.SortPriority - node1.SortPriority; } } protected abstract void InitializeCATIDs(); #endregion #region non-virtual methods internal void InstantiateItemsDraggedOrCutOrCopiedList() { this.itemsDraggedOrCutOrCopied = new List<HierarchyNode>(); } /// <summary> /// Overloaded method. Invokes MSBuild using the default configuration and does without logging on the output window pane. /// </summary> public MSBuildResult Build(string target) { this.Site.GetUIThread().MustBeCalledFromUIThread(); return this.Build(string.Empty, target); } /// <summary> /// This is called from the main thread before the background build starts. /// cleanBuild is not part of the vsopts, but passed down as the callpath is differently /// PrepareBuild mainly creates directories and cleans house if cleanBuild is true /// </summary> public virtual void PrepareBuild(string config, bool cleanBuild) { this.Site.GetUIThread().MustBeCalledFromUIThread(); try { SetConfiguration(config); var outputPath = Path.GetDirectoryName(GetProjectProperty("OutputPath")); PackageUtilities.EnsureOutputPath(outputPath); } finally { SetCurrentConfiguration(); } } /// <summary> /// Do the build by invoking msbuild /// </summary> public virtual MSBuildResult Build(string config, string target) { this.Site.GetUIThread().MustBeCalledFromUIThread(); lock (ProjectNode.BuildLock) { IVsOutputWindowPane output = null; var outputWindow = (IVsOutputWindow)GetService(typeof(SVsOutputWindow)); if (outputWindow != null && ErrorHandler.Failed(outputWindow.GetPane(VSConstants.GUID_BuildOutputWindowPane, out output))) { outputWindow.CreatePane(VSConstants.GUID_BuildOutputWindowPane, "Build", 1, 1); outputWindow.GetPane(VSConstants.GUID_BuildOutputWindowPane, out output); } var engineLogOnlyCritical = this.BuildPrelude(output); var result = MSBuildResult.Failed; try { SetBuildConfigurationProperties(config); result = InvokeMsBuild(target); } finally { // Unless someone specifically request to use an output window pane, we should not output to it if (null != output) { SetOutputLogger(null); this.BuildEngine.OnlyLogCriticalEvents = engineLogOnlyCritical; } } return result; } } /// <summary> /// Get value of Project property /// </summary> /// <param name="propertyName">Name of Property to retrieve</param> /// <returns>Value of property</returns> public string GetProjectProperty(string propertyName) { return this.GetProjectProperty(propertyName, true); } /// <summary> /// Get Node from ItemID. /// </summary> /// <param name="itemId">ItemID for the requested node</param> /// <returns>Node if found</returns> public HierarchyNode NodeFromItemId(uint itemId) { if (VSConstants.VSITEMID_ROOT == itemId) { return this; } else if (VSConstants.VSITEMID_NIL == itemId) { return null; } else if (VSConstants.VSITEMID_SELECTION == itemId) { throw new NotImplementedException(); } return (HierarchyNode)this.ItemIdMap[itemId]; } /// <summary> /// This method return new project element, and add new MSBuild item to the project/build hierarchy /// </summary> /// <param name="file">file name</param> /// <param name="itemType">MSBuild item type</param> /// <returns>new project element</returns> public MsBuildProjectElement CreateMsBuildFileItem(string file, string itemType) { return new MsBuildProjectElement(this, file, itemType); } /// <summary> /// This method returns new project element based on existing MSBuild item. It does not modify/add project/build hierarchy at all. /// </summary> /// <param name="item">MSBuild item instance</param> /// <returns>wrapping project element</returns> public MsBuildProjectElement GetProjectElement(MSBuild.ProjectItem item) { return new MsBuildProjectElement(this, item); } /// <summary> /// Create FolderNode from Path /// </summary> /// <param name="path">Path to folder</param> /// <returns>FolderNode created that can be added to the hierarchy</returns> protected internal FolderNode CreateFolderNode(string path) { var item = this.AddFolderToMsBuild(path); var folderNode = CreateFolderNode(item); return folderNode; } internal bool QueryEditFiles(bool suppressUI, params string[] files) { var result = true; if (this.disableQueryEdit) { return true; } else { if (this.GetService(typeof(SVsQueryEditQuerySave)) is IVsQueryEditQuerySave2 queryEditQuerySave) { var qef = tagVSQueryEditFlags.QEF_AllowInMemoryEdits; if (suppressUI) { qef |= tagVSQueryEditFlags.QEF_SilentMode; } // If we are debugging, we want to prevent our project from being reloaded. To // do this, we pass the QEF_NoReload flag if (!Utilities.IsVisualStudioInDesignMode(this.Site)) { qef |= tagVSQueryEditFlags.QEF_NoReload; } var flags = new uint[files.Length]; var attributes = new VSQEQS_FILE_ATTRIBUTE_DATA[files.Length]; var hr = queryEditQuerySave.QueryEditFiles( (uint)qef, files.Length, // 1 file files, // array of files flags, // no per file flags attributes, // no per file file attributes out var verdict, out _ // ignore additional results ); var qer = (tagVSQueryEditResult)verdict; if (ErrorHandler.Failed(hr) || (qer != tagVSQueryEditResult.QER_EditOK)) { if (!suppressUI && !Utilities.IsInAutomationFunction(this.Site)) { var message = files.Length == 1 ? SR.GetString(SR.CancelQueryEdit, files[0]) : SR.GetString(SR.CancelQueryEditMultiple); var title = string.Empty; var icon = OLEMSGICON.OLEMSGICON_CRITICAL; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); } result = false; } } } return result; } /// <summary> /// Verify if the file can be written to. /// Return false if the file is read only and/or not checked out /// and the user did not give permission to change it. /// Note that exact behavior can also be affected based on the SCC /// settings under Tools->Options. /// </summary> internal bool QueryEditProjectFile(bool suppressUI) { return QueryEditFiles(suppressUI, this.filename, this.UserProjectFilename); } internal bool QueryFolderAdd(HierarchyNode targetFolder, string path) { if (!this.disableQueryEdit) { if (this.GetService(typeof(SVsTrackProjectDocuments)) is IVsTrackProjectDocuments2 queryTrack) { var res = new VSQUERYADDDIRECTORYRESULTS[1]; ErrorHandler.ThrowOnFailure( queryTrack.OnQueryAddDirectories( GetOuterInterface<IVsProject>(), 1, new[] { CommonUtils.GetAbsoluteFilePath(GetBaseDirectoryForAddingFiles(targetFolder), Path.GetFileName(path)) }, new[] { VSQUERYADDDIRECTORYFLAGS.VSQUERYADDDIRECTORYFLAGS_padding }, res, res ) ); if (res[0] == VSQUERYADDDIRECTORYRESULTS.VSQUERYADDDIRECTORYRESULTS_AddNotOK) { return false; } } } return true; } internal bool QueryFolderRemove(HierarchyNode targetFolder, string path) { if (!this.disableQueryEdit) { if (this.GetService(typeof(SVsTrackProjectDocuments)) is IVsTrackProjectDocuments2 queryTrack) { var res = new VSQUERYREMOVEDIRECTORYRESULTS[1]; ErrorHandler.ThrowOnFailure( queryTrack.OnQueryRemoveDirectories( GetOuterInterface<IVsProject>(), 1, new[] { CommonUtils.GetAbsoluteFilePath(GetBaseDirectoryForAddingFiles(targetFolder), Path.GetFileName(path)) }, new[] { VSQUERYREMOVEDIRECTORYFLAGS.VSQUERYREMOVEDIRECTORYFLAGS_padding }, res, res ) ); if (res[0] == VSQUERYREMOVEDIRECTORYRESULTS.VSQUERYREMOVEDIRECTORYRESULTS_RemoveNotOK) { return false; } } } return true; } /// <summary> /// Given a node determines what is the directory that can accept files. /// If the node is a FoldeNode than it is the Url of the Folder. /// If the node is a ProjectNode it is the project folder. /// Otherwise (such as FileNode subitem) it delegate the resolution to the parent node. /// </summary> internal string GetBaseDirectoryForAddingFiles(HierarchyNode nodeToAddFile) { var baseDir = string.Empty; if (nodeToAddFile is FolderNode) { baseDir = nodeToAddFile.Url; } else if (nodeToAddFile is ProjectNode) { baseDir = this.ProjectHome; } else if (nodeToAddFile != null) { baseDir = GetBaseDirectoryForAddingFiles(nodeToAddFile.Parent); } return baseDir; } /// <summary> /// For internal use only. /// This creates a copy of an existing configuration and add it to the project. /// Caller should change the condition on the PropertyGroup. /// If derived class want to accomplish this, they should call ConfigProvider.AddCfgsOfCfgName() /// It is expected that in the future MSBuild will have support for this so we don't have to /// do it manually. /// </summary> /// <param name="group">PropertyGroup to clone</param> /// <returns></returns> internal MSBuildConstruction.ProjectPropertyGroupElement ClonePropertyGroup(MSBuildConstruction.ProjectPropertyGroupElement group) { // Create a new (empty) PropertyGroup var newPropertyGroup = this.buildProject.Xml.AddPropertyGroup(); // Now copy everything from the group we are trying to clone to the group we are creating if (!string.IsNullOrEmpty(group.Condition)) { newPropertyGroup.Condition = group.Condition; } foreach (var prop in group.Properties) { var newProperty = newPropertyGroup.AddProperty(prop.Name, prop.Value); if (!string.IsNullOrEmpty(prop.Condition)) { newProperty.Condition = prop.Condition; } } return newPropertyGroup; } /// <summary> /// Get the project extensions /// </summary> /// <returns></returns> internal MSBuildConstruction.ProjectExtensionsElement GetProjectExtensions() { var extensionsElement = this.buildProject.Xml.ChildrenReversed.OfType<MSBuildConstruction.ProjectExtensionsElement>().FirstOrDefault(); if (extensionsElement == null) { extensionsElement = this.buildProject.Xml.CreateProjectExtensionsElement(); this.buildProject.Xml.AppendChild(extensionsElement); } return extensionsElement; } /// <summary> /// Set the xmlText as a project extension element with the id passed. /// </summary> /// <param name="id">The id of the project extension element.</param> /// <param name="xmlText">The value to set for a project extension.</param> internal void SetProjectExtensions(string id, string xmlText) { var element = this.GetProjectExtensions(); // If it doesn't already have a value and we're asked to set it to // nothing, don't do anything. Same as old OM. Keeps project neat. if (element == null) { if (xmlText.Length == 0) { return; } element = this.buildProject.Xml.CreateProjectExtensionsElement(); this.buildProject.Xml.AppendChild(element); } element[id] = xmlText; } /// <summary> /// Register the project with the Scc manager. /// </summary> protected void RegisterSccProject() { if (this.isRegisteredWithScc || string.IsNullOrEmpty(this.sccProjectName)) { return; } if (this.Site.GetService(typeof(SVsSccManager)) is IVsSccManager2 sccManager) { ErrorHandler.ThrowOnFailure(sccManager.RegisterSccProject(this, this.sccProjectName, this.sccAuxPath, this.sccLocalPath, this.sccProvider)); this.isRegisteredWithScc = true; } } /// <summary> /// Unregisters us from the SCC manager /// </summary> protected void UnRegisterProject() { if (!this.isRegisteredWithScc) { return; } if (this.Site.GetService(typeof(SVsSccManager)) is IVsSccManager2 sccManager) { ErrorHandler.ThrowOnFailure(sccManager.UnregisterSccProject(this)); this.isRegisteredWithScc = false; } } /// <summary> /// Get the CATID corresponding to the specified type. /// </summary> /// <param name="type">Type of the object for which you want the CATID</param> /// <returns>CATID</returns> protected internal Guid GetCATIDForType(Type type) { Utilities.ArgumentNotNull(nameof(type), type); if (this.catidMapping == null) { this.catidMapping = new Dictionary<Type, Guid>(); InitializeCATIDs(); } if (this.catidMapping.TryGetValue(type, out var result)) { return result; } // If you get here and you want your object to be extensible, then add a call to AddCATIDMapping() in your project constructor return Guid.Empty; } /// <summary> /// This is used to specify a CATID corresponding to a BrowseObject or an ExtObject. /// The CATID can be any GUID you choose. For types which are your owns, you could use /// their type GUID, while for other types (such as those provided in the MPF) you should /// provide a different GUID. /// </summary> /// <param name="type">Type of the extensible object</param> /// <param name="catid">GUID that extender can use to uniquely identify your object type</param> protected void AddCATIDMapping(Type type, Guid catid) { if (this.catidMapping == null) { this.catidMapping = new Dictionary<Type, Guid>(); InitializeCATIDs(); } this.catidMapping.Add(type, catid); } /// <summary> /// Initialize an object with an XML fragment. /// </summary> /// <param name="iPersistXMLFragment">Object that support being initialized with an XML fragment</param> /// <param name="configName">Name of the configuration being initialized, null if it is the project</param> /// <param name="platformName">Name of the platform being initialized, null is ok</param> protected internal void LoadXmlFragment(IPersistXMLFragment persistXmlFragment, string configName, string platformName) { Utilities.ArgumentNotNull(nameof(persistXmlFragment), persistXmlFragment); if (this.xmlFragments == null) { // Retrieve the xml fragments from MSBuild this.xmlFragments = new XmlDocument(); var fragments = GetProjectExtensions()[ProjectFileConstants.VisualStudio]; fragments = string.Format(CultureInfo.InvariantCulture, "<root>{0}</root>", fragments); this.xmlFragments.LoadXml(fragments); } // We need to loop through all the flavors ErrorHandler.ThrowOnFailure(((IVsAggregatableProject)this).GetAggregateProjectTypeGuids(out var flavorsGuid)); foreach (var flavor in Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(flavorsGuid)) { // Look for a matching fragment var flavorGuidString = flavor.ToString("B"); string fragment = null; XmlNode node = null; foreach (XmlNode child in this.xmlFragments.FirstChild.ChildNodes) { if (child.Attributes.Count > 0) { var guid = string.Empty; var configuration = string.Empty; var platform = string.Empty; if (child.Attributes[ProjectFileConstants.Guid] != null) { guid = child.Attributes[ProjectFileConstants.Guid].Value; } if (child.Attributes[ProjectFileConstants.Configuration] != null) { configuration = child.Attributes[ProjectFileConstants.Configuration].Value; } if (child.Attributes[ProjectFileConstants.Platform] != null) { platform = child.Attributes[ProjectFileConstants.Platform].Value; } if (StringComparer.OrdinalIgnoreCase.Equals(child.Name, ProjectFileConstants.FlavorProperties) && StringComparer.OrdinalIgnoreCase.Equals(guid, flavorGuidString) && ((string.IsNullOrEmpty(configName) && string.IsNullOrEmpty(configuration)) || (StringComparer.OrdinalIgnoreCase.Equals(configuration, configName))) && ((string.IsNullOrEmpty(platformName) && string.IsNullOrEmpty(platform)) || (StringComparer.OrdinalIgnoreCase.Equals(platform, platformName)))) { // we found the matching fragment fragment = child.InnerXml; node = child; break; } } } var flavorGuid = flavor; if (string.IsNullOrEmpty(fragment)) { // the fragment was not found so init with default values ErrorHandler.ThrowOnFailure(persistXmlFragment.InitNew(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE)); // While we don't yet support user files, our flavors might, so we will store that in the project file until then // TODO: Refactor this code when we support user files ErrorHandler.ThrowOnFailure(persistXmlFragment.InitNew(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE)); } else { ErrorHandler.ThrowOnFailure(persistXmlFragment.Load(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE, fragment)); // While we don't yet support user files, our flavors might, so we will store that in the project file until then // TODO: Refactor this code when we support user files if (node.NextSibling != null && node.NextSibling.Attributes[ProjectFileConstants.User] != null) { ErrorHandler.ThrowOnFailure(persistXmlFragment.Load(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE, node.NextSibling.InnerXml)); } } } } /// <summary> /// Retrieve all XML fragments that need to be saved from the flavors and store the information in msbuild. /// </summary> protected void PersistXMLFragments() { if (IsFlavorDirty()) { var doc = new XmlDocument(); var root = doc.CreateElement("ROOT"); // We will need the list of configuration inside the loop, so get it before entering the loop var count = new uint[1]; IVsCfg[] configs = null; var hr = this.ConfigProvider.GetCfgs(0, null, count, null); if (ErrorHandler.Succeeded(hr) && count[0] > 0) { configs = new IVsCfg[count[0]]; hr = this.ConfigProvider.GetCfgs((uint)configs.Length, configs, count, null); if (ErrorHandler.Failed(hr)) { count[0] = 0; } } if (count[0] == 0) { configs = new IVsCfg[0]; } // We need to loop through all the flavors ErrorHandler.ThrowOnFailure(((IVsAggregatableProject)this).GetAggregateProjectTypeGuids(out var flavorsGuid)); foreach (var flavor in Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(flavorsGuid)) { var outerHierarchy = GetOuterInterface<IPersistXMLFragment>(); // First check the project if (outerHierarchy != null) { // Retrieve the XML fragment var fragment = string.Empty; var flavorGuid = flavor; ErrorHandler.ThrowOnFailure((outerHierarchy).Save(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE, out fragment, 1)); if (!string.IsNullOrEmpty(fragment)) { // Add the fragment to our XML WrapXmlFragment(doc, root, flavor, null, null, fragment); } // While we don't yet support user files, our flavors might, so we will store that in the project file until then // TODO: Refactor this code when we support user files fragment = string.Empty; ErrorHandler.ThrowOnFailure((outerHierarchy).Save(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE, out fragment, 1)); if (!string.IsNullOrEmpty(fragment)) { // Add the fragment to our XML var node = WrapXmlFragment(doc, root, flavor, null, null, fragment); node.Attributes.Append(doc.CreateAttribute(ProjectFileConstants.User)); } } // Then look at the configurations foreach (var config in configs) { // Get the fragment for this flavor/config pair ErrorHandler.ThrowOnFailure(((ProjectConfig)config).GetXmlFragment(flavor, _PersistStorageType.PST_PROJECT_FILE, out var fragment)); if (!string.IsNullOrEmpty(fragment)) { WrapXmlFragment(doc, root, flavor, ((ProjectConfig)config).ConfigName, ((ProjectConfig)config).PlatformName, fragment); } } } if (root.ChildNodes != null && root.ChildNodes.Count > 0) { // Save our XML (this is only the non-build information for each flavor) in msbuild SetProjectExtensions(ProjectFileConstants.VisualStudio, root.InnerXml.ToString()); } } } [Obsolete("Use ImageMonikers instead")] internal int GetIconIndex(ImageName name) { return (int)name; } [Obsolete("Use ImageMonikers instead")] internal IntPtr GetIconHandleByName(ImageName name) { return this.ImageHandler.GetIconHandle(GetIconIndex(name)); } internal Dictionary<string, string> ParseCommandArgs(IntPtr vaIn, Guid cmdGroup, uint cmdId) { var switches = QueryCommandArguments(cmdGroup, cmdId, CommandOrigin.UiHierarchy); if (string.IsNullOrEmpty(switches)) { return null; } return ParseCommandArgs(vaIn, switches); } internal Dictionary<string, string> ParseCommandArgs(IntPtr vaIn, string switches) { string args; if (vaIn == IntPtr.Zero || string.IsNullOrEmpty(args = Marshal.GetObjectForNativeVariant(vaIn) as string)) { return null; } var parse = this.Site.GetService(typeof(SVsParseCommandLine)) as IVsParseCommandLine; if (ErrorHandler.Failed(parse.ParseCommandTail(args, -1))) { return null; } parse.EvaluateSwitches(switches); var res = new Dictionary<string, string>(); var i = -1; foreach (var sw in switches.Split(' ')) { i += 1; var key = sw; var comma = key.IndexOf(','); if (comma > 0) { key = key.Remove(comma); } int hr; switch (hr = parse.IsSwitchPresent(i)) { case VSConstants.S_OK: ErrorHandler.ThrowOnFailure(parse.GetSwitchValue(i, out var value)); res[key] = value; break; case VSConstants.S_FALSE: break; default: ErrorHandler.ThrowOnFailure(hr); break; } } i = 0; ErrorHandler.ThrowOnFailure(parse.GetParamCount(out var count)); for (i = 0; i < count; ++i) { string key = i.ToString(); ErrorHandler.ThrowOnFailure(parse.GetParam(i, out var value)); res[key] = value; } return res; } #endregion #region IVsGetCfgProvider Members //================================================================================= public virtual int GetCfgProvider(out IVsCfgProvider p) { // Be sure to call the property here since that is doing a polymorhic ProjectConfig creation. p = this.ConfigProvider; return (p == null ? VSConstants.E_NOTIMPL : VSConstants.S_OK); } #endregion #region IPersist Members public int GetClassID(out Guid clsid) { clsid = this.ProjectGuid; return VSConstants.S_OK; } #endregion #region IPersistFileFormat Members int IPersistFileFormat.GetClassID(out Guid clsid) { clsid = this.ProjectGuid; return VSConstants.S_OK; } public virtual int GetCurFile(out string name, out uint formatIndex) { name = this.filename; formatIndex = 0; return VSConstants.S_OK; } public virtual int GetFormatList(out string formatlist) { formatlist = string.Empty; return VSConstants.S_OK; } public virtual int InitNew(uint formatIndex) { return VSConstants.S_OK; } public virtual int IsDirty(out int isDirty) { if (this.BuildProject.Xml.HasUnsavedChanges || this.IsProjectFileDirty || IsFlavorDirty()) { isDirty = 1; } else { isDirty = 0; } return VSConstants.S_OK; } /// <summary> /// Get the outer IVsHierarchy implementation. /// This is used for scenario where a flavor may be modifying the behavior /// </summary> internal IVsHierarchy GetOuterHierarchy() { IVsHierarchy hierarchy = null; // The hierarchy of a node is its project node hierarchy var projectUnknown = Marshal.GetIUnknownForObject(this); try { hierarchy = (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsHierarchy)); } finally { if (projectUnknown != IntPtr.Zero) { Marshal.Release(projectUnknown); } } return hierarchy; } internal T GetOuterInterface<T>() where T : class { return GetOuterHierarchy() as T; } private bool IsFlavorDirty() { var isDirty = 0; // See if one of our flavor consider us dirty var outerHierarchy = GetOuterInterface<IPersistXMLFragment>(); if (outerHierarchy != null) { // First check the project ErrorHandler.ThrowOnFailure(outerHierarchy.IsFragmentDirty((uint)_PersistStorageType.PST_PROJECT_FILE, out isDirty)); // While we don't yet support user files, our flavors might, so we will store that in the project file until then // TODO: Refactor this code when we support user files if (isDirty == 0) { ErrorHandler.ThrowOnFailure(outerHierarchy.IsFragmentDirty((uint)_PersistStorageType.PST_USER_FILE, out isDirty)); } } if (isDirty == 0) { // Then look at the configurations var count = new uint[1]; var hr = this.ConfigProvider.GetCfgs(0, null, count, null); if (ErrorHandler.Succeeded(hr) && count[0] > 0) { // We need to loop through the configurations var configs = new IVsCfg[count[0]]; hr = this.ConfigProvider.GetCfgs((uint)configs.Length, configs, count, null); Debug.Assert(ErrorHandler.Succeeded(hr), "failed to retrieve configurations"); foreach (var config in configs) { isDirty = ((ProjectConfig)config).IsFlavorDirty(_PersistStorageType.PST_PROJECT_FILE); if (isDirty != 0) { break; } } } } return isDirty != 0; } int IPersistFileFormat.Load(string fileName, uint mode, int readOnly) { // This isn't how projects are loaded, C#, VB, and CPS all fail this call return VSConstants.E_NOTIMPL; } public virtual int Save(string fileToBeSaved, int remember, uint formatIndex) { // The file name can be null. Then try to use the Url. var tempFileToBeSaved = fileToBeSaved; if (string.IsNullOrEmpty(tempFileToBeSaved) && !string.IsNullOrEmpty(this.Url)) { tempFileToBeSaved = this.Url; } if (string.IsNullOrEmpty(tempFileToBeSaved)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(fileToBeSaved)); } var setProjectFileDirtyAfterSave = 0; if (remember == 0) { ErrorHandler.ThrowOnFailure(IsDirty(out setProjectFileDirtyAfterSave)); } // Update the project with the latest flavor data (if needed) PersistXMLFragments(); var result = VSConstants.S_OK; var saveAs = true; if (CommonUtils.IsSamePath(tempFileToBeSaved, this.filename)) { saveAs = false; } if (!saveAs) { var fileChanges = new SuspendFileChanges(this.Site, this.filename); fileChanges.Suspend(); try { // Ensure the directory exist var saveFolder = Path.GetDirectoryName(tempFileToBeSaved); if (!Directory.Exists(saveFolder)) { Directory.CreateDirectory(saveFolder); } // Save the project SaveMSBuildProjectFile(tempFileToBeSaved); } finally { fileChanges.Resume(); } } else { result = this.SaveAs(tempFileToBeSaved); if (result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } } if (setProjectFileDirtyAfterSave != 0) { this.isDirty = true; } return result; } protected virtual void SaveMSBuildProjectFile(string filename) { this.buildProject.Save(filename); this.isDirty = false; } public virtual int SaveCompleted(string filename) { // TODO: turn file watcher back on. return VSConstants.S_OK; } #endregion #region IVsProject3 Members /// <summary> /// Callback from the additem dialog. Deals with adding new and existing items /// </summary> public virtual int GetMkDocument(uint itemId, out string mkDoc) { mkDoc = null; if (itemId == VSConstants.VSITEMID_SELECTION) { return VSConstants.E_UNEXPECTED; } var n = this.NodeFromItemId(itemId); if (n == null) { return VSConstants.E_INVALIDARG; } mkDoc = n.GetMkDocument(); if (string.IsNullOrEmpty(mkDoc)) { return VSConstants.E_FAIL; } return VSConstants.S_OK; } public virtual int AddItem(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, VSADDRESULT[] result) { var empty = Guid.Empty; return AddItemWithSpecific( itemIdLoc, op, itemName, filesToOpen, files, dlgOwner, op == VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE ? (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen : 0, ref empty, null, ref empty, result); } /// <summary> /// Creates new items in a project, adds existing files to a project, or causes Add Item wizards to be run /// </summary> /// <param name="itemIdLoc"></param> /// <param name="op"></param> /// <param name="itemName"></param> /// <param name="filesToOpen"></param> /// <param name="files">Array of file names. /// If dwAddItemOperation is VSADDITEMOP_CLONEFILE the first item in the array is the name of the file to clone. /// If dwAddItemOperation is VSADDITEMOP_OPENDIRECTORY, the first item in the array is the directory to open. /// If dwAddItemOperation is VSADDITEMOP_RUNWIZARD, the first item is the name of the wizard to run, /// and the second item is the file name the user supplied (same as itemName).</param> /// <param name="dlgOwner"></param> /// <param name="editorFlags"></param> /// <param name="editorType"></param> /// <param name="physicalView"></param> /// <param name="logicalView"></param> /// <param name="result"></param> /// <returns>S_OK if it succeeds </returns> /// <remarks>The result array is initalized to failure.</remarks> public virtual int AddItemWithSpecific(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, VSADDRESULT[] result) { return AddItemWithSpecificInternal(itemIdLoc, op, itemName, filesToOpen, files, dlgOwner, editorFlags, ref editorType, physicalView, ref logicalView, result); } // TODO: Refactor me into something sane internal int AddItemWithSpecificInternal(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, VSADDRESULT[] result, bool? promptOverwrite = null) { if (files == null || result == null || files.Length == 0 || result.Length == 0) { return VSConstants.E_INVALIDARG; } // Locate the node to be the container node for the file(s) being added // only projectnode or foldernode and file nodes are valid container nodes // We need to locate the parent since the item wizard expects the parent to be passed. var n = this.NodeFromItemId(itemIdLoc); if (n == null) { return VSConstants.E_INVALIDARG; } while (!n.CanAddFiles && (!this.CanFileNodesHaveChilds || !(n is FileNode))) { n = n.Parent; } Debug.Assert(n != null, "We should at this point have either a ProjectNode or FolderNode or a FileNode as a container for the new filenodes"); // handle link and runwizard operations at this point var isLink = false; switch (op) { case VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE: // we do not support this right now isLink = true; break; case VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD: result[0] = this.RunWizard(n, itemName, files[0], dlgOwner); return VSConstants.S_OK; } var actualFiles = new string[files.Length]; var flags = this.GetQueryAddFileFlags(files); var baseDir = this.GetBaseDirectoryForAddingFiles(n); // If we did not get a directory for node that is the parent of the item then fail. if (string.IsNullOrEmpty(baseDir)) { return VSConstants.E_FAIL; } // Pre-calculates some paths that we can use when calling CanAddItems var filesToAdd = new List<string>(); foreach (var file in files) { string fileName; var newFileName = string.Empty; switch (op) { case VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE: fileName = Path.GetFileName(itemName ?? file); newFileName = CommonUtils.GetAbsoluteFilePath(baseDir, fileName); break; case VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE: case VSADDITEMOPERATION.VSADDITEMOP_OPENFILE: fileName = Path.GetFileName(file); newFileName = CommonUtils.GetAbsoluteFilePath(baseDir, fileName); if (isLink && CommonUtils.IsSubpathOf(this.ProjectHome, file)) { // creating a link to a file that's actually in the project, it's not really a link. isLink = false; // If the file is not going to be added in its // current path (GetDirectoryName(file) != baseDir), // we need to update the filename and also update // the destination node (n). Otherwise, we don't // want to change the destination node (previous // behavior) - just trust that our caller knows // what they are doing. (Web Essentials relies on // this.) if (!CommonUtils.IsSameDirectory(baseDir, Path.GetDirectoryName(file))) { newFileName = file; n = this.CreateFolderNodes(Path.GetDirectoryName(file)); } } break; } filesToAdd.Add(newFileName); } // Ask tracker objects if we can add files if (!this.tracker.CanAddItems(filesToAdd.ToArray(), flags)) { // We were not allowed to add the files return VSConstants.E_FAIL; } if (!this.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } // Add the files to the hierarchy var actualFilesAddedIndex = 0; var itemsToInvalidate = new List<HierarchyNode>(); for (var index = 0; index < filesToAdd.Count; index++) { HierarchyNode child; var overwrite = false; MsBuildProjectElement linkedFile = null; var newFileName = filesToAdd[index]; var file = files[index]; result[0] = VSADDRESULT.ADDRESULT_Failure; child = this.FindNodeByFullPath(newFileName); if (child != null) { // If the file to be added is an existing file part of the hierarchy then continue. if (CommonUtils.IsSamePath(file, newFileName)) { if (child.IsNonMemberItem) { for (var node = child; node != null; node = node.Parent) { itemsToInvalidate.Add(node); // We want to include the first member item, so // this test is not part of the loop condition. if (!node.IsNonMemberItem) { break; } } // https://pytools.codeplex.com/workitem/1251 ErrorHandler.ThrowOnFailure(child.IncludeInProject(false)); } result[0] = VSADDRESULT.ADDRESULT_Cancel; continue; } else if (isLink) { var message = "There is already a file of the same name in this folder."; var title = string.Empty; var icon = OLEMSGICON.OLEMSGICON_QUERY; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } else { var canOverWriteExistingItem = CanOverwriteExistingItem(file, newFileName, !child.IsNonMemberItem); if (canOverWriteExistingItem == E_CANCEL_FILE_ADD) { result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } else if (canOverWriteExistingItem == (int)OleConstants.OLECMDERR_E_CANCELED) { result[0] = VSADDRESULT.ADDRESULT_Cancel; return canOverWriteExistingItem; } else if (canOverWriteExistingItem == VSConstants.S_OK) { overwrite = true; } else { return canOverWriteExistingItem; } } } else { if (isLink) { child = this.FindNodeByFullPath(file); if (child != null) { var message = string.Format("There is already a link to '{0}'. A project cannot have more than one link to the same file.", file); var title = string.Empty; var icon = OLEMSGICON.OLEMSGICON_QUERY; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } } if (newFileName.Length >= NativeMethods.MAX_PATH) { var icon = OLEMSGICON.OLEMSGICON_CRITICAL; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.Site, FolderNode.PathTooLongMessage, null, icon, buttons, defaultButton); result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } // we need to figure out where this file would be added and make sure there's // not an existing link node at the same location var filename = Path.GetFileName(newFileName); var folder = this.FindNodeByFullPath(Path.GetDirectoryName(newFileName)); if (folder != null) { if (folder.FindImmediateChildByName(filename) != null) { var message = "There is already a file of the same name in this folder."; var title = string.Empty; var icon = OLEMSGICON.OLEMSGICON_QUERY; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } } } // If the file to be added is not in the same path copy it. if (!CommonUtils.IsSamePath(file, newFileName) || Directory.Exists(newFileName)) { if (!overwrite && File.Exists(newFileName)) { var existingChild = this.FindNodeByFullPath(file); if (existingChild == null || !existingChild.IsLinkFile) { var message = SR.GetString(SR.FileAlreadyExists, newFileName); var title = string.Empty; var icon = OLEMSGICON.OLEMSGICON_QUERY; var buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNO; var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; if (isLink) { message = "There is already a file of the same name in this folder."; buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; } var messageboxResult = VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton); if (messageboxResult != NativeMethods.IDYES) { result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; } } } var updatingNode = this.FindNodeByFullPath(file); if (updatingNode != null && updatingNode.IsLinkFile) { // we just need to update the link to the new path. linkedFile = updatingNode.ItemNode as MsBuildProjectElement; } else if (Directory.Exists(file)) { // http://pytools.codeplex.com/workitem/546 var hr = AddDirectory(result, n, file, promptOverwrite); if (ErrorHandler.Failed(hr)) { return hr; } result[0] = VSADDRESULT.ADDRESULT_Success; continue; } else if (!isLink) { // Copy the file to the correct location. // We will suppress the file change events to be triggered to this item, since we are going to copy over the existing file and thus we will trigger a file change event. // We do not want the filechange event to ocur in this case, similar that we do not want a file change event to occur when saving a file. var fileChange = this.site.GetService(typeof(SVsFileChangeEx)) as IVsFileChangeEx; Utilities.CheckNotNull(fileChange); try { ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(VSConstants.VSCOOKIE_NIL, newFileName, 1)); if (op == VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE) { this.AddFileFromTemplate(file, newFileName); } else { PackageUtilities.CopyUrlToLocal(new Uri(file), newFileName); // Reset RO attribute on file if present - for example, if source file was under TFS control and not checked out. try { var fileInfo = new FileInfo(newFileName); if (fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly)) { fileInfo.Attributes &= ~FileAttributes.ReadOnly; } } catch (Exception ex) when (!ExceptionExtensions.IsCriticalException(ex)) { // Best-effort, but no big deal if this fails. } } } finally { ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(VSConstants.VSCOOKIE_NIL, newFileName, 0)); } } } if (overwrite) { if (child.IsNonMemberItem) { ErrorHandler.ThrowOnFailure(child.IncludeInProject(false)); } } else if (linkedFile != null || isLink) { // files not moving, add the old name, and set the link. var friendlyPath = CommonUtils.GetRelativeFilePath(this.ProjectHome, file); FileNode newChild; if (linkedFile == null) { Debug.Assert(!CommonUtils.IsSubpathOf(this.ProjectHome, file), "Should have cleared isLink above for file in project dir"); newChild = CreateFileNode(file); } else { newChild = CreateFileNode(linkedFile); } newChild.SetIsLinkFile(true); newChild.ItemNode.SetMetadata(ProjectFileConstants.Link, CommonUtils.CreateFriendlyFilePath(this.ProjectHome, newFileName)); n.AddChild(newChild); DocumentManager.RenameDocument(this.site, file, file, n.ID); LinkFileAdded(file); } else { //Add new filenode/dependentfilenode this.AddNewFileNodeToHierarchy(n, newFileName); } result[0] = VSADDRESULT.ADDRESULT_Success; actualFiles[actualFilesAddedIndex++] = newFileName; } // Notify listeners that items were appended. if (actualFilesAddedIndex > 0) { OnItemsAppended(n); } foreach (var node in itemsToInvalidate.Where(node => node != null).Reverse()) { OnInvalidateItems(node); } //Open files if this was requested through the editorFlags var openFiles = (editorFlags & (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen) != 0; if (openFiles && actualFiles.Length <= filesToOpen) { for (var i = 0; i < filesToOpen; i++) { if (!string.IsNullOrEmpty(actualFiles[i])) { var name = actualFiles[i]; var child = this.FindNodeByFullPath(name); Debug.Assert(child != null, "We should have been able to find the new element in the hierarchy"); if (child != null) { IVsWindowFrame frame; if (editorType == Guid.Empty) { var view = child.DefaultOpensWithDesignView ? VSConstants.LOGVIEWID.Designer_guid : Guid.Empty; ErrorHandler.ThrowOnFailure(this.OpenItem(child.ID, ref view, IntPtr.Zero, out frame)); } else { ErrorHandler.ThrowOnFailure(this.OpenItemWithSpecific(child.ID, editorFlags, ref editorType, physicalView, ref logicalView, IntPtr.Zero, out frame)); } // Show the window frame in the UI and make it the active window if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } } } } } return VSConstants.S_OK; } /// <summary> /// Adds a folder into the project recursing and adding any sub-files and sub-directories. /// /// The user can be prompted to overwrite the existing files if the folder already exists /// in the project. They will be initially prompted to overwrite - if they answer no /// we'll set promptOverwrite to false and when we recurse we won't prompt. If they say /// yes then we'll set it to true and we will prompt for individual files. /// </summary> private int AddDirectory(VSADDRESULT[] result, HierarchyNode n, string file, bool? promptOverwrite) { // need to recursively add all of the directory contents var targetFolder = n.FindImmediateChildByName(Path.GetFileName(file)); if (targetFolder == null) { var fullPath = Path.Combine(GetBaseDirectoryForAddingFiles(n), Path.GetFileName(file)); Directory.CreateDirectory(fullPath); var newChild = CreateFolderNode(fullPath); n.AddChild(newChild); targetFolder = newChild; } else if (targetFolder.IsNonMemberItem) { var hr = targetFolder.IncludeInProject(true); if (ErrorHandler.Succeeded(hr)) { OnInvalidateItems(targetFolder.Parent); } return hr; } else if (promptOverwrite == null) { var res = MessageBox.Show( string.Format( @"This folder already contains a folder called '{0}'. If the files in the existing folder have the same names as files in the folder you are copying, do you want to replace the existing files?", Path.GetFileName(file)), "Merge Folders", MessageBoxButtons.YesNoCancel ); // yes means prompt for each file // no means don't prompt for any of the files // cancel means forget what I'm doing switch (res) { case DialogResult.Cancel: result[0] = VSADDRESULT.ADDRESULT_Cancel; return (int)OleConstants.OLECMDERR_E_CANCELED; case DialogResult.No: promptOverwrite = false; break; case DialogResult.Yes: promptOverwrite = true; break; } } var empty = Guid.Empty; // add the files... var dirFiles = Directory.GetFiles(file); if (dirFiles.Length > 0) { var subRes = AddItemWithSpecificInternal( targetFolder.ID, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE, null, (uint)dirFiles.Length, dirFiles, IntPtr.Zero, 0, ref empty, null, ref empty, result, promptOverwrite: promptOverwrite ); if (ErrorHandler.Failed(subRes)) { return subRes; } } // add any subdirectories... var subDirs = Directory.GetDirectories(file); if (subDirs.Length > 0) { return AddItemWithSpecificInternal( targetFolder.ID, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE, null, (uint)subDirs.Length, subDirs, IntPtr.Zero, 0, ref empty, null, ref empty, result, promptOverwrite: promptOverwrite ); } return VSConstants.S_OK; } protected virtual void LinkFileAdded(string filename) { } /// <summary> /// for now used by add folder. Called on the ROOT, as only the project should need /// to implement this. /// for folders, called with parent folder, blank extension and blank suggested root /// </summary> public virtual int GenerateUniqueItemName(uint itemIdLoc, string ext, string suggestedRoot, out string itemName) { var root = string.IsNullOrEmpty(suggestedRoot) ? "NewFolder" : suggestedRoot.Trim(); var extToUse = string.IsNullOrEmpty(ext) ? "" : ext.Trim(); itemName = string.Empty; // Find the folder or project the item is being added to. var parent = NodeFromItemId(itemIdLoc); while (parent != null && !parent.CanAddFiles) { parent = parent.Parent; } if (parent == null) { return VSConstants.E_FAIL; } var destDirectory = parent is ProjectNode parentProject ? parentProject.ProjectHome : parent.Url; for (var count = 1; count < int.MaxValue; ++count) { var candidate = string.Format( CultureInfo.CurrentCulture, "{0}{1}{2}", root, count, extToUse ); var candidatePath = CommonUtils.GetAbsoluteFilePath(destDirectory, candidate); if (File.Exists(candidatePath) || Directory.Exists(candidatePath)) { // Cannot create a file or a directory when one exists with // the same name. continue; } if (parent.AllChildren.Any(n => candidate == n.GetItemName())) { // Cannot create a node if one exists with the same name. continue; } itemName = candidate; return VSConstants.S_OK; } return VSConstants.E_FAIL; } public virtual int GetItemContext(uint itemId, out Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { // the as cast isn't necessary, but makes it obvious via Find all refs how this is being used psp = this.NodeFromItemId(itemId) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; return VSConstants.S_OK; } public virtual int IsDocumentInProject(string mkDoc, out int found, VSDOCUMENTPRIORITY[] pri, out uint itemId) { if (pri != null && pri.Length >= 1) { pri[0] = VSDOCUMENTPRIORITY.DP_Unsupported; } found = 0; itemId = 0; // Debugger will pass in non-normalized paths for remote Linux debugging (produced by concatenating a local Windows-style path // with a portion of the remote Unix-style path) - need to normalize to look it up. mkDoc = CommonUtils.NormalizePath(mkDoc); // If it is the project file just return. if (CommonUtils.IsSamePath(mkDoc, this.GetMkDocument())) { found = 1; itemId = VSConstants.VSITEMID_ROOT; } else { var child = this.FindNodeByFullPath(EnsureRootedPath(mkDoc)); if (child != null && (!child.IsNonMemberItem || IncludeNonMemberItemInProject(child))) { found = 1; itemId = child.ID; } } if (found == 1) { if (pri != null && pri.Length >= 1) { pri[0] = VSDOCUMENTPRIORITY.DP_Standard; } } return VSConstants.S_OK; } protected virtual bool IncludeNonMemberItemInProject(HierarchyNode node) { return false; } public virtual int OpenItem(uint itemId, ref Guid logicalView, IntPtr punkDocDataExisting, out IVsWindowFrame frame) { // Init output params frame = null; var node = this.NodeFromItemId(itemId); if (node == null) { throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), nameof(itemId)); } // Delegate to the document manager object that knows how to open the item var documentManager = node.GetDocumentManager(); if (documentManager != null) { return documentManager.Open(ref logicalView, punkDocDataExisting, out frame, WindowFrameShowAction.DoNotShow); } // This node does not have an associated document manager and we must fail return VSConstants.E_FAIL; } public virtual int OpenItemWithSpecific(uint itemId, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame) { // Init output params frame = null; var node = this.NodeFromItemId(itemId); if (node == null) { throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), nameof(itemId)); } // Delegate to the document manager object that knows how to open the item var documentManager = node.GetDocumentManager(); if (documentManager != null) { return documentManager.OpenWithSpecific(editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, WindowFrameShowAction.DoNotShow); } // This node does not have an associated document manager and we must fail return VSConstants.E_FAIL; } public virtual int RemoveItem(uint reserved, uint itemId, out int result) { var node = this.NodeFromItemId(itemId); if (node == null) { throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), nameof(itemId)); } node.Remove(true); result = 1; return VSConstants.S_OK; } public virtual int ReopenItem(uint itemId, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame) { // Init output params frame = null; var node = this.NodeFromItemId(itemId); if (node == null) { throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), nameof(itemId)); } // Delegate to the document manager object that knows how to open the item var documentManager = node.GetDocumentManager(); if (documentManager != null) { return documentManager.ReOpenWithSpecific(0, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, WindowFrameShowAction.DoNotShow); } // This node does not have an associated document manager and we must fail return VSConstants.E_FAIL; } /// <summary> /// Implements IVsProject3::TransferItem /// This function is called when an open miscellaneous file is being transferred /// to our project. The sequence is for the shell to call AddItemWithSpecific and /// then use TransferItem to transfer the open document to our project. /// </summary> /// <param name="oldMkDoc">Old document name</param> /// <param name="newMkDoc">New document name</param> /// <param name="frame">Optional frame if the document is open</param> /// <returns></returns> public virtual int TransferItem(string oldMkDoc, string newMkDoc, IVsWindowFrame frame) { // Fail if hierarchy already closed if (this.ProjectMgr == null || this.IsClosed) { return VSConstants.E_FAIL; } //Fail if the document names passed are null. if (oldMkDoc == null || newMkDoc == null) { return VSConstants.E_INVALIDARG; } var hr = VSConstants.S_OK; var priority = new VSDOCUMENTPRIORITY[1]; var itemid = VSConstants.VSITEMID_NIL; uint cookie = 0; uint grfFlags = 0; var pRdt = GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRdt == null) { return VSConstants.E_ABORT; } IVsHierarchy pHier; uint id; var docdataForCookiePtr = IntPtr.Zero; var docDataPtr = IntPtr.Zero; var hierPtr = IntPtr.Zero; // We get the document from the running doc table so that we can see if it is transient try { ErrorHandler.ThrowOnFailure(pRdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldMkDoc, out pHier, out id, out docdataForCookiePtr, out cookie)); } finally { if (docdataForCookiePtr != IntPtr.Zero) { Marshal.Release(docdataForCookiePtr); } } //Get the document info try { ErrorHandler.ThrowOnFailure(pRdt.GetDocumentInfo(cookie, out grfFlags, out var readLocks, out var editLocks, out var doc, out pHier, out id, out docDataPtr)); } finally { if (docDataPtr != IntPtr.Zero) { Marshal.Release(docDataPtr); } } // Now see if the document is in the project. If not, we fail try { ErrorHandler.ThrowOnFailure(IsDocumentInProject(newMkDoc, out var found, priority, out itemid)); Debug.Assert(itemid != VSConstants.VSITEMID_NIL && itemid != VSConstants.VSITEMID_ROOT); hierPtr = Marshal.GetComInterfaceForObject(this, typeof(IVsUIHierarchy)); // Now rename the document ErrorHandler.ThrowOnFailure(pRdt.RenameDocument(oldMkDoc, newMkDoc, hierPtr, itemid)); } finally { if (hierPtr != IntPtr.Zero) { Marshal.Release(hierPtr); } } //Change the caption if we are passed a window frame if (frame != null) { var newNode = FindNodeByFullPath(newMkDoc); if (newNode != null) { var caption = newNode.Caption; hr = frame.SetProperty((int)(__VSFPROPID.VSFPROPID_OwnerCaption), caption); } } return hr; } #endregion #region IVsDependencyProvider Members public int EnumDependencies(out IVsEnumDependencies enumDependencies) { enumDependencies = new EnumDependencies(this.buildDependencyList); return VSConstants.S_OK; } public int OpenDependency(string szDependencyCanonicalName, out IVsDependency dependency) { dependency = null; return VSConstants.S_OK; } #endregion #region IVsComponentUser methods /// <summary> /// Add Components to the Project. /// Used by the environment to add components specified by the user in the Component Selector dialog /// to the specified project /// </summary> /// <param name="dwAddCompOperation">The component operation to be performed.</param> /// <param name="cComponents">Number of components to be added</param> /// <param name="rgpcsdComponents">array of component selector data</param> /// <param name="hwndDialog">Handle to the component picker dialog</param> /// <param name="pResult">Result to be returned to the caller</param> public virtual int AddComponent(VSADDCOMPOPERATION dwAddCompOperation, uint cComponents, System.IntPtr[] rgpcsdComponents, System.IntPtr hwndDialog, VSADDCOMPRESULT[] pResult) { this.Site.GetUIThread().MustBeCalledFromUIThread(); if (rgpcsdComponents == null || pResult == null) { return VSConstants.E_FAIL; } //initalize the out parameter pResult[0] = VSADDCOMPRESULT.ADDCOMPRESULT_Success; var references = GetReferenceContainer(); if (null == references) { // This project does not support references or the reference container was not created. // In both cases this operation is not supported. return VSConstants.E_NOTIMPL; } for (var cCount = 0; cCount < cComponents; cCount++) { var ptr = rgpcsdComponents[cCount]; var selectorData = (VSCOMPONENTSELECTORDATA)Marshal.PtrToStructure(ptr, typeof(VSCOMPONENTSELECTORDATA)); if (null == references.AddReferenceFromSelectorData(selectorData)) { //Skip further proccessing since a reference has to be added pResult[0] = VSADDCOMPRESULT.ADDCOMPRESULT_Failure; return VSConstants.S_OK; } } return VSConstants.S_OK; } #endregion #region IVsSccProject2 Members /// <summary> /// This method is called to determine which files should be placed under source control for a given VSITEMID within this hierarchy. /// </summary> /// <param name="itemId">Identifier for the VSITEMID being queried.</param> /// <param name="stringsOut">Pointer to an array of CALPOLESTR strings containing the file names for this item.</param> /// <param name="flagsOut">Pointer to a CADWORD array of flags stored in DWORDs indicating that some of the files have special behaviors.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetSccFiles(uint itemId, CALPOLESTR[] stringsOut, CADWORD[] flagsOut) { if (itemId == VSConstants.VSITEMID_SELECTION) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(itemId)); } else if (itemId == VSConstants.VSITEMID_ROOT) { // Root node. Return our project file path. if (stringsOut != null && stringsOut.Length > 0) { stringsOut[0] = Utilities.CreateCALPOLESTR(new[] { this.filename }); } if (flagsOut != null && flagsOut.Length > 0) { flagsOut[0] = Utilities.CreateCADWORD(new[] { tagVsSccFilesFlags.SFF_NoFlags }); } return VSConstants.S_OK; } // otherwise delegate to either a file or a folder to get the SCC files var n = this.NodeFromItemId(itemId); if (n == null) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(itemId)); } var files = new List<string>(); var flags = new List<tagVsSccFilesFlags>(); n.GetSccFiles(files, flags); if (stringsOut != null && stringsOut.Length > 0) { stringsOut[0] = Utilities.CreateCALPOLESTR(files); } if (flagsOut != null && flagsOut.Length > 0) { flagsOut[0] = Utilities.CreateCADWORD(flags); } return VSConstants.S_OK; } protected internal override void GetSccFiles(IList<string> files, IList<tagVsSccFilesFlags> flags) { for (var n = this.FirstChild; n != null; n = n.NextSibling) { n.GetSccFiles(files, flags); } } protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { for (var n = this.FirstChild; n != null; n = n.NextSibling) { n.GetSccSpecialFiles(sccFile, files, flags); } } /// <summary> /// This method is called to discover special (hidden files) associated with a given VSITEMID within this hierarchy. /// </summary> /// <param name="itemId">Identifier for the VSITEMID being queried.</param> /// <param name="sccFile">One of the files associated with the node</param> /// <param name="stringsOut">Pointer to an array of CALPOLESTR strings containing the file names for this item.</param> /// <param name="flagsOut">Pointer to a CADWORD array of flags stored in DWORDs indicating that some of the files have special behaviors.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> /// <remarks>This method is called to discover any special or hidden files associated with an item in the project hierarchy. It is called when GetSccFiles returns with the SFF_HasSpecialFiles flag set for any of the files associated with the node.</remarks> public virtual int GetSccSpecialFiles(uint itemId, string sccFile, CALPOLESTR[] stringsOut, CADWORD[] flagsOut) { if (itemId == VSConstants.VSITEMID_SELECTION) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(itemId)); } var node = this.NodeFromItemId(itemId); if (node == null) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(itemId)); } var files = new List<string>(); var flags = new List<tagVsSccFilesFlags>(); node.GetSccSpecialFiles(sccFile, files, flags); if (stringsOut != null && stringsOut.Length > 0) { stringsOut[0] = Utilities.CreateCALPOLESTR(files); } if (flagsOut != null && flagsOut.Length > 0) { flagsOut[0] = Utilities.CreateCADWORD(flags); } // we have no special files. return VSConstants.S_OK; } /// <summary> /// This method is called by the source control portion of the environment to inform the project of changes to the source control glyph on various nodes. /// </summary> /// <param name="affectedNodes">Count of changed nodes.</param> /// <param name="itemidAffectedNodes">An array of VSITEMID identifiers of the changed nodes.</param> /// <param name="newGlyphs">An array of VsStateIcon glyphs representing the new state of the corresponding item in rgitemidAffectedNodes.</param> /// <param name="newSccStatus">An array of status flags from SccStatus corresponding to rgitemidAffectedNodes. </param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int SccGlyphChanged(int affectedNodes, uint[] itemidAffectedNodes, VsStateIcon[] newGlyphs, uint[] newSccStatus) { // if all the paramaters are null adn the count is 0, it means scc wants us to updated everything if (affectedNodes == 0 && itemidAffectedNodes == null && newGlyphs == null && newSccStatus == null) { ReDrawNode(this, UIHierarchyElement.SccState); this.UpdateSccStateIcons(); } else if (affectedNodes > 0 && itemidAffectedNodes != null && newGlyphs != null && newSccStatus != null) { for (var i = 0; i < affectedNodes; i++) { var node = this.NodeFromItemId(itemidAffectedNodes[i]); if (node == null) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), nameof(itemidAffectedNodes)); } ReDrawNode(node, UIHierarchyElement.SccState); } } return VSConstants.S_OK; } /// <summary> /// This method is called by the source control portion of the environment when a project is initially added to source control, or to change some of the project's settings. /// </summary> /// <param name="sccProjectName">String, opaque to the project, that identifies the project location on the server. Persist this string in the project file. </param> /// <param name="sccLocalPath">String, opaque to the project, that identifies the path to the server. Persist this string in the project file.</param> /// <param name="sccAuxPath">String, opaque to the project, that identifies the local path to the project. Persist this string in the project file.</param> /// <param name="sccProvider">String, opaque to the project, that identifies the source control package. Persist this string in the project file.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int SetSccLocation(string sccProjectName, string sccAuxPath, string sccLocalPath, string sccProvider) { Utilities.ArgumentNotNull(nameof(sccProjectName), sccProjectName); Utilities.ArgumentNotNull(nameof(sccAuxPath), sccAuxPath); Utilities.ArgumentNotNull(nameof(sccLocalPath), sccLocalPath); Utilities.ArgumentNotNull(nameof(sccProvider), sccProvider); // Save our settings (returns true if something changed) if (!SetSccSettings(sccProjectName, sccLocalPath, sccAuxPath, sccProvider)) { return VSConstants.S_OK; } var unbinding = (sccProjectName.Length == 0 && sccProvider.Length == 0); if (unbinding || QueryEditProjectFile(false)) { this.buildProject.SetProperty(ProjectFileConstants.SccProjectName, sccProjectName); this.buildProject.SetProperty(ProjectFileConstants.SccProvider, sccProvider); this.buildProject.SetProperty(ProjectFileConstants.SccAuxPath, sccAuxPath); this.buildProject.SetProperty(ProjectFileConstants.SccLocalPath, sccLocalPath); } this.isRegisteredWithScc = true; return VSConstants.S_OK; } #endregion #region IVsProjectSpecialFiles Members /// <summary> /// Allows you to query the project for special files and optionally create them. /// </summary> /// <param name="fileId">__PSFFILEID of the file</param> /// <param name="flags">__PSFFLAGS flags for the file</param> /// <param name="itemid">The itemid of the node in the hierarchy</param> /// <param name="fileName">The file name of the special file.</param> /// <returns></returns> public virtual int GetFile(int fileId, uint flags, out uint itemid, out string fileName) { itemid = VSConstants.VSITEMID_NIL; fileName = string.Empty; // We need to return S_OK, otherwise the property page tabs will not be shown. return VSConstants.E_NOTIMPL; } #endregion #region IAggregatedHierarchy Members /// <summary> /// Get the inner object of an aggregated hierarchy /// </summary> /// <returns>A HierarchyNode</returns> public virtual HierarchyNode GetInner() { return this; } #endregion #region IReferenceDataProvider Members /// <summary> /// Returns the reference container node. /// </summary> /// <returns></returns> public IReferenceContainer GetReferenceContainer() { return FindImmediateChild(node => node is IReferenceContainer) as IReferenceContainer; } #endregion #region IBuildDependencyUpdate Members public virtual IVsBuildDependency[] BuildDependencies => this.buildDependencyList.ToArray(); public virtual void AddBuildDependency(IVsBuildDependency dependency) { if (this.isClosed || dependency == null) { return; } if (!this.buildDependencyList.Contains(dependency)) { this.buildDependencyList.Add(dependency); } } public virtual void RemoveBuildDependency(IVsBuildDependency dependency) { if (this.isClosed || dependency == null) { return; } if (this.buildDependencyList.Contains(dependency)) { this.buildDependencyList.Remove(dependency); } } #endregion #region IProjectEventsListener Members public bool IsProjectEventsListener { get; set; } = true; #endregion #region IVsAggregatableProject Members /// <summary> /// Retrieve the list of project GUIDs that are aggregated together to make this project. /// </summary> /// <param name="projectTypeGuids">Semi colon separated list of Guids. Typically, the last GUID would be the GUID of the base project factory</param> /// <returns>HResult</returns> public int GetAggregateProjectTypeGuids(out string projectTypeGuids) { projectTypeGuids = this.GetProjectProperty(ProjectFileConstants.ProjectTypeGuids, false); // In case someone manually removed this from our project file, default to our project without flavors if (string.IsNullOrEmpty(projectTypeGuids)) { projectTypeGuids = this.ProjectGuid.ToString("B"); } return VSConstants.S_OK; } /// <summary> /// This is where the initialization occurs. /// </summary> public virtual int InitializeForOuter(string filename, string location, string name, uint flags, ref Guid iid, out IntPtr projectPointer, out int canceled) { canceled = 0; projectPointer = IntPtr.Zero; // Initialize the project this.Load(filename, location, name, flags, ref iid, out canceled); if (canceled != 1) { // Set ourself as the project var project = Marshal.GetIUnknownForObject(this); try { return Marshal.QueryInterface(project, ref iid, out projectPointer); } finally { Marshal.Release(project); } } return VSConstants.OLE_E_PROMPTSAVECANCELLED; } /// <summary> /// This is called after the project is done initializing the different layer of the aggregations /// </summary> /// <returns>HResult</returns> public virtual int OnAggregationComplete() { return VSConstants.S_OK; } /// <summary> /// Set the list of GUIDs that are aggregated together to create this project. /// </summary> /// <param name="projectTypeGuids">Semi-colon separated list of GUIDs, the last one is usually the project factory of the base project factory</param> /// <returns>HResult</returns> public int SetAggregateProjectTypeGuids(string projectTypeGuids) { this.SetProjectProperty(ProjectFileConstants.ProjectTypeGuids, projectTypeGuids); return VSConstants.S_OK; } /// <summary> /// We are always the inner most part of the aggregation /// and as such we don't support setting an inner project /// </summary> public int SetInnerProject(object innerProject) { return VSConstants.E_NOTIMPL; } #endregion #region IVsProjectFlavorCfgProvider Members int IVsProjectFlavorCfgProvider.CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) { // Our config object is also our IVsProjectFlavorCfg object ppFlavorCfg = pBaseProjectCfg as IVsProjectFlavorCfg; return VSConstants.S_OK; } #endregion #region IVsBuildPropertyStorage Members /// <summary> /// Get the property of an item /// </summary> /// <param name="itemId">ItemID</param> /// <param name="attributeName">Name of the property</param> /// <param name="attributeValue">Value of the property (out parameter)</param> /// <returns>HRESULT</returns> int IVsBuildPropertyStorage.GetItemAttribute(uint itemId, string attributeName, out string attributeValue) { attributeValue = null; var node = NodeFromItemId(itemId); if (node == null) { throw new ArgumentException("Invalid item id", nameof(itemId)); } if (node.ItemNode != null) { attributeValue = node.ItemNode.GetMetadata(attributeName); } else if (node == node.ProjectMgr) { attributeName = node.ProjectMgr.GetProjectProperty(attributeName); } return VSConstants.S_OK; } /// <summary> /// Get the value of the property in the project file /// </summary> /// <param name="propertyName">Name of the property to remove</param> /// <param name="configName">Configuration for which to remove the property</param> /// <param name="storage">Project or user file (_PersistStorageType)</param> /// <param name="propertyValue">Value of the property (out parameter)</param> /// <returns>HRESULT</returns> public virtual int GetPropertyValue(string propertyName, string configName, uint storage, out string propertyValue) { // TODO: when adding support for User files, we need to update this method propertyValue = null; if (string.IsNullOrEmpty(configName)) { propertyValue = this.GetProjectProperty(propertyName, false); } else { int platformStart; if ((platformStart = configName.IndexOf('|')) != -1) { // matches C# project system, GetPropertyValue handles display name, not just config name configName = configName.Substring(0, platformStart); } ErrorHandler.ThrowOnFailure(this.ConfigProvider.GetCfgOfName(configName, string.Empty, out var configurationInterface)); var config = (ProjectConfig)configurationInterface; propertyValue = config.GetConfigurationProperty(propertyName, true); } return VSConstants.S_OK; } /// <summary> /// Delete a property /// In our case this simply mean defining it as null /// </summary> /// <param name="propertyName">Name of the property to remove</param> /// <param name="configName">Configuration for which to remove the property</param> /// <param name="storage">Project or user file (_PersistStorageType)</param> /// <returns>HRESULT</returns> int IVsBuildPropertyStorage.RemoveProperty(string propertyName, string configName, uint storage) { return ((IVsBuildPropertyStorage)this).SetPropertyValue(propertyName, configName, storage, null); } /// <summary> /// Set a property on an item /// </summary> /// <param name="itemId">ItemID</param> /// <param name="attributeName">Name of the property</param> /// <param name="attributeValue">New value for the property</param> /// <returns>HRESULT</returns> int IVsBuildPropertyStorage.SetItemAttribute(uint itemId, string attributeName, string attributeValue) { var node = NodeFromItemId(itemId); if (node == null) { throw new ArgumentException("Invalid item id", nameof(itemId)); } node.ItemNode.SetMetadata(attributeName, attributeValue); return VSConstants.S_OK; } /// <summary> /// Set a project property /// </summary> /// <param name="propertyName">Name of the property to set</param> /// <param name="configName">Configuration for which to set the property</param> /// <param name="storage">Project file or user file (_PersistStorageType)</param> /// <param name="propertyValue">New value for that property</param> /// <returns>HRESULT</returns> int IVsBuildPropertyStorage.SetPropertyValue(string propertyName, string configName, uint storage, string propertyValue) { if (string.IsNullOrEmpty(configName)) { if (storage == (uint)_PersistStorageType.PST_PROJECT_FILE) { this.SetProjectProperty(propertyName, propertyValue); } else { this.SetUserProjectProperty(propertyName, propertyValue); } } else { ErrorHandler.ThrowOnFailure(this.ConfigProvider.GetCfgOfName(configName, string.Empty, out var configurationInterface)); var config = (ProjectConfig)configurationInterface; config.SetConfigurationProperty(propertyName, propertyValue); } return VSConstants.S_OK; } #endregion #region private helper methods /// <summary> /// Initialize projectNode /// </summary> private void Initialize() { this.ID = VSConstants.VSITEMID_ROOT; this.tracker = new TrackDocumentsHelper(this); // Ensure the SVsBuildManagerAccessor is initialized, so there is an IVsUpdateSolutionEvents4 for // solution update events (through Microsoft.VisualStudio.CommonIDE.BuildManager.BuildManagerAccessor). // This ensures that the first build after project creation succeeds. this.buildManagerAccessor = (IVsBuildManagerAccessor)this.Site.GetService(typeof(SVsBuildManagerAccessor)); } /// <summary> /// Add an item to the hierarchy based on the item path /// </summary> /// <param name="item">Item to add</param> /// <returns>Added node</returns> private HierarchyNode AddIndependentFileNode(MSBuild.ProjectItem item, HierarchyNode parent) { return AddFileNodeToNode(item, parent); } /// <summary> /// Add a dependent file node to the hierarchy /// </summary> /// <param name="item">msbuild item to add</param> /// <param name="parentNode">Parent Node</param> /// <returns>Added node</returns> private HierarchyNode AddDependentFileNodeToNode(MSBuild.ProjectItem item, HierarchyNode parentNode) { FileNode node = this.CreateDependentFileNode(new MsBuildProjectElement(this, item)); parentNode.AddChild(node); // Make sure to set the HasNameRelation flag on the dependent node if it is related to the parent by name if (!node.HasParentNodeNameRelation && StringComparer.OrdinalIgnoreCase.Equals(node.GetRelationalName(), parentNode.GetRelationalName())) { node.HasParentNodeNameRelation = true; } return node; } /// <summary> /// Add a file node to the hierarchy /// </summary> /// <param name="item">msbuild item to add</param> /// <param name="parentNode">Parent Node</param> /// <returns>Added node</returns> private HierarchyNode AddFileNodeToNode(MSBuild.ProjectItem item, HierarchyNode parentNode) { var node = this.CreateFileNode(new MsBuildProjectElement(this, item)); parentNode.AddChild(node); return node; } /// <summary> /// Get the parent node of an msbuild item /// </summary> /// <param name="item">msbuild item</param> /// <returns>parent node</returns> internal HierarchyNode GetItemParentNode(MSBuild.ProjectItem item) { this.Site.GetUIThread().MustBeCalledFromUIThread(); var link = item.GetMetadataValue(ProjectFileConstants.Link); HierarchyNode currentParent = this; var strPath = item.EvaluatedInclude; if (!string.IsNullOrWhiteSpace(link)) { strPath = Path.GetDirectoryName(link); } else { if (this.DiskNodes.TryGetValue(Path.GetDirectoryName(Path.Combine(this.ProjectHome, strPath)) + "\\", out var parent)) { // fast path, filename is normalized, and the folder already exists return parent; } var absPath = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, strPath); if (CommonUtils.IsSubpathOf(this.ProjectHome, absPath)) { strPath = CommonUtils.GetRelativeDirectoryPath(this.ProjectHome, Path.GetDirectoryName(absPath)); } else { // file lives outside of the project, w/o a link it's just at the top level. return this; } } if (strPath.Length > 0) { // Use the relative to verify the folders... currentParent = this.CreateFolderNodes(strPath); } return currentParent; } private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) { if (this.isDisposed) { throw new ObjectDisposedException(null); } if (resetCache || this.currentConfig == null) { // Get properties from project file and cache it this.SetCurrentConfiguration(); this.currentConfig = this.buildProject.CreateProjectInstance(); } if (this.currentConfig == null) { throw new Exception(SR.GetString(SR.FailedToRetrieveProperties, propertyName)); } // return property asked for return this.currentConfig.GetProperty(propertyName); } /// <summary> /// Updates our scc project settings. /// </summary> /// <param name="sccProjectName">String, opaque to the project, that identifies the project location on the server. Persist this string in the project file. </param> /// <param name="sccLocalPath">String, opaque to the project, that identifies the path to the server. Persist this string in the project file.</param> /// <param name="sccAuxPath">String, opaque to the project, that identifies the local path to the project. Persist this string in the project file.</param> /// <param name="sccProvider">String, opaque to the project, that identifies the source control package. Persist this string in the project file.</param> /// <returns>Returns true if something changed.</returns> private bool SetSccSettings(string sccProjectName, string sccLocalPath, string sccAuxPath, string sccProvider) { var changed = false; Debug.Assert(sccProjectName != null && sccLocalPath != null && sccAuxPath != null && sccProvider != null); if (!StringComparer.OrdinalIgnoreCase.Equals(sccProjectName, this.sccProjectName) || !StringComparer.OrdinalIgnoreCase.Equals(sccLocalPath, this.sccLocalPath) || !StringComparer.OrdinalIgnoreCase.Equals(sccAuxPath, this.sccAuxPath) || !StringComparer.OrdinalIgnoreCase.Equals(sccProvider, this.sccProvider)) { changed = true; this.sccProjectName = sccProjectName; this.sccLocalPath = sccLocalPath; this.sccAuxPath = sccAuxPath; this.sccProvider = sccProvider; } return changed; } /// <summary> /// Sets the scc info from the project file. /// </summary> private void InitSccInfo() { this.sccProjectName = this.GetProjectProperty(ProjectFileConstants.SccProjectName, false); this.sccLocalPath = this.GetProjectProperty(ProjectFileConstants.SccLocalPath, false); this.sccProvider = this.GetProjectProperty(ProjectFileConstants.SccProvider, false); this.sccAuxPath = this.GetProjectProperty(ProjectFileConstants.SccAuxPath, false); } internal void OnAfterProjectOpen() { this.projectOpened = true; } private static XmlElement WrapXmlFragment(XmlDocument document, XmlElement root, Guid flavor, string configuration, string platform, string fragment) { var node = document.CreateElement(ProjectFileConstants.FlavorProperties); var attribute = document.CreateAttribute(ProjectFileConstants.Guid); attribute.Value = flavor.ToString("B"); node.Attributes.Append(attribute); if (!string.IsNullOrEmpty(configuration)) { attribute = document.CreateAttribute(ProjectFileConstants.Configuration); attribute.Value = configuration; node.Attributes.Append(attribute); attribute = document.CreateAttribute(ProjectFileConstants.Platform); attribute.Value = platform; node.Attributes.Append(attribute); } node.InnerXml = fragment; root.AppendChild(node); return node; } /// <summary> /// Sets the project guid from the project file. If no guid is found a new one is created and assigne for the instance project guid. /// </summary> private void SetProjectGuidFromProjectFile() { var projectGuid = this.GetProjectProperty(ProjectFileConstants.ProjectGuid, false); if (string.IsNullOrEmpty(projectGuid)) { this.projectIdGuid = Guid.NewGuid(); } else { var guid = new Guid(projectGuid); if (guid != this.projectIdGuid) { this.projectIdGuid = guid; } } } /// <summary> /// Helper for sharing common code between Build() and BuildAsync() /// </summary> /// <param name="output"></param> /// <returns></returns> private bool BuildPrelude(IVsOutputWindowPane output) { var engineLogOnlyCritical = false; // If there is some output, then we can ask the build engine to log more than // just the critical events. if (null != output) { engineLogOnlyCritical = this.BuildEngine.OnlyLogCriticalEvents; this.BuildEngine.OnlyLogCriticalEvents = false; } this.SetOutputLogger(output); return engineLogOnlyCritical; } /// <summary> /// Recusively parses the tree and closes all nodes. /// </summary> /// <param name="node">The subtree to close.</param> private static void CloseAllNodes(HierarchyNode node) { for (var n = node.FirstChild; n != null; n = n.NextSibling) { if (n.FirstChild != null) { CloseAllNodes(n); } n.Close(); } } /// <summary> /// Set the build project with the new project instance value /// </summary> /// <param name="project">The new build project instance</param> private void SetBuildProject(MSBuild.Project project) { var isNewBuildProject = (this.buildProject != project); this.buildProject = project; if (this.buildProject != null) { SetupProjectGlobalPropertiesThatAllProjectSystemsMustSet(); } if (isNewBuildProject) { NewBuildProject(project); } } /// <summary> /// Called when a new value for <see cref="BuildProject"/> is available. /// </summary> protected virtual void NewBuildProject(MSBuild.Project project) { } /// <summary> /// Setup the global properties for project instance. /// </summary> private void SetupProjectGlobalPropertiesThatAllProjectSystemsMustSet() { string solutionDirectory = null; string solutionFile = null; string userOptionsFile = null; if (this.Site.GetService(typeof(SVsSolution)) is IVsSolution solution) { // We do not want to throw. If we cannot set the solution related constants we set them to empty string. solution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptionsFile); } if (solutionDirectory == null) { solutionDirectory = string.Empty; } if (solutionFile == null) { solutionFile = string.Empty; } var solutionFileName = Path.GetFileName(solutionFile); var solutionName = Path.GetFileNameWithoutExtension(solutionFile); var solutionExtension = Path.GetExtension(solutionFile); this.buildProject.SetGlobalProperty(GlobalProperty.SolutionDir.ToString(), solutionDirectory); this.buildProject.SetGlobalProperty(GlobalProperty.SolutionPath.ToString(), solutionFile); this.buildProject.SetGlobalProperty(GlobalProperty.SolutionFileName.ToString(), solutionFileName); this.buildProject.SetGlobalProperty(GlobalProperty.SolutionName.ToString(), solutionName); this.buildProject.SetGlobalProperty(GlobalProperty.SolutionExt.ToString(), solutionExtension); // Other misc properties this.buildProject.SetGlobalProperty(GlobalProperty.BuildingInsideVisualStudio.ToString(), "true"); this.buildProject.SetGlobalProperty(GlobalProperty.Configuration.ToString(), ProjectConfig.Debug); this.buildProject.SetGlobalProperty(GlobalProperty.Platform.ToString(), ProjectConfig.AnyCPU); // DevEnvDir property object installDirAsObject = null; if (this.Site.GetService(typeof(SVsShell)) is IVsShell shell) { // We do not want to throw. If we cannot set the solution related constants we set them to empty string. shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject); } // Ensure that we have traimnling backslash as this is done for the langproj macros too. var installDir = CommonUtils.NormalizeDirectoryPath((string)installDirAsObject) ?? string.Empty; this.buildProject.SetGlobalProperty(GlobalProperty.DevEnvDir.ToString(), installDir); } /// <summary> /// Attempts to lock in the privilege of running a build in Visual Studio. /// </summary> /// <param name="designTime"><c>false</c> if this build was called for by the Solution Build Manager; <c>true</c> otherwise.</param> /// <returns>A value indicating whether a build may proceed.</returns> /// <remarks> /// This method must be called on the UI thread. /// </remarks> private bool TryBeginBuild(bool designTime) { // Need to claim the UI thread for build under the following conditions: // 1. The build must use a resource that uses the UI thread, such as // - you set HostServices and you have a host object which requires (even indirectly) the UI thread (VB and C# compilers do this for instance.) // or, // 2. The build requires the in-proc node AND waits on the UI thread for the build to complete, such as: // - you use a ProjectInstance to build, or // - you have specified a host object, whether or not it requires the UI thread, or // - you set HostServices and you have specified a node affinity. // - In addition to the above you also call submission.Execute(), or you call submission.ExecuteAsync() and then also submission.WaitHandle.Wait*(). bool requiresUIThread = designTime; // If the SVsBuildManagerAccessor service is absent, we're not running within Visual Studio. if (this.buildManagerAccessor != null) { if (requiresUIThread) { var result = this.buildManagerAccessor.ClaimUIThreadForBuild(); if (result < 0) { // Not allowed to claim the UI thread right now. Try again later. return false; } } if (designTime) { var result = this.buildManagerAccessor.BeginDesignTimeBuild(); if (result < 0) { if (requiresUIThread) { this.buildManagerAccessor.ReleaseUIThreadForBuild(); } // Not allowed to begin a design-time build at this time. Try again later. return false; } } // We obtained all the resources we need. So don't release the UI thread until after the build is finished. } else { var buildParameters = new BuildParameters(this.buildEngine); BuildManager.DefaultBuildManager.BeginBuild(buildParameters); } this.buildInProcess = true; return true; } /// <summary> /// Lets Visual Studio know that we're done with our design-time build so others can use the build manager. /// </summary> /// <param name="submission">The build submission that built, if any.</param> /// <param name="designTime">This must be the same value as the one passed to <see cref="TryBeginBuild"/>.</param> /// <remarks> /// This method must be called on the UI thread. /// </remarks> private void EndBuild(BuildSubmission submission, bool designTime) { Debug.Assert(this.buildInProcess); bool requiresUIThread = designTime; if (this.buildManagerAccessor != null) { // It's very important that we try executing all three end-build steps, even if errors occur partway through. try { if (submission != null) { Marshal.ThrowExceptionForHR(this.buildManagerAccessor.UnregisterLoggers(submission.SubmissionId)); } } catch (Exception ex) when (!ExceptionExtensions.IsCriticalException(ex)) { Trace.TraceError(ex.ToString()); } try { if (designTime) { Marshal.ThrowExceptionForHR(this.buildManagerAccessor.EndDesignTimeBuild()); } } catch (Exception ex) when (!ExceptionExtensions.IsCriticalException(ex)) { Trace.TraceError(ex.ToString()); } try { if (requiresUIThread) { Marshal.ThrowExceptionForHR(this.buildManagerAccessor.ReleaseUIThreadForBuild()); } } catch (Exception ex) when (!ExceptionExtensions.IsCriticalException(ex)) { Trace.TraceError(ex.ToString()); } } else { BuildManager.DefaultBuildManager.EndBuild(); } this.buildInProcess = false; } #endregion #region IProjectEventsCallback Members public virtual void BeforeClose() { } #endregion #region IVsProjectBuildSystem Members public virtual int SetHostObject(string targetName, string taskName, object hostObject) { Debug.Assert(targetName != null && taskName != null && this.buildProject != null && this.buildProject.Targets != null); if (targetName == null || taskName == null || this.buildProject == null || this.buildProject.Targets == null) { return VSConstants.E_INVALIDARG; } this.buildProject.ProjectCollection.HostServices.RegisterHostObject(this.buildProject.FullPath, targetName, taskName, (Microsoft.Build.Framework.ITaskHost)hostObject); return VSConstants.S_OK; } public int BuildTarget(string targetName, out bool success) { success = false; var result = this.Build(targetName); if (result == MSBuildResult.Successful) { success = true; } return VSConstants.S_OK; } public virtual int CancelBatchEdit() { return VSConstants.E_NOTIMPL; } public virtual int EndBatchEdit() { return VSConstants.E_NOTIMPL; } public virtual int StartBatchEdit() { return VSConstants.E_NOTIMPL; } /// <summary> /// Used to determine the kind of build system, in VS 2005 there's only one defined kind: MSBuild /// </summary> /// <param name="kind"></param> /// <returns></returns> public virtual int GetBuildSystemKind(out uint kind) { kind = (uint)_BuildSystemKindFlags2.BSK_MSBUILD_VS10; return VSConstants.S_OK; } #endregion /// <summary> /// Finds a node by it's full path on disk. /// </summary> internal HierarchyNode FindNodeByFullPath(string name) { Debug.Assert(Path.IsPathRooted(name)); this.DiskNodes.TryGetValue(name, out var node); return node; } /// <summary> /// Gets the parent folder if path were added to be added to the hierarchy /// in it's default (non-linked item) location. Returns null if the path /// of parent folders to the item don't exist yet. /// </summary> /// <param name="path">The full path on disk to the item which is being queried about..</param> internal HierarchyNode GetParentFolderForPath(string path) { var parentDir = CommonUtils.GetParent(path); HierarchyNode parent; if (CommonUtils.IsSamePath(parentDir, this.ProjectHome)) { parent = this; } else { parent = FindNodeByFullPath(parentDir); } return parent; } #region IVsUIHierarchy methods public virtual int ExecCommand(uint itemId, ref Guid guidCmdGroup, uint nCmdId, uint nCmdExecOpt, IntPtr pvain, IntPtr p) { return this.InternalExecCommand(guidCmdGroup, nCmdId, nCmdExecOpt, pvain, p, CommandOrigin.UiHierarchy); } public virtual int QueryStatusCommand(uint itemId, ref Guid guidCmdGroup, uint cCmds, OLECMD[] cmds, IntPtr pCmdText) { return this.QueryStatusSelection(guidCmdGroup, cCmds, cmds, pCmdText, CommandOrigin.UiHierarchy); } int IVsUIHierarchy.Close() { return ((IVsHierarchy)this).Close(); } #endregion #region IVsHierarchy methods public virtual int AdviseHierarchyEvents(IVsHierarchyEvents sink, out uint cookie) { cookie = this.hierarchyEventSinks.Add(sink) + 1; return VSConstants.S_OK; } /// <summary> /// Closes the project node. /// </summary> /// <returns>A success or failure value.</returns> int IVsHierarchy.Close() { var hr = VSConstants.S_OK; try { Close(); } catch (COMException e) { hr = e.ErrorCode; } return hr; } /// <summary> /// Sets the service provider from which to access the services. /// </summary> /// <param name="site">An instance to an Microsoft.VisualStudio.OLE.Interop object</param> /// <returns>A success or failure value.</returns> public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) { return VSConstants.S_OK; } public virtual int GetCanonicalName(uint itemId, out string name) { var n = NodeFromItemId(itemId); name = (n != null) ? n.GetCanonicalName() : null; return VSConstants.S_OK; } public virtual int GetGuidProperty(uint itemId, int propid, out Guid guid) { guid = Guid.Empty; var n = NodeFromItemId(itemId); if (n != null) { var hr = n.GetGuidProperty(propid, out guid); var vspropId = (__VSHPROPID)propid; return hr; } if (guid == Guid.Empty) { return VSConstants.DISP_E_MEMBERNOTFOUND; } return VSConstants.S_OK; } public virtual int GetProperty(uint itemId, int propId, out object propVal) { propVal = null; if (itemId != VSConstants.VSITEMID_ROOT && propId == (int)__VSHPROPID.VSHPROPID_IconImgList) { return VSConstants.DISP_E_MEMBERNOTFOUND; } var n = NodeFromItemId(itemId); if (n != null) { propVal = n.GetProperty(propId); } if (propVal == null) { return VSConstants.DISP_E_MEMBERNOTFOUND; } return VSConstants.S_OK; } public virtual int GetNestedHierarchy(uint itemId, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pItemId) { ppHierarchyNested = IntPtr.Zero; pItemId = 0; // If itemid is not a nested hierarchy we must return E_FAIL. return VSConstants.E_FAIL; } public virtual int GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) { site = this.Site.GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider)) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; return VSConstants.S_OK; } /// <summary> /// the canonicalName of an item is it's URL, or better phrased, /// the persistence data we put into @RelPath, which is a relative URL /// to the root project /// returning the itemID from this means scanning the list /// </summary> /// <param name="name"></param> /// <param name="itemId"></param> public virtual int ParseCanonicalName(string name, out uint itemId) { // we always start at the current node and go it's children down, so // if you want to scan the whole tree, better call // the root try { name = EnsureRootedPath(name); var child = FindNodeByFullPath(name); if (child != null) { itemId = child.HierarchyId; return VSConstants.S_OK; } } catch (ArgumentException) { // This is expected when the path contains // invalid characters. This can happen with // 'core' node files like console, debug, etc. } itemId = 0; return VSConstants.E_FAIL; } private string EnsureRootedPath(string name) { if (!Path.IsPathRooted(name)) { name = CommonUtils.GetAbsoluteFilePath( this.ProjectHome, name ); } return name; } public virtual int QueryClose(out int fCanClose) { fCanClose = 1; return VSConstants.S_OK; } public virtual int SetGuidProperty(uint itemId, int propid, ref Guid guid) { var n = NodeFromItemId(itemId); var rc = VSConstants.E_INVALIDARG; if (n != null) { rc = n.SetGuidProperty(propid, ref guid); } return rc; } public virtual int SetProperty(uint itemId, int propid, object value) { var n = NodeFromItemId(itemId); if (n != null) { return n.SetProperty(propid, value); } else { return VSConstants.DISP_E_MEMBERNOTFOUND; } } public virtual int UnadviseHierarchyEvents(uint cookie) { this.hierarchyEventSinks.RemoveAt(cookie - 1); return VSConstants.S_OK; } public int Unused0() { return VSConstants.E_NOTIMPL; } public int Unused1() { return VSConstants.E_NOTIMPL; } public int Unused2() { return VSConstants.E_NOTIMPL; } public int Unused3() { return VSConstants.E_NOTIMPL; } public int Unused4() { return VSConstants.E_NOTIMPL; } #endregion #region Hierarchy change notification internal void OnItemAdded(HierarchyNode parent, HierarchyNode child, HierarchyNode previousVisible = null) { Utilities.ArgumentNotNull(nameof(parent), parent); Utilities.ArgumentNotNull(nameof(child), child); this.Site.GetUIThread().MustBeCalledFromUIThread(); var isDiskNode = false; if (child is IDiskBasedNode diskNode) { this.DiskNodes[diskNode.Url] = child; isDiskNode = true; } NodejsToolsEventSource.Instance.HierarchyEventStart(parent.HierarchyId, parent.GetItemName(), child.HierarchyId, child.GetItemName(), previousVisible?.HierarchyId, previousVisible?.GetItemName(), isDiskNode); if ((this.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) { NodejsToolsEventSource.Instance.HierarchyEventStop("Do not trigger OnItemAdded."); return; } this.ExtensibilityEventsDispatcher.FireItemAdded(child); var prev = previousVisible ?? child.PreviousVisibleSibling; var prevId = (prev != null) ? prev.HierarchyId : VSConstants.VSITEMID_NIL; foreach (IVsHierarchyEvents sink in this.hierarchyEventSinks) { var result = 0; try { result = sink.OnItemAdded(parent.HierarchyId, prevId, child.HierarchyId); if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) { NodejsToolsEventSource.Instance.HierarchyEventException("OnItemAdded failed.", result, parent.HierarchyId, prevId, child.HierarchyId, this.GetHierarchyItems()); ErrorHandler.ThrowOnFailure(result); } } catch (InvalidOperationException ex) { NodejsToolsEventSource.Instance.HierarchyEventException(ex.Message, result, parent.HierarchyId, prevId, child.HierarchyId, this.GetHierarchyItems()); throw; } } NodejsToolsEventSource.Instance.HierarchyEventStop("OnItemAdded successful."); } private IEnumerable<HierarchyItem> GetHierarchyItems() { var solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution; return solution.EnumerateHierarchyItems(); } internal void OnItemDeleted(HierarchyNode deletedItem) { this.Site.GetUIThread().MustBeCalledFromUIThread(); if (deletedItem is IDiskBasedNode diskNode) { this.DiskNodes.TryRemove(diskNode.Url, out _); } this.RaiseItemDeleted(deletedItem); } internal void RaiseItemDeleted(HierarchyNode deletedItem) { if ((this.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) { return; } this.ExtensibilityEventsDispatcher.FireItemRemoved(deletedItem); if (this.hierarchyEventSinks.Count > 0) { // Note that in some cases (deletion of project node for example), an Advise // may be removed while we are iterating over it. To get around this problem we // take a snapshot of the advise list and walk that. var clonedSink = new List<IVsHierarchyEvents>(); foreach (IVsHierarchyEvents anEvent in this.hierarchyEventSinks) { clonedSink.Add(anEvent); } foreach (var clonedEvent in clonedSink) { var result = clonedEvent.OnItemDeleted(deletedItem.HierarchyId); if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) { ErrorHandler.ThrowOnFailure(result); } } } } internal void OnItemsAppended(HierarchyNode parent) { Utilities.ArgumentNotNull(nameof(parent), parent); if ((this.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) { return; } foreach (IVsHierarchyEvents sink in this.hierarchyEventSinks) { var result = sink.OnItemsAppended(parent.HierarchyId); if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) { ErrorHandler.ThrowOnFailure(result); } } } internal void OnPropertyChanged(HierarchyNode node, int propid, uint flags) { Utilities.ArgumentNotNull(nameof(node), node); if ((this.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) { return; } foreach (IVsHierarchyEvents sink in this.hierarchyEventSinks) { var result = sink.OnPropertyChanged(node.HierarchyId, propid, flags); if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) { ErrorHandler.ThrowOnFailure(result); } } } internal void OnInvalidateItems(HierarchyNode parent) { Utilities.ArgumentNotNull(nameof(parent), parent); if ((this.EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) { return; } var wasExpanded = this.ParentHierarchy != null && parent.GetIsExpanded(); foreach (IVsHierarchyEvents sink in this.hierarchyEventSinks) { var result = sink.OnInvalidateItems(parent.HierarchyId); if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) { ErrorHandler.ThrowOnFailure(result); } } if (wasExpanded) { parent.ExpandItem(EXPANDFLAGS.EXPF_ExpandFolder); } } /// <summary> /// Causes the hierarchy to be redrawn. /// </summary> /// <param name="element">Used by the hierarchy to decide which element to redraw</param> internal void ReDrawNode(HierarchyNode node, UIHierarchyElement element) { foreach (IVsHierarchyEvents sink in this.hierarchyEventSinks) { int result; if ((element & UIHierarchyElement.Icon) != 0) { result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_IconIndex, 0); Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument()); } if ((element & UIHierarchyElement.Caption) != 0) { result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_Caption, 0); Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument()); } if ((element & UIHierarchyElement.SccState) != 0) { result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_StateIconIndex, 0); Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument()); } } } #endregion #region IVsHierarchyDeleteHandler methods public virtual int DeleteItem(uint delItemOp, uint itemId) { if (itemId == VSConstants.VSITEMID_SELECTION) { return VSConstants.E_INVALIDARG; } var node = NodeFromItemId(itemId); if (node != null) { node.Remove((delItemOp & (uint)__VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) != 0); return VSConstants.S_OK; } return VSConstants.E_FAIL; } public virtual int QueryDeleteItem(uint delItemOp, uint itemId, out int candelete) { candelete = 0; if (itemId == VSConstants.VSITEMID_SELECTION) { return VSConstants.E_INVALIDARG; } // We ask the project what state it is. If he is a state that should not allow delete then we return. if (IsCurrentStateASuppressCommandsMode()) { return VSConstants.S_OK; } var node = NodeFromItemId(itemId); if (node == null) { return VSConstants.E_FAIL; } // Ask the nodes if they can remove the item. var canDeleteItem = node.CanDeleteItem((__VSDELETEITEMOPERATION)delItemOp); if (canDeleteItem) { candelete = 1; } return VSConstants.S_OK; } #endregion #region IVsHierarchyDeleteHandler2 methods public int ShowMultiSelDeleteOrRemoveMessage(uint dwDelItemOp, uint cDelItems, uint[] rgDelItems, out int pfCancelOperation) { pfCancelOperation = 0; return VSConstants.S_OK; } public int ShowSpecificDeleteRemoveMessage(uint dwDelItemOps, uint cDelItems, uint[] rgDelItems, out int pfShowStandardMessage, out uint pdwDelItemOp) { pfShowStandardMessage = 1; pdwDelItemOp = dwDelItemOps; var items = rgDelItems.Select(id => NodeFromItemId(id)).Where(n => n != null).ToArray(); if (items.Length == 0) { return VSConstants.S_OK; } else { items[0].ShowDeleteMessage(items, (__VSDELETEITEMOPERATION)dwDelItemOps, out var cancel, out var showStandardDialog); if (showStandardDialog || cancel) { pdwDelItemOp = 0; } if (!showStandardDialog) { pfShowStandardMessage = 0; } } return VSConstants.S_OK; } #endregion #region IVsPersistHierarchyItem2 methods /// <summary> /// Saves the hierarchy item to disk. /// </summary> /// <param name="saveFlag">Flags whose values are taken from the VSSAVEFLAGS enumeration.</param> /// <param name="silentSaveAsName">New filename when doing silent save as</param> /// <param name="itemid">Item identifier of the hierarchy item saved from VSITEMID.</param> /// <param name="docData">Item identifier of the hierarchy item saved from VSITEMID.</param> /// <param name="cancelled">[out] true if the save action was canceled.</param> /// <returns>[out] true if the save action was canceled.</returns> public virtual int SaveItem(VSSAVEFLAGS saveFlag, string silentSaveAsName, uint itemid, IntPtr docData, out int cancelled) { cancelled = 0; // Validate itemid if (itemid == VSConstants.VSITEMID_ROOT || itemid == VSConstants.VSITEMID_SELECTION) { return VSConstants.E_INVALIDARG; } var node = this.NodeFromItemId(itemid); if (node == null) { return VSConstants.E_FAIL; } var existingFileMoniker = node.GetMkDocument(); // We can only perform save if the document is open if (docData == IntPtr.Zero) { throw new InvalidOperationException(SR.GetString(SR.CanNotSaveFileNotOpeneInEditor, node.Url)); } var docNew = string.Empty; var returnCode = VSConstants.S_OK; IPersistFileFormat ff = null; IVsPersistDocData dd = null; var shell = this.Site.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell); try { //Save docdata object. //For the saveas action a dialog is show in order to enter new location of file. //In case of a save action and the file is readonly a dialog is also shown //with a couple of options, SaveAs, Overwrite or Cancel. ff = Marshal.GetObjectForIUnknown(docData) as IPersistFileFormat; Utilities.CheckNotNull(ff); if (VSSAVEFLAGS.VSSAVE_SilentSave == saveFlag) { ErrorHandler.ThrowOnFailure(shell.SaveDocDataToFile(saveFlag, ff, silentSaveAsName, out docNew, out cancelled)); } else { dd = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; Utilities.CheckNotNull(dd); ErrorHandler.ThrowOnFailure(dd.SaveDocData(saveFlag, out docNew, out cancelled)); } // We can be unloaded after the SaveDocData() call if the save caused a designer to add a file and this caused // the project file to be reloaded (QEQS caused a newer version of the project file to be downloaded). So we check // here. if (this.IsClosed) { cancelled = 1; return (int)OleConstants.OLECMDERR_E_CANCELED; } else { // if a SaveAs occurred we need to update to the fact our item's name has changed. // this includes the following: // 1. call RenameDocument on the RunningDocumentTable // 2. update the full path name for the item in our hierarchy // 3. a directory-based project may need to transfer the open editor to the // MiscFiles project if the new file is saved outside of the project directory. // This is accomplished by calling IVsExternalFilesManager::TransferDocument // we have three options for a saveas action to be performed // 1. the flag was set (the save as command was triggered) // 2. a silent save specifying a new document name // 3. a save command was triggered but was not possible because the file has a read only attrib. Therefore // the user has chosen to do a save as in the dialog that showed up var emptyOrSamePath = string.IsNullOrEmpty(docNew) || CommonUtils.IsSamePath(existingFileMoniker, docNew); var saveAs = ((saveFlag == VSSAVEFLAGS.VSSAVE_SaveAs)) || ((saveFlag == VSSAVEFLAGS.VSSAVE_SilentSave) && !emptyOrSamePath) || ((saveFlag == VSSAVEFLAGS.VSSAVE_Save) && !emptyOrSamePath); if (saveAs) { returnCode = node.AfterSaveItemAs(docData, docNew); // If it has been cancelled recover the old name. if ((returnCode == (int)OleConstants.OLECMDERR_E_CANCELED || returnCode == VSConstants.E_ABORT)) { // Cleanup. this.DeleteFromStorage(docNew); if (ff != null) { returnCode = shell.SaveDocDataToFile(VSSAVEFLAGS.VSSAVE_SilentSave, ff, existingFileMoniker, out docNew, out cancelled); } } else if (returnCode != VSConstants.S_OK) { ErrorHandler.ThrowOnFailure(returnCode); } } } } catch (COMException e) { Trace.WriteLine("Exception :" + e.Message); returnCode = e.ErrorCode; // Try to recover // changed from MPFProj: // http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=6982 if (ff != null && cancelled == 0) { ErrorHandler.ThrowOnFailure(shell.SaveDocDataToFile(VSSAVEFLAGS.VSSAVE_SilentSave, ff, existingFileMoniker, out docNew, out cancelled)); } } return returnCode; } /// <summary> /// Determines whether the hierarchy item changed. /// </summary> /// <param name="itemId">Item identifier of the hierarchy item contained in VSITEMID.</param> /// <param name="docData">Pointer to the IUnknown interface of the hierarchy item.</param> /// <param name="isDirty">true if the hierarchy item changed.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int IsItemDirty(uint itemId, IntPtr docData, out int isDirty) { var pd = (IVsPersistDocData)Marshal.GetObjectForIUnknown(docData); return ErrorHandler.ThrowOnFailure(pd.IsDocDataDirty(out isDirty)); } /// <summary> /// Flag indicating that changes to a file can be ignored when item is saved or reloaded. /// </summary> /// <param name="itemId">Specifies the item id from VSITEMID.</param> /// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int IgnoreItemFileChanges(uint itemId, int ignoreFlag) { var node = this.NodeFromItemId(itemId); if (node != null) { node.IgnoreItemFileChanges(ignoreFlag == 0 ? false : true); } return VSConstants.S_OK; } /// <summary> /// Called to determine whether a project item is reloadable before calling ReloadItem. /// </summary> /// <param name="itemId">Item identifier of an item in the hierarchy. Valid values are VSITEMID_NIL, VSITEMID_ROOT and VSITEMID_SELECTION.</param> /// <param name="isReloadable">A flag indicating that the project item is reloadable (1 for reloadable, 0 for non-reloadable).</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int IsItemReloadable(uint itemId, out int isReloadable) { isReloadable = 0; var node = this.NodeFromItemId(itemId); if (node != null) { isReloadable = (node.IsItemReloadable()) ? 1 : 0; } return VSConstants.S_OK; } /// <summary> /// Called to reload a project item. /// </summary> /// <param name="itemId">Specifies itemid from VSITEMID.</param> /// <param name="reserved">Reserved.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int ReloadItem(uint itemId, uint reserved) { var node = this.NodeFromItemId(itemId); if (node != null) { node.ReloadItem(reserved); } return VSConstants.S_OK; } #endregion public void UpdatePathForDeferredSave(string oldPath, string newPath) { this.Site.GetUIThread().MustBeCalledFromUIThread(); if (this.DiskNodes.TryRemove(oldPath, out var existing)) { this.DiskNodes.TryAdd(newPath, existing); } } public IVsHierarchy ParentHierarchy => this.parentHierarchy; [Conditional("DEBUG")] internal void AssertHasParentHierarchy() { // Calling into solution explorer before a parent hierarchy is assigned can // cause us to corrupt solution explorer if we're using flavored projects. We // will call in with our inner project node and later we get wrapped in an // aggregate COM object which has different object identity. At that point // solution explorer is confused because it uses object identity to track // the hierarchies. Debug.Assert(this.parentHierarchy != null, "dont call into the hierarchy before the project is loaded, it corrupts the hierarchy"); } } }
41.504595
290
0.539593
[ "Apache-2.0" ]
ConnectionMaster/nodejstools
Nodejs/Product/Nodejs/SharedProject/ProjectNode.cs
282,079
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.XLANGs.BaseTypes; using Microsoft.BizTalk.XLANGs.BTXEngine; // 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("Pipelines")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pipelines")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Microsoft.XLANGs.BaseTypes.BizTalkAssemblyAttribute(typeof(BTXService))] // 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("1ad073aa-4915-48ca-81f0-e6c77c5be5e0")] // 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.775
84
0.755642
[ "MIT" ]
BTDF/BTDF
src/btdf/Samples/BizTalk/Bam/Pipelines/Properties/AssemblyInfo.cs
1,554
C#
using OpenLoganalyzerLib.Core.Enum; using OpenLoganalyzerLib.Core.Interfaces.Loader; using OpenLoganalyzerLib.Core.Interfaces.Loglines; using OpenLoganalyzerLib.Core.Loglines; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; namespace OpenLoganalyzerLib.Core.Loader { public class FileLoader : ILoader { private ILoaderConfiguration configuration; /// <summary> /// Set the configuration /// </summary> /// <param name="configuration">The configuration to set</param> public void SetConfiguration(ILoaderConfiguration newConfiguration) { configuration = newConfiguration; } /// <summary> /// Load the data /// </summary> /// <returns>A list with the log lines</returns> public List<ILogLine> Load() { List<ILogLine> logLines = new List<ILogLine>(); if (configuration.LoaderType != LoaderTypeEnum.FileLoader) { return logLines; } if (!File.Exists(configuration.GetAdditionalSetting(AdditionalSettingsEnum.FilePath))) { return logLines; } foreach (string line in File.ReadAllLines(configuration.GetAdditionalSetting(AdditionalSettingsEnum.FilePath))) { if (line == "") { continue; } string thrownBy = ""; string severity = ""; string message = ""; Dictionary<string, string> additionalLines = new Dictionary<string, string>(); DateTime time = DateTime.Now; foreach (string filterName in configuration.FilterNames) { string filterString = configuration.Filters[filterName]; MatchCollection matches = Regex.Matches(line, filterString); if (matches.Count >= 1) { switch (filterName) { case "Caller": thrownBy = GetMatch(matches); break; case "Message": message = GetMatch(matches); break; case "Severity": severity = GetMatch(matches); break; case "Datetime": string format = configuration.GetAdditionalSetting(AdditionalSettingsEnum.DateTimeFormat); if (format == "") { continue; } DateTime.TryParseExact(GetMatch(matches), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out time); break; default: additionalLines.Add(filterName, matches[0].Value); break; } } } ILogLine logLine = new SimpleLogline(thrownBy, time, message, severity, additionalLines); logLines.Add(logLine); } return logLines; } /// <summary> /// This method will get all the matches and return the string /// </summary> /// <param name="matchCollection"></param> /// <returns></returns> private string GetMatch(MatchCollection matchCollection) { string returnString = ""; Match realMatch = matchCollection[0]; returnString = realMatch.Value.Trim(); if (realMatch.Groups.Count == 2) { Group currentGroup = realMatch.Groups[1]; returnString = currentGroup.Value.Trim(); } return returnString; } } }
34.311475
143
0.48925
[ "MIT" ]
XanatosX/OpenLoganalyzer
OpenLoganalyzerLib/Core/Loader/FileLoader.cs
4,188
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/osconfig/v1alpha/os_policy.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.OsConfig.V1Alpha { /// <summary>Holder for reflection information generated from google/cloud/osconfig/v1alpha/os_policy.proto</summary> public static partial class OsPolicyReflection { #region Descriptor /// <summary>File descriptor for google/cloud/osconfig/v1alpha/os_policy.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OsPolicyReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvY2xvdWQvb3Njb25maWcvdjFhbHBoYS9vc19wb2xpY3kucHJv", "dG8SHWdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFscGhhGh9nb29nbGUvYXBp", "L2ZpZWxkX2JlaGF2aW9yLnByb3RvIukhCghPU1BvbGljeRIPCgJpZBgBIAEo", "CUID4EECEhMKC2Rlc2NyaXB0aW9uGAIgASgJEj8KBG1vZGUYAyABKA4yLC5n", "b29nbGUuY2xvdWQub3Njb25maWcudjFhbHBoYS5PU1BvbGljeS5Nb2RlQgPg", "QQISUwoPcmVzb3VyY2VfZ3JvdXBzGAQgAygLMjUuZ29vZ2xlLmNsb3VkLm9z", "Y29uZmlnLnYxYWxwaGEuT1NQb2xpY3kuUmVzb3VyY2VHcm91cEID4EECEiUK", "HWFsbG93X25vX3Jlc291cmNlX2dyb3VwX21hdGNoGAUgASgIGjUKCE9TRmls", "dGVyEhUKDW9zX3Nob3J0X25hbWUYASABKAkSEgoKb3NfdmVyc2lvbhgCIAEo", "CRriHQoIUmVzb3VyY2USDwoCaWQYASABKAlCA+BBAhJPCgNwa2cYAiABKAsy", "QC5nb29nbGUuY2xvdWQub3Njb25maWcudjFhbHBoYS5PU1BvbGljeS5SZXNv", "dXJjZS5QYWNrYWdlUmVzb3VyY2VIABJZCgpyZXBvc2l0b3J5GAMgASgLMkMu", "Z29vZ2xlLmNsb3VkLm9zY29uZmlnLnYxYWxwaGEuT1NQb2xpY3kuUmVzb3Vy", "Y2UuUmVwb3NpdG9yeVJlc291cmNlSAASTQoEZXhlYxgEIAEoCzI9Lmdvb2ds", "ZS5jbG91ZC5vc2NvbmZpZy52MWFscGhhLk9TUG9saWN5LlJlc291cmNlLkV4", "ZWNSZXNvdXJjZUgAEk0KBGZpbGUYBSABKAsyPS5nb29nbGUuY2xvdWQub3Nj", "b25maWcudjFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5GaWxlUmVzb3VyY2VI", "ABrQAgoERmlsZRJOCgZyZW1vdGUYASABKAsyPC5nb29nbGUuY2xvdWQub3Nj", "b25maWcudjFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5GaWxlLlJlbW90ZUgA", "EkgKA2djcxgCIAEoCzI5Lmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFscGhh", "Lk9TUG9saWN5LlJlc291cmNlLkZpbGUuR2NzSAASFAoKbG9jYWxfcGF0aBgD", "IAEoCUgAEhYKDmFsbG93X2luc2VjdXJlGAQgASgIGjMKBlJlbW90ZRIQCgN1", "cmkYASABKAlCA+BBAhIXCg9zaGEyNTZfY2hlY2tzdW0YAiABKAkaQwoDR2Nz", "EhMKBmJ1Y2tldBgBIAEoCUID4EECEhMKBm9iamVjdBgCIAEoCUID4EECEhIK", "CmdlbmVyYXRpb24YAyABKANCBgoEdHlwZRrZCQoPUGFja2FnZVJlc291cmNl", "EmkKDWRlc2lyZWRfc3RhdGUYASABKA4yTS5nb29nbGUuY2xvdWQub3Njb25m", "aWcudjFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5QYWNrYWdlUmVzb3VyY2Uu", "RGVzaXJlZFN0YXRlQgPgQQISUwoDYXB0GAIgASgLMkQuZ29vZ2xlLmNsb3Vk", "Lm9zY29uZmlnLnYxYWxwaGEuT1NQb2xpY3kuUmVzb3VyY2UuUGFja2FnZVJl", "c291cmNlLkFQVEgAElMKA2RlYhgDIAEoCzJELmdvb2dsZS5jbG91ZC5vc2Nv", "bmZpZy52MWFscGhhLk9TUG9saWN5LlJlc291cmNlLlBhY2thZ2VSZXNvdXJj", "ZS5EZWJIABJTCgN5dW0YBCABKAsyRC5nb29nbGUuY2xvdWQub3Njb25maWcu", "djFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5QYWNrYWdlUmVzb3VyY2UuWVVN", "SAASWQoGenlwcGVyGAUgASgLMkcuZ29vZ2xlLmNsb3VkLm9zY29uZmlnLnYx", "YWxwaGEuT1NQb2xpY3kuUmVzb3VyY2UuUGFja2FnZVJlc291cmNlLlp5cHBl", "ckgAElMKA3JwbRgGIAEoCzJELmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFs", "cGhhLk9TUG9saWN5LlJlc291cmNlLlBhY2thZ2VSZXNvdXJjZS5SUE1IABJZ", "CgZnb29nZXQYByABKAsyRy5nb29nbGUuY2xvdWQub3Njb25maWcudjFhbHBo", "YS5PU1BvbGljeS5SZXNvdXJjZS5QYWNrYWdlUmVzb3VyY2UuR29vR2V0SAAS", "UwoDbXNpGAggASgLMkQuZ29vZ2xlLmNsb3VkLm9zY29uZmlnLnYxYWxwaGEu", "T1NQb2xpY3kuUmVzb3VyY2UuUGFja2FnZVJlc291cmNlLk1TSUgAGmQKA0Rl", "YhJKCgZzb3VyY2UYASABKAsyNS5nb29nbGUuY2xvdWQub3Njb25maWcudjFh", "bHBoYS5PU1BvbGljeS5SZXNvdXJjZS5GaWxlQgPgQQISEQoJcHVsbF9kZXBz", "GAIgASgIGhgKA0FQVBIRCgRuYW1lGAEgASgJQgPgQQIaZAoDUlBNEkoKBnNv", "dXJjZRgBIAEoCzI1Lmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFscGhhLk9T", "UG9saWN5LlJlc291cmNlLkZpbGVCA+BBAhIRCglwdWxsX2RlcHMYAiABKAga", "GAoDWVVNEhEKBG5hbWUYASABKAlCA+BBAhobCgZaeXBwZXISEQoEbmFtZRgB", "IAEoCUID4EECGhsKBkdvb0dldBIRCgRuYW1lGAEgASgJQgPgQQIaZQoDTVNJ", "EkoKBnNvdXJjZRgBIAEoCzI1Lmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFs", "cGhhLk9TUG9saWN5LlJlc291cmNlLkZpbGVCA+BBAhISCgpwcm9wZXJ0aWVz", "GAIgAygJIkkKDERlc2lyZWRTdGF0ZRIdChlERVNJUkVEX1NUQVRFX1VOU1BF", "Q0lGSUVEEAASDQoJSU5TVEFMTEVEEAESCwoHUkVNT1ZFRBACQhAKDnN5c3Rl", "bV9wYWNrYWdlGtEHChJSZXBvc2l0b3J5UmVzb3VyY2USYAoDYXB0GAEgASgL", "MlEuZ29vZ2xlLmNsb3VkLm9zY29uZmlnLnYxYWxwaGEuT1NQb2xpY3kuUmVz", "b3VyY2UuUmVwb3NpdG9yeVJlc291cmNlLkFwdFJlcG9zaXRvcnlIABJgCgN5", "dW0YAiABKAsyUS5nb29nbGUuY2xvdWQub3Njb25maWcudjFhbHBoYS5PU1Bv", "bGljeS5SZXNvdXJjZS5SZXBvc2l0b3J5UmVzb3VyY2UuWXVtUmVwb3NpdG9y", "eUgAEmYKBnp5cHBlchgDIAEoCzJULmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52", "MWFscGhhLk9TUG9saWN5LlJlc291cmNlLlJlcG9zaXRvcnlSZXNvdXJjZS5a", "eXBwZXJSZXBvc2l0b3J5SAASYAoDZ29vGAQgASgLMlEuZ29vZ2xlLmNsb3Vk", "Lm9zY29uZmlnLnYxYWxwaGEuT1NQb2xpY3kuUmVzb3VyY2UuUmVwb3NpdG9y", "eVJlc291cmNlLkdvb1JlcG9zaXRvcnlIABqjAgoNQXB0UmVwb3NpdG9yeRJ4", "CgxhcmNoaXZlX3R5cGUYASABKA4yXS5nb29nbGUuY2xvdWQub3Njb25maWcu", "djFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5SZXBvc2l0b3J5UmVzb3VyY2Uu", "QXB0UmVwb3NpdG9yeS5BcmNoaXZlVHlwZUID4EECEhAKA3VyaRgCIAEoCUID", "4EECEhkKDGRpc3RyaWJ1dGlvbhgDIAEoCUID4EECEhcKCmNvbXBvbmVudHMY", "BCADKAlCA+BBAhIPCgdncGdfa2V5GAUgASgJIkEKC0FyY2hpdmVUeXBlEhwK", "GEFSQ0hJVkVfVFlQRV9VTlNQRUNJRklFRBAAEgcKA0RFQhABEgsKB0RFQl9T", "UkMQAhpfCg1ZdW1SZXBvc2l0b3J5Eg8KAmlkGAEgASgJQgPgQQISFAoMZGlz", "cGxheV9uYW1lGAIgASgJEhUKCGJhc2VfdXJsGAMgASgJQgPgQQISEAoIZ3Bn", "X2tleXMYBCADKAkaYgoQWnlwcGVyUmVwb3NpdG9yeRIPCgJpZBgBIAEoCUID", "4EECEhQKDGRpc3BsYXlfbmFtZRgCIAEoCRIVCghiYXNlX3VybBgDIAEoCUID", "4EECEhAKCGdwZ19rZXlzGAQgAygJGjQKDUdvb1JlcG9zaXRvcnkSEQoEbmFt", "ZRgBIAEoCUID4EECEhAKA3VybBgCIAEoCUID4EECQgwKCnJlcG9zaXRvcnka", "jQQKDEV4ZWNSZXNvdXJjZRJZCgh2YWxpZGF0ZRgBIAEoCzJCLmdvb2dsZS5j", "bG91ZC5vc2NvbmZpZy52MWFscGhhLk9TUG9saWN5LlJlc291cmNlLkV4ZWNS", "ZXNvdXJjZS5FeGVjQgPgQQISUwoHZW5mb3JjZRgCIAEoCzJCLmdvb2dsZS5j", "bG91ZC5vc2NvbmZpZy52MWFscGhhLk9TUG9saWN5LlJlc291cmNlLkV4ZWNS", "ZXNvdXJjZS5FeGVjGswCCgRFeGVjEkUKBGZpbGUYASABKAsyNS5nb29nbGUu", "Y2xvdWQub3Njb25maWcudjFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5GaWxl", "SAASEAoGc2NyaXB0GAIgASgJSAASDAoEYXJncxgDIAMoCRJoCgtpbnRlcnBy", "ZXRlchgEIAEoDjJOLmdvb2dsZS5jbG91ZC5vc2NvbmZpZy52MWFscGhhLk9T", "UG9saWN5LlJlc291cmNlLkV4ZWNSZXNvdXJjZS5FeGVjLkludGVycHJldGVy", "QgPgQQISGAoQb3V0cHV0X2ZpbGVfcGF0aBgFIAEoCSJPCgtJbnRlcnByZXRl", "chIbChdJTlRFUlBSRVRFUl9VTlNQRUNJRklFRBAAEggKBE5PTkUQARIJCgVT", "SEVMTBACEg4KClBPV0VSU0hFTEwQA0IICgZzb3VyY2Ua1gIKDEZpbGVSZXNv", "dXJjZRJFCgRmaWxlGAEgASgLMjUuZ29vZ2xlLmNsb3VkLm9zY29uZmlnLnYx", "YWxwaGEuT1NQb2xpY3kuUmVzb3VyY2UuRmlsZUgAEhEKB2NvbnRlbnQYAiAB", "KAlIABIRCgRwYXRoGAMgASgJQgPgQQISXgoFc3RhdGUYBCABKA4ySi5nb29n", "bGUuY2xvdWQub3Njb25maWcudjFhbHBoYS5PU1BvbGljeS5SZXNvdXJjZS5G", "aWxlUmVzb3VyY2UuRGVzaXJlZFN0YXRlQgPgQQISEwoLcGVybWlzc2lvbnMY", "BSABKAkiWgoMRGVzaXJlZFN0YXRlEh0KGURFU0lSRURfU1RBVEVfVU5TUEVD", "SUZJRUQQABILCgdQUkVTRU5UEAESCgoGQUJTRU5UEAISEgoOQ09OVEVOVFNf", "TUFUQ0gQA0IICgZzb3VyY2VCDwoNcmVzb3VyY2VfdHlwZRqeAQoNUmVzb3Vy", "Y2VHcm91cBJDCglvc19maWx0ZXIYASABKAsyMC5nb29nbGUuY2xvdWQub3Nj", "b25maWcudjFhbHBoYS5PU1BvbGljeS5PU0ZpbHRlchJICglyZXNvdXJjZXMY", "AiADKAsyMC5nb29nbGUuY2xvdWQub3Njb25maWcudjFhbHBoYS5PU1BvbGlj", "eS5SZXNvdXJjZUID4EECIj0KBE1vZGUSFAoQTU9ERV9VTlNQRUNJRklFRBAA", "Eg4KClZBTElEQVRJT04QARIPCgtFTkZPUkNFTUVOVBACQt4BCiFjb20uZ29v", "Z2xlLmNsb3VkLm9zY29uZmlnLnYxYWxwaGFCDU9TUG9saWN5UHJvdG9QAVpF", "Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9jbG91ZC9v", "c2NvbmZpZy92MWFscGhhO29zY29uZmlnqgIdR29vZ2xlLkNsb3VkLk9zQ29u", "ZmlnLlYxQWxwaGHKAh1Hb29nbGVcQ2xvdWRcT3NDb25maWdcVjFhbHBoYeoC", "IEdvb2dsZTo6Q2xvdWQ6Ok9zQ29uZmlnOjpWMWFscGhhYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.FieldBehaviorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Parser, new[]{ "Id", "Description", "Mode", "ResourceGroups", "AllowNoResourceGroupMatch" }, null, new[]{ typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter.Parser, new[]{ "OsShortName", "OsVersion" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Parser, new[]{ "Id", "Pkg", "Repository", "Exec", "File" }, new[]{ "ResourceType" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Parser, new[]{ "Remote", "Gcs", "LocalPath", "AllowInsecure" }, new[]{ "Type" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote.Parser, new[]{ "Uri", "Sha256Checksum" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs.Parser, new[]{ "Bucket", "Object", "Generation" }, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Parser, new[]{ "DesiredState", "Apt", "Deb", "Yum", "Zypper", "Rpm", "Googet", "Msi" }, new[]{ "SystemPackage" }, new[]{ typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb.Parser, new[]{ "Source", "PullDeps" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT.Parser, new[]{ "Name" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM.Parser, new[]{ "Source", "PullDeps" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM.Parser, new[]{ "Name" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper.Parser, new[]{ "Name" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet.Parser, new[]{ "Name" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI.Parser, new[]{ "Source", "Properties" }, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Parser, new[]{ "Apt", "Yum", "Zypper", "Goo" }, new[]{ "Repository" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Parser, new[]{ "ArchiveType", "Uri", "Distribution", "Components", "GpgKey" }, null, new[]{ typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType) }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository.Parser, new[]{ "Id", "DisplayName", "BaseUrl", "GpgKeys" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository.Parser, new[]{ "Id", "DisplayName", "BaseUrl", "GpgKeys" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository.Parser, new[]{ "Name", "Url" }, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Parser, new[]{ "Validate", "Enforce" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Parser, new[]{ "File", "Script", "Args", "Interpreter", "OutputFilePath" }, new[]{ "Source" }, new[]{ typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter) }, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Parser, new[]{ "File", "Content", "Path", "State", "Permissions" }, new[]{ "Source" }, new[]{ typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState) }, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup), global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup.Parser, new[]{ "OsFilter", "Resources" }, null, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// An OS policy defines the desired state configuration for a VM. /// </summary> public sealed partial class OSPolicy : pb::IMessage<OSPolicy> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<OSPolicy> _parser = new pb::MessageParser<OSPolicy>(() => new OSPolicy()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<OSPolicy> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OsPolicyReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSPolicy() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSPolicy(OSPolicy other) : this() { id_ = other.id_; description_ = other.description_; mode_ = other.mode_; resourceGroups_ = other.resourceGroups_.Clone(); allowNoResourceGroupMatch_ = other.allowNoResourceGroupMatch_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSPolicy Clone() { return new OSPolicy(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; /// <summary> /// Required. The id of the OS policy with the following restrictions: /// /// * Must contain only lowercase letters, numbers, and hyphens. /// * Must start with a letter. /// * Must be between 1-63 characters. /// * Must end with a number or a letter. /// * Must be unique within the assignment. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 2; private string description_ = ""; /// <summary> /// Policy description. /// Length of the description is limited to 1024 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "mode" field.</summary> public const int ModeFieldNumber = 3; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode mode_ = global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified; /// <summary> /// Required. Policy mode /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode Mode { get { return mode_; } set { mode_ = value; } } /// <summary>Field number for the "resource_groups" field.</summary> public const int ResourceGroupsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup> _repeated_resourceGroups_codec = pb::FieldCodec.ForMessage(34, global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup> resourceGroups_ = new pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup>(); /// <summary> /// Required. List of resource groups for the policy. /// For a particular VM, resource groups are evaluated in the order specified /// and the first resource group that is applicable is selected and the rest /// are ignored. /// /// If none of the resource groups are applicable for a VM, the VM is /// considered to be non-compliant w.r.t this policy. This behavior can be /// toggled by the flag `allow_no_resource_group_match` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.ResourceGroup> ResourceGroups { get { return resourceGroups_; } } /// <summary>Field number for the "allow_no_resource_group_match" field.</summary> public const int AllowNoResourceGroupMatchFieldNumber = 5; private bool allowNoResourceGroupMatch_; /// <summary> /// This flag determines the OS policy compliance status when none of the /// resource groups within the policy are applicable for a VM. Set this value /// to `true` if the policy needs to be reported as compliant even if the /// policy has nothing to validate or enforce. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool AllowNoResourceGroupMatch { get { return allowNoResourceGroupMatch_; } set { allowNoResourceGroupMatch_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as OSPolicy); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(OSPolicy other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; if (Description != other.Description) return false; if (Mode != other.Mode) return false; if(!resourceGroups_.Equals(other.resourceGroups_)) return false; if (AllowNoResourceGroupMatch != other.AllowNoResourceGroupMatch) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (Mode != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified) hash ^= Mode.GetHashCode(); hash ^= resourceGroups_.GetHashCode(); if (AllowNoResourceGroupMatch != false) hash ^= AllowNoResourceGroupMatch.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } if (Mode != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Mode); } resourceGroups_.WriteTo(output, _repeated_resourceGroups_codec); if (AllowNoResourceGroupMatch != false) { output.WriteRawTag(40); output.WriteBool(AllowNoResourceGroupMatch); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } if (Mode != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Mode); } resourceGroups_.WriteTo(ref output, _repeated_resourceGroups_codec); if (AllowNoResourceGroupMatch != false) { output.WriteRawTag(40); output.WriteBool(AllowNoResourceGroupMatch); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (Mode != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Mode); } size += resourceGroups_.CalculateSize(_repeated_resourceGroups_codec); if (AllowNoResourceGroupMatch != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(OSPolicy other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.Description.Length != 0) { Description = other.Description; } if (other.Mode != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode.Unspecified) { Mode = other.Mode; } resourceGroups_.Add(other.resourceGroups_); if (other.AllowNoResourceGroupMatch != false) { AllowNoResourceGroupMatch = other.AllowNoResourceGroupMatch; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } case 18: { Description = input.ReadString(); break; } case 24: { Mode = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode) input.ReadEnum(); break; } case 34: { resourceGroups_.AddEntriesFrom(input, _repeated_resourceGroups_codec); break; } case 40: { AllowNoResourceGroupMatch = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Id = input.ReadString(); break; } case 18: { Description = input.ReadString(); break; } case 24: { Mode = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Mode) input.ReadEnum(); break; } case 34: { resourceGroups_.AddEntriesFrom(ref input, _repeated_resourceGroups_codec); break; } case 40: { AllowNoResourceGroupMatch = input.ReadBool(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the OSPolicy message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Policy mode /// </summary> public enum Mode { /// <summary> /// Invalid mode /// </summary> [pbr::OriginalName("MODE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// This mode checks if the configuration resources in the policy are in /// their desired state. No actions are performed if they are not in the /// desired state. This mode is used for reporting purposes. /// </summary> [pbr::OriginalName("VALIDATION")] Validation = 1, /// <summary> /// This mode checks if the configuration resources in the policy are in /// their desired state, and if not, enforces the desired state. /// </summary> [pbr::OriginalName("ENFORCEMENT")] Enforcement = 2, } /// <summary> /// The `OSFilter` is used to specify the OS filtering criteria for the /// resource group. /// </summary> public sealed partial class OSFilter : pb::IMessage<OSFilter> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<OSFilter> _parser = new pb::MessageParser<OSFilter>(() => new OSFilter()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<OSFilter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSFilter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSFilter(OSFilter other) : this() { osShortName_ = other.osShortName_; osVersion_ = other.osVersion_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OSFilter Clone() { return new OSFilter(this); } /// <summary>Field number for the "os_short_name" field.</summary> public const int OsShortNameFieldNumber = 1; private string osShortName_ = ""; /// <summary> /// This should match OS short name emitted by the OS inventory agent. /// An empty value matches any OS. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OsShortName { get { return osShortName_; } set { osShortName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "os_version" field.</summary> public const int OsVersionFieldNumber = 2; private string osVersion_ = ""; /// <summary> /// This value should match the version emitted by the OS inventory /// agent. /// Prefix matches are supported if asterisk(*) is provided as the /// last character. For example, to match all versions with a major /// version of `7`, specify the following value for this field `7.*` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OsVersion { get { return osVersion_; } set { osVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as OSFilter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(OSFilter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OsShortName != other.OsShortName) return false; if (OsVersion != other.OsVersion) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (OsShortName.Length != 0) hash ^= OsShortName.GetHashCode(); if (OsVersion.Length != 0) hash ^= OsVersion.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (OsShortName.Length != 0) { output.WriteRawTag(10); output.WriteString(OsShortName); } if (OsVersion.Length != 0) { output.WriteRawTag(18); output.WriteString(OsVersion); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (OsShortName.Length != 0) { output.WriteRawTag(10); output.WriteString(OsShortName); } if (OsVersion.Length != 0) { output.WriteRawTag(18); output.WriteString(OsVersion); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (OsShortName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OsShortName); } if (OsVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OsVersion); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(OSFilter other) { if (other == null) { return; } if (other.OsShortName.Length != 0) { OsShortName = other.OsShortName; } if (other.OsVersion.Length != 0) { OsVersion = other.OsVersion; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { OsShortName = input.ReadString(); break; } case 18: { OsVersion = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { OsShortName = input.ReadString(); break; } case 18: { OsVersion = input.ReadString(); break; } } } } #endif } /// <summary> /// An OS policy resource is used to define the desired state configuration /// and provides a specific functionality like installing/removing packages, /// executing a script etc. /// /// The system ensures that resources are always in their desired state by /// taking necessary actions if they have drifted from their desired state. /// </summary> public sealed partial class Resource : pb::IMessage<Resource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Resource> _parser = new pb::MessageParser<Resource>(() => new Resource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Resource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Resource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Resource(Resource other) : this() { id_ = other.id_; switch (other.ResourceTypeCase) { case ResourceTypeOneofCase.Pkg: Pkg = other.Pkg.Clone(); break; case ResourceTypeOneofCase.Repository: Repository = other.Repository.Clone(); break; case ResourceTypeOneofCase.Exec: Exec = other.Exec.Clone(); break; case ResourceTypeOneofCase.File: File = other.File.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Resource Clone() { return new Resource(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; /// <summary> /// Required. The id of the resource with the following restrictions: /// /// * Must contain only lowercase letters, numbers, and hyphens. /// * Must start with a letter. /// * Must be between 1-63 characters. /// * Must end with a number or a letter. /// * Must be unique within the OS policy. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "pkg" field.</summary> public const int PkgFieldNumber = 2; /// <summary> /// Package resource /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource Pkg { get { return resourceTypeCase_ == ResourceTypeOneofCase.Pkg ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource) resourceType_ : null; } set { resourceType_ = value; resourceTypeCase_ = value == null ? ResourceTypeOneofCase.None : ResourceTypeOneofCase.Pkg; } } /// <summary>Field number for the "repository" field.</summary> public const int RepositoryFieldNumber = 3; /// <summary> /// Package repository resource /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource Repository { get { return resourceTypeCase_ == ResourceTypeOneofCase.Repository ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource) resourceType_ : null; } set { resourceType_ = value; resourceTypeCase_ = value == null ? ResourceTypeOneofCase.None : ResourceTypeOneofCase.Repository; } } /// <summary>Field number for the "exec" field.</summary> public const int ExecFieldNumber = 4; /// <summary> /// Exec resource /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource Exec { get { return resourceTypeCase_ == ResourceTypeOneofCase.Exec ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource) resourceType_ : null; } set { resourceType_ = value; resourceTypeCase_ = value == null ? ResourceTypeOneofCase.None : ResourceTypeOneofCase.Exec; } } /// <summary>Field number for the "file" field.</summary> public const int FileFieldNumber = 5; /// <summary> /// File resource /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource File { get { return resourceTypeCase_ == ResourceTypeOneofCase.File ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource) resourceType_ : null; } set { resourceType_ = value; resourceTypeCase_ = value == null ? ResourceTypeOneofCase.None : ResourceTypeOneofCase.File; } } private object resourceType_; /// <summary>Enum of possible cases for the "resource_type" oneof.</summary> public enum ResourceTypeOneofCase { None = 0, Pkg = 2, Repository = 3, Exec = 4, File = 5, } private ResourceTypeOneofCase resourceTypeCase_ = ResourceTypeOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceTypeOneofCase ResourceTypeCase { get { return resourceTypeCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearResourceType() { resourceTypeCase_ = ResourceTypeOneofCase.None; resourceType_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Resource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Resource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; if (!object.Equals(Pkg, other.Pkg)) return false; if (!object.Equals(Repository, other.Repository)) return false; if (!object.Equals(Exec, other.Exec)) return false; if (!object.Equals(File, other.File)) return false; if (ResourceTypeCase != other.ResourceTypeCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) hash ^= Pkg.GetHashCode(); if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) hash ^= Repository.GetHashCode(); if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) hash ^= Exec.GetHashCode(); if (resourceTypeCase_ == ResourceTypeOneofCase.File) hash ^= File.GetHashCode(); hash ^= (int) resourceTypeCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) { output.WriteRawTag(18); output.WriteMessage(Pkg); } if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) { output.WriteRawTag(26); output.WriteMessage(Repository); } if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) { output.WriteRawTag(34); output.WriteMessage(Exec); } if (resourceTypeCase_ == ResourceTypeOneofCase.File) { output.WriteRawTag(42); output.WriteMessage(File); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) { output.WriteRawTag(18); output.WriteMessage(Pkg); } if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) { output.WriteRawTag(26); output.WriteMessage(Repository); } if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) { output.WriteRawTag(34); output.WriteMessage(Exec); } if (resourceTypeCase_ == ResourceTypeOneofCase.File) { output.WriteRawTag(42); output.WriteMessage(File); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Pkg); } if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Repository); } if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Exec); } if (resourceTypeCase_ == ResourceTypeOneofCase.File) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(File); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Resource other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } switch (other.ResourceTypeCase) { case ResourceTypeOneofCase.Pkg: if (Pkg == null) { Pkg = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource(); } Pkg.MergeFrom(other.Pkg); break; case ResourceTypeOneofCase.Repository: if (Repository == null) { Repository = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource(); } Repository.MergeFrom(other.Repository); break; case ResourceTypeOneofCase.Exec: if (Exec == null) { Exec = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource(); } Exec.MergeFrom(other.Exec); break; case ResourceTypeOneofCase.File: if (File == null) { File = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource(); } File.MergeFrom(other.File); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) { subBuilder.MergeFrom(Pkg); } input.ReadMessage(subBuilder); Pkg = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) { subBuilder.MergeFrom(Repository); } input.ReadMessage(subBuilder); Repository = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) { subBuilder.MergeFrom(Exec); } input.ReadMessage(subBuilder); Exec = subBuilder; break; } case 42: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Id = input.ReadString(); break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Pkg) { subBuilder.MergeFrom(Pkg); } input.ReadMessage(subBuilder); Pkg = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Repository) { subBuilder.MergeFrom(Repository); } input.ReadMessage(subBuilder); Repository = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.Exec) { subBuilder.MergeFrom(Exec); } input.ReadMessage(subBuilder); Exec = subBuilder; break; } case 42: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource(); if (resourceTypeCase_ == ResourceTypeOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the Resource message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// A remote or local file. /// </summary> public sealed partial class File : pb::IMessage<File> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<File> _parser = new pb::MessageParser<File>(() => new File()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<File> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public File() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public File(File other) : this() { allowInsecure_ = other.allowInsecure_; switch (other.TypeCase) { case TypeOneofCase.Remote: Remote = other.Remote.Clone(); break; case TypeOneofCase.Gcs: Gcs = other.Gcs.Clone(); break; case TypeOneofCase.LocalPath: LocalPath = other.LocalPath; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public File Clone() { return new File(this); } /// <summary>Field number for the "remote" field.</summary> public const int RemoteFieldNumber = 1; /// <summary> /// A generic remote file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote Remote { get { return typeCase_ == TypeOneofCase.Remote ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote) type_ : null; } set { type_ = value; typeCase_ = value == null ? TypeOneofCase.None : TypeOneofCase.Remote; } } /// <summary>Field number for the "gcs" field.</summary> public const int GcsFieldNumber = 2; /// <summary> /// A Cloud Storage object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs Gcs { get { return typeCase_ == TypeOneofCase.Gcs ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs) type_ : null; } set { type_ = value; typeCase_ = value == null ? TypeOneofCase.None : TypeOneofCase.Gcs; } } /// <summary>Field number for the "local_path" field.</summary> public const int LocalPathFieldNumber = 3; /// <summary> /// A local path within the VM to use. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string LocalPath { get { return typeCase_ == TypeOneofCase.LocalPath ? (string) type_ : ""; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); typeCase_ = TypeOneofCase.LocalPath; } } /// <summary>Field number for the "allow_insecure" field.</summary> public const int AllowInsecureFieldNumber = 4; private bool allowInsecure_; /// <summary> /// Defaults to false. When false, files are subject to validations /// based on the file type: /// /// Remote: A checksum must be specified. /// Cloud Storage: An object generation number must be specified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool AllowInsecure { get { return allowInsecure_; } set { allowInsecure_ = value; } } private object type_; /// <summary>Enum of possible cases for the "type" oneof.</summary> public enum TypeOneofCase { None = 0, Remote = 1, Gcs = 2, LocalPath = 3, } private TypeOneofCase typeCase_ = TypeOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public TypeOneofCase TypeCase { get { return typeCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearType() { typeCase_ = TypeOneofCase.None; type_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as File); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(File other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Remote, other.Remote)) return false; if (!object.Equals(Gcs, other.Gcs)) return false; if (LocalPath != other.LocalPath) return false; if (AllowInsecure != other.AllowInsecure) return false; if (TypeCase != other.TypeCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (typeCase_ == TypeOneofCase.Remote) hash ^= Remote.GetHashCode(); if (typeCase_ == TypeOneofCase.Gcs) hash ^= Gcs.GetHashCode(); if (typeCase_ == TypeOneofCase.LocalPath) hash ^= LocalPath.GetHashCode(); if (AllowInsecure != false) hash ^= AllowInsecure.GetHashCode(); hash ^= (int) typeCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (typeCase_ == TypeOneofCase.Remote) { output.WriteRawTag(10); output.WriteMessage(Remote); } if (typeCase_ == TypeOneofCase.Gcs) { output.WriteRawTag(18); output.WriteMessage(Gcs); } if (typeCase_ == TypeOneofCase.LocalPath) { output.WriteRawTag(26); output.WriteString(LocalPath); } if (AllowInsecure != false) { output.WriteRawTag(32); output.WriteBool(AllowInsecure); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (typeCase_ == TypeOneofCase.Remote) { output.WriteRawTag(10); output.WriteMessage(Remote); } if (typeCase_ == TypeOneofCase.Gcs) { output.WriteRawTag(18); output.WriteMessage(Gcs); } if (typeCase_ == TypeOneofCase.LocalPath) { output.WriteRawTag(26); output.WriteString(LocalPath); } if (AllowInsecure != false) { output.WriteRawTag(32); output.WriteBool(AllowInsecure); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (typeCase_ == TypeOneofCase.Remote) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Remote); } if (typeCase_ == TypeOneofCase.Gcs) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Gcs); } if (typeCase_ == TypeOneofCase.LocalPath) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LocalPath); } if (AllowInsecure != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(File other) { if (other == null) { return; } if (other.AllowInsecure != false) { AllowInsecure = other.AllowInsecure; } switch (other.TypeCase) { case TypeOneofCase.Remote: if (Remote == null) { Remote = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote(); } Remote.MergeFrom(other.Remote); break; case TypeOneofCase.Gcs: if (Gcs == null) { Gcs = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs(); } Gcs.MergeFrom(other.Gcs); break; case TypeOneofCase.LocalPath: LocalPath = other.LocalPath; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote(); if (typeCase_ == TypeOneofCase.Remote) { subBuilder.MergeFrom(Remote); } input.ReadMessage(subBuilder); Remote = subBuilder; break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs(); if (typeCase_ == TypeOneofCase.Gcs) { subBuilder.MergeFrom(Gcs); } input.ReadMessage(subBuilder); Gcs = subBuilder; break; } case 26: { LocalPath = input.ReadString(); break; } case 32: { AllowInsecure = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Remote(); if (typeCase_ == TypeOneofCase.Remote) { subBuilder.MergeFrom(Remote); } input.ReadMessage(subBuilder); Remote = subBuilder; break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Types.Gcs(); if (typeCase_ == TypeOneofCase.Gcs) { subBuilder.MergeFrom(Gcs); } input.ReadMessage(subBuilder); Gcs = subBuilder; break; } case 26: { LocalPath = input.ReadString(); break; } case 32: { AllowInsecure = input.ReadBool(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the File message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Specifies a file available via some URI. /// </summary> public sealed partial class Remote : pb::IMessage<Remote> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Remote> _parser = new pb::MessageParser<Remote>(() => new Remote()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Remote> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Remote() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Remote(Remote other) : this() { uri_ = other.uri_; sha256Checksum_ = other.sha256Checksum_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Remote Clone() { return new Remote(this); } /// <summary>Field number for the "uri" field.</summary> public const int UriFieldNumber = 1; private string uri_ = ""; /// <summary> /// Required. URI from which to fetch the object. It should contain both the /// protocol and path following the format `{protocol}://{location}`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Uri { get { return uri_; } set { uri_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "sha256_checksum" field.</summary> public const int Sha256ChecksumFieldNumber = 2; private string sha256Checksum_ = ""; /// <summary> /// SHA256 checksum of the remote file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Sha256Checksum { get { return sha256Checksum_; } set { sha256Checksum_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Remote); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Remote other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Uri != other.Uri) return false; if (Sha256Checksum != other.Sha256Checksum) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Uri.Length != 0) hash ^= Uri.GetHashCode(); if (Sha256Checksum.Length != 0) hash ^= Sha256Checksum.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Uri.Length != 0) { output.WriteRawTag(10); output.WriteString(Uri); } if (Sha256Checksum.Length != 0) { output.WriteRawTag(18); output.WriteString(Sha256Checksum); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Uri.Length != 0) { output.WriteRawTag(10); output.WriteString(Uri); } if (Sha256Checksum.Length != 0) { output.WriteRawTag(18); output.WriteString(Sha256Checksum); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Uri.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Uri); } if (Sha256Checksum.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Sha256Checksum); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Remote other) { if (other == null) { return; } if (other.Uri.Length != 0) { Uri = other.Uri; } if (other.Sha256Checksum.Length != 0) { Sha256Checksum = other.Sha256Checksum; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Uri = input.ReadString(); break; } case 18: { Sha256Checksum = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Uri = input.ReadString(); break; } case 18: { Sha256Checksum = input.ReadString(); break; } } } } #endif } /// <summary> /// Specifies a file available as a Cloud Storage Object. /// </summary> public sealed partial class Gcs : pb::IMessage<Gcs> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Gcs> _parser = new pb::MessageParser<Gcs>(() => new Gcs()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Gcs> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Gcs() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Gcs(Gcs other) : this() { bucket_ = other.bucket_; object_ = other.object_; generation_ = other.generation_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Gcs Clone() { return new Gcs(this); } /// <summary>Field number for the "bucket" field.</summary> public const int BucketFieldNumber = 1; private string bucket_ = ""; /// <summary> /// Required. Bucket of the Cloud Storage object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Bucket { get { return bucket_; } set { bucket_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "object" field.</summary> public const int ObjectFieldNumber = 2; private string object_ = ""; /// <summary> /// Required. Name of the Cloud Storage object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Object { get { return object_; } set { object_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "generation" field.</summary> public const int GenerationFieldNumber = 3; private long generation_; /// <summary> /// Generation number of the Cloud Storage object. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long Generation { get { return generation_; } set { generation_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Gcs); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Gcs other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Bucket != other.Bucket) return false; if (Object != other.Object) return false; if (Generation != other.Generation) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Bucket.Length != 0) hash ^= Bucket.GetHashCode(); if (Object.Length != 0) hash ^= Object.GetHashCode(); if (Generation != 0L) hash ^= Generation.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Bucket.Length != 0) { output.WriteRawTag(10); output.WriteString(Bucket); } if (Object.Length != 0) { output.WriteRawTag(18); output.WriteString(Object); } if (Generation != 0L) { output.WriteRawTag(24); output.WriteInt64(Generation); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Bucket.Length != 0) { output.WriteRawTag(10); output.WriteString(Bucket); } if (Object.Length != 0) { output.WriteRawTag(18); output.WriteString(Object); } if (Generation != 0L) { output.WriteRawTag(24); output.WriteInt64(Generation); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Bucket.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Bucket); } if (Object.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Object); } if (Generation != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Generation); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Gcs other) { if (other == null) { return; } if (other.Bucket.Length != 0) { Bucket = other.Bucket; } if (other.Object.Length != 0) { Object = other.Object; } if (other.Generation != 0L) { Generation = other.Generation; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Bucket = input.ReadString(); break; } case 18: { Object = input.ReadString(); break; } case 24: { Generation = input.ReadInt64(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Bucket = input.ReadString(); break; } case 18: { Object = input.ReadString(); break; } case 24: { Generation = input.ReadInt64(); break; } } } } #endif } } #endregion } /// <summary> /// A resource that manages a system package. /// </summary> public sealed partial class PackageResource : pb::IMessage<PackageResource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<PackageResource> _parser = new pb::MessageParser<PackageResource>(() => new PackageResource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<PackageResource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public PackageResource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public PackageResource(PackageResource other) : this() { desiredState_ = other.desiredState_; switch (other.SystemPackageCase) { case SystemPackageOneofCase.Apt: Apt = other.Apt.Clone(); break; case SystemPackageOneofCase.Deb: Deb = other.Deb.Clone(); break; case SystemPackageOneofCase.Yum: Yum = other.Yum.Clone(); break; case SystemPackageOneofCase.Zypper: Zypper = other.Zypper.Clone(); break; case SystemPackageOneofCase.Rpm: Rpm = other.Rpm.Clone(); break; case SystemPackageOneofCase.Googet: Googet = other.Googet.Clone(); break; case SystemPackageOneofCase.Msi: Msi = other.Msi.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public PackageResource Clone() { return new PackageResource(this); } /// <summary>Field number for the "desired_state" field.</summary> public const int DesiredStateFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState desiredState_ = global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified; /// <summary> /// Required. The desired state the agent should maintain for this package. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState DesiredState { get { return desiredState_; } set { desiredState_ = value; } } /// <summary>Field number for the "apt" field.</summary> public const int AptFieldNumber = 2; /// <summary> /// A package managed by Apt. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT Apt { get { return systemPackageCase_ == SystemPackageOneofCase.Apt ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Apt; } } /// <summary>Field number for the "deb" field.</summary> public const int DebFieldNumber = 3; /// <summary> /// A deb package file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb Deb { get { return systemPackageCase_ == SystemPackageOneofCase.Deb ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Deb; } } /// <summary>Field number for the "yum" field.</summary> public const int YumFieldNumber = 4; /// <summary> /// A package managed by YUM. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM Yum { get { return systemPackageCase_ == SystemPackageOneofCase.Yum ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Yum; } } /// <summary>Field number for the "zypper" field.</summary> public const int ZypperFieldNumber = 5; /// <summary> /// A package managed by Zypper. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper Zypper { get { return systemPackageCase_ == SystemPackageOneofCase.Zypper ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Zypper; } } /// <summary>Field number for the "rpm" field.</summary> public const int RpmFieldNumber = 6; /// <summary> /// An rpm package file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM Rpm { get { return systemPackageCase_ == SystemPackageOneofCase.Rpm ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Rpm; } } /// <summary>Field number for the "googet" field.</summary> public const int GoogetFieldNumber = 7; /// <summary> /// A package managed by GooGet. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet Googet { get { return systemPackageCase_ == SystemPackageOneofCase.Googet ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Googet; } } /// <summary>Field number for the "msi" field.</summary> public const int MsiFieldNumber = 8; /// <summary> /// An MSI package. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI Msi { get { return systemPackageCase_ == SystemPackageOneofCase.Msi ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI) systemPackage_ : null; } set { systemPackage_ = value; systemPackageCase_ = value == null ? SystemPackageOneofCase.None : SystemPackageOneofCase.Msi; } } private object systemPackage_; /// <summary>Enum of possible cases for the "system_package" oneof.</summary> public enum SystemPackageOneofCase { None = 0, Apt = 2, Deb = 3, Yum = 4, Zypper = 5, Rpm = 6, Googet = 7, Msi = 8, } private SystemPackageOneofCase systemPackageCase_ = SystemPackageOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SystemPackageOneofCase SystemPackageCase { get { return systemPackageCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearSystemPackage() { systemPackageCase_ = SystemPackageOneofCase.None; systemPackage_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as PackageResource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(PackageResource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DesiredState != other.DesiredState) return false; if (!object.Equals(Apt, other.Apt)) return false; if (!object.Equals(Deb, other.Deb)) return false; if (!object.Equals(Yum, other.Yum)) return false; if (!object.Equals(Zypper, other.Zypper)) return false; if (!object.Equals(Rpm, other.Rpm)) return false; if (!object.Equals(Googet, other.Googet)) return false; if (!object.Equals(Msi, other.Msi)) return false; if (SystemPackageCase != other.SystemPackageCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (DesiredState != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified) hash ^= DesiredState.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Apt) hash ^= Apt.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Deb) hash ^= Deb.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Yum) hash ^= Yum.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Zypper) hash ^= Zypper.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Rpm) hash ^= Rpm.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Googet) hash ^= Googet.GetHashCode(); if (systemPackageCase_ == SystemPackageOneofCase.Msi) hash ^= Msi.GetHashCode(); hash ^= (int) systemPackageCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (DesiredState != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) DesiredState); } if (systemPackageCase_ == SystemPackageOneofCase.Apt) { output.WriteRawTag(18); output.WriteMessage(Apt); } if (systemPackageCase_ == SystemPackageOneofCase.Deb) { output.WriteRawTag(26); output.WriteMessage(Deb); } if (systemPackageCase_ == SystemPackageOneofCase.Yum) { output.WriteRawTag(34); output.WriteMessage(Yum); } if (systemPackageCase_ == SystemPackageOneofCase.Zypper) { output.WriteRawTag(42); output.WriteMessage(Zypper); } if (systemPackageCase_ == SystemPackageOneofCase.Rpm) { output.WriteRawTag(50); output.WriteMessage(Rpm); } if (systemPackageCase_ == SystemPackageOneofCase.Googet) { output.WriteRawTag(58); output.WriteMessage(Googet); } if (systemPackageCase_ == SystemPackageOneofCase.Msi) { output.WriteRawTag(66); output.WriteMessage(Msi); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (DesiredState != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) DesiredState); } if (systemPackageCase_ == SystemPackageOneofCase.Apt) { output.WriteRawTag(18); output.WriteMessage(Apt); } if (systemPackageCase_ == SystemPackageOneofCase.Deb) { output.WriteRawTag(26); output.WriteMessage(Deb); } if (systemPackageCase_ == SystemPackageOneofCase.Yum) { output.WriteRawTag(34); output.WriteMessage(Yum); } if (systemPackageCase_ == SystemPackageOneofCase.Zypper) { output.WriteRawTag(42); output.WriteMessage(Zypper); } if (systemPackageCase_ == SystemPackageOneofCase.Rpm) { output.WriteRawTag(50); output.WriteMessage(Rpm); } if (systemPackageCase_ == SystemPackageOneofCase.Googet) { output.WriteRawTag(58); output.WriteMessage(Googet); } if (systemPackageCase_ == SystemPackageOneofCase.Msi) { output.WriteRawTag(66); output.WriteMessage(Msi); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (DesiredState != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DesiredState); } if (systemPackageCase_ == SystemPackageOneofCase.Apt) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Apt); } if (systemPackageCase_ == SystemPackageOneofCase.Deb) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Deb); } if (systemPackageCase_ == SystemPackageOneofCase.Yum) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Yum); } if (systemPackageCase_ == SystemPackageOneofCase.Zypper) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Zypper); } if (systemPackageCase_ == SystemPackageOneofCase.Rpm) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Rpm); } if (systemPackageCase_ == SystemPackageOneofCase.Googet) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Googet); } if (systemPackageCase_ == SystemPackageOneofCase.Msi) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Msi); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(PackageResource other) { if (other == null) { return; } if (other.DesiredState != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState.Unspecified) { DesiredState = other.DesiredState; } switch (other.SystemPackageCase) { case SystemPackageOneofCase.Apt: if (Apt == null) { Apt = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT(); } Apt.MergeFrom(other.Apt); break; case SystemPackageOneofCase.Deb: if (Deb == null) { Deb = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb(); } Deb.MergeFrom(other.Deb); break; case SystemPackageOneofCase.Yum: if (Yum == null) { Yum = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM(); } Yum.MergeFrom(other.Yum); break; case SystemPackageOneofCase.Zypper: if (Zypper == null) { Zypper = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper(); } Zypper.MergeFrom(other.Zypper); break; case SystemPackageOneofCase.Rpm: if (Rpm == null) { Rpm = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM(); } Rpm.MergeFrom(other.Rpm); break; case SystemPackageOneofCase.Googet: if (Googet == null) { Googet = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet(); } Googet.MergeFrom(other.Googet); break; case SystemPackageOneofCase.Msi: if (Msi == null) { Msi = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI(); } Msi.MergeFrom(other.Msi); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { DesiredState = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState) input.ReadEnum(); break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT(); if (systemPackageCase_ == SystemPackageOneofCase.Apt) { subBuilder.MergeFrom(Apt); } input.ReadMessage(subBuilder); Apt = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb(); if (systemPackageCase_ == SystemPackageOneofCase.Deb) { subBuilder.MergeFrom(Deb); } input.ReadMessage(subBuilder); Deb = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM(); if (systemPackageCase_ == SystemPackageOneofCase.Yum) { subBuilder.MergeFrom(Yum); } input.ReadMessage(subBuilder); Yum = subBuilder; break; } case 42: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper(); if (systemPackageCase_ == SystemPackageOneofCase.Zypper) { subBuilder.MergeFrom(Zypper); } input.ReadMessage(subBuilder); Zypper = subBuilder; break; } case 50: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM(); if (systemPackageCase_ == SystemPackageOneofCase.Rpm) { subBuilder.MergeFrom(Rpm); } input.ReadMessage(subBuilder); Rpm = subBuilder; break; } case 58: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet(); if (systemPackageCase_ == SystemPackageOneofCase.Googet) { subBuilder.MergeFrom(Googet); } input.ReadMessage(subBuilder); Googet = subBuilder; break; } case 66: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI(); if (systemPackageCase_ == SystemPackageOneofCase.Msi) { subBuilder.MergeFrom(Msi); } input.ReadMessage(subBuilder); Msi = subBuilder; break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { DesiredState = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.DesiredState) input.ReadEnum(); break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.APT(); if (systemPackageCase_ == SystemPackageOneofCase.Apt) { subBuilder.MergeFrom(Apt); } input.ReadMessage(subBuilder); Apt = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Deb(); if (systemPackageCase_ == SystemPackageOneofCase.Deb) { subBuilder.MergeFrom(Deb); } input.ReadMessage(subBuilder); Deb = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.YUM(); if (systemPackageCase_ == SystemPackageOneofCase.Yum) { subBuilder.MergeFrom(Yum); } input.ReadMessage(subBuilder); Yum = subBuilder; break; } case 42: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.Zypper(); if (systemPackageCase_ == SystemPackageOneofCase.Zypper) { subBuilder.MergeFrom(Zypper); } input.ReadMessage(subBuilder); Zypper = subBuilder; break; } case 50: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.RPM(); if (systemPackageCase_ == SystemPackageOneofCase.Rpm) { subBuilder.MergeFrom(Rpm); } input.ReadMessage(subBuilder); Rpm = subBuilder; break; } case 58: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.GooGet(); if (systemPackageCase_ == SystemPackageOneofCase.Googet) { subBuilder.MergeFrom(Googet); } input.ReadMessage(subBuilder); Googet = subBuilder; break; } case 66: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Types.MSI(); if (systemPackageCase_ == SystemPackageOneofCase.Msi) { subBuilder.MergeFrom(Msi); } input.ReadMessage(subBuilder); Msi = subBuilder; break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the PackageResource message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// The desired state that the OS Config agent maintains on the VM. /// </summary> public enum DesiredState { /// <summary> /// Unspecified is invalid. /// </summary> [pbr::OriginalName("DESIRED_STATE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Ensure that the package is installed. /// </summary> [pbr::OriginalName("INSTALLED")] Installed = 1, /// <summary> /// The agent ensures that the package is not installed and /// uninstalls it if detected. /// </summary> [pbr::OriginalName("REMOVED")] Removed = 2, } /// <summary> /// A deb package file. dpkg packages only support INSTALLED state. /// </summary> public sealed partial class Deb : pb::IMessage<Deb> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Deb> _parser = new pb::MessageParser<Deb>(() => new Deb()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Deb> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Deb() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Deb(Deb other) : this() { source_ = other.source_ != null ? other.source_.Clone() : null; pullDeps_ = other.pullDeps_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Deb Clone() { return new Deb(this); } /// <summary>Field number for the "source" field.</summary> public const int SourceFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File source_; /// <summary> /// Required. A deb package. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File Source { get { return source_; } set { source_ = value; } } /// <summary>Field number for the "pull_deps" field.</summary> public const int PullDepsFieldNumber = 2; private bool pullDeps_; /// <summary> /// Whether dependencies should also be installed. /// - install when false: `dpkg -i package` /// - install when true: `apt-get update &amp;&amp; apt-get -y install /// package.deb` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool PullDeps { get { return pullDeps_; } set { pullDeps_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Deb); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Deb other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Source, other.Source)) return false; if (PullDeps != other.PullDeps) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (source_ != null) hash ^= Source.GetHashCode(); if (PullDeps != false) hash ^= PullDeps.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } if (PullDeps != false) { output.WriteRawTag(16); output.WriteBool(PullDeps); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } if (PullDeps != false) { output.WriteRawTag(16); output.WriteBool(PullDeps); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (source_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Source); } if (PullDeps != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Deb other) { if (other == null) { return; } if (other.source_ != null) { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } Source.MergeFrom(other.Source); } if (other.PullDeps != false) { PullDeps = other.PullDeps; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 16: { PullDeps = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 16: { PullDeps = input.ReadBool(); break; } } } } #endif } /// <summary> /// A package managed by APT. /// - install: `apt-get update &amp;&amp; apt-get -y install [name]` /// - remove: `apt-get -y remove [name]` /// </summary> public sealed partial class APT : pb::IMessage<APT> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<APT> _parser = new pb::MessageParser<APT>(() => new APT()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<APT> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public APT() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public APT(APT other) : this() { name_ = other.name_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public APT Clone() { return new APT(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. Package name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as APT); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(APT other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(APT other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } } } } #endif } /// <summary> /// An RPM package file. RPM packages only support INSTALLED state. /// </summary> public sealed partial class RPM : pb::IMessage<RPM> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RPM> _parser = new pb::MessageParser<RPM>(() => new RPM()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RPM> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RPM() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RPM(RPM other) : this() { source_ = other.source_ != null ? other.source_.Clone() : null; pullDeps_ = other.pullDeps_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RPM Clone() { return new RPM(this); } /// <summary>Field number for the "source" field.</summary> public const int SourceFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File source_; /// <summary> /// Required. An rpm package. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File Source { get { return source_; } set { source_ = value; } } /// <summary>Field number for the "pull_deps" field.</summary> public const int PullDepsFieldNumber = 2; private bool pullDeps_; /// <summary> /// Whether dependencies should also be installed. /// - install when false: `rpm --upgrade --replacepkgs package.rpm` /// - install when true: `yum -y install package.rpm` or /// `zypper -y install package.rpm` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool PullDeps { get { return pullDeps_; } set { pullDeps_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RPM); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RPM other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Source, other.Source)) return false; if (PullDeps != other.PullDeps) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (source_ != null) hash ^= Source.GetHashCode(); if (PullDeps != false) hash ^= PullDeps.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } if (PullDeps != false) { output.WriteRawTag(16); output.WriteBool(PullDeps); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } if (PullDeps != false) { output.WriteRawTag(16); output.WriteBool(PullDeps); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (source_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Source); } if (PullDeps != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RPM other) { if (other == null) { return; } if (other.source_ != null) { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } Source.MergeFrom(other.Source); } if (other.PullDeps != false) { PullDeps = other.PullDeps; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 16: { PullDeps = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 16: { PullDeps = input.ReadBool(); break; } } } } #endif } /// <summary> /// A package managed by YUM. /// - install: `yum -y install package` /// - remove: `yum -y remove package` /// </summary> public sealed partial class YUM : pb::IMessage<YUM> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<YUM> _parser = new pb::MessageParser<YUM>(() => new YUM()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<YUM> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YUM() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YUM(YUM other) : this() { name_ = other.name_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YUM Clone() { return new YUM(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. Package name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as YUM); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(YUM other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(YUM other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } } } } #endif } /// <summary> /// A package managed by Zypper. /// - install: `zypper -y install package` /// - remove: `zypper -y rm package` /// </summary> public sealed partial class Zypper : pb::IMessage<Zypper> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Zypper> _parser = new pb::MessageParser<Zypper>(() => new Zypper()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Zypper> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Zypper() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Zypper(Zypper other) : this() { name_ = other.name_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Zypper Clone() { return new Zypper(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. Package name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Zypper); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Zypper other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Zypper other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } } } } #endif } /// <summary> /// A package managed by GooGet. /// - install: `googet -noconfirm install package` /// - remove: `googet -noconfirm remove package` /// </summary> public sealed partial class GooGet : pb::IMessage<GooGet> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GooGet> _parser = new pb::MessageParser<GooGet>(() => new GooGet()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<GooGet> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooGet() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooGet(GooGet other) : this() { name_ = other.name_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooGet Clone() { return new GooGet(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. Package name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as GooGet); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(GooGet other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(GooGet other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } } } } #endif } /// <summary> /// An MSI package. MSI packages only support INSTALLED state. /// </summary> public sealed partial class MSI : pb::IMessage<MSI> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MSI> _parser = new pb::MessageParser<MSI>(() => new MSI()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<MSI> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.PackageResource.Descriptor.NestedTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MSI() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MSI(MSI other) : this() { source_ = other.source_ != null ? other.source_.Clone() : null; properties_ = other.properties_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MSI Clone() { return new MSI(this); } /// <summary>Field number for the "source" field.</summary> public const int SourceFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File source_; /// <summary> /// Required. The MSI package. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File Source { get { return source_; } set { source_ = value; } } /// <summary>Field number for the "properties" field.</summary> public const int PropertiesFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_properties_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> properties_ = new pbc::RepeatedField<string>(); /// <summary> /// Additional properties to use during installation. /// This should be in the format of Property=Setting. /// Appended to the defaults of `ACTION=INSTALL /// REBOOT=ReallySuppress`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Properties { get { return properties_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as MSI); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(MSI other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Source, other.Source)) return false; if(!properties_.Equals(other.properties_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (source_ != null) hash ^= Source.GetHashCode(); hash ^= properties_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } properties_.WriteTo(output, _repeated_properties_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (source_ != null) { output.WriteRawTag(10); output.WriteMessage(Source); } properties_.WriteTo(ref output, _repeated_properties_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (source_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Source); } size += properties_.CalculateSize(_repeated_properties_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(MSI other) { if (other == null) { return; } if (other.source_ != null) { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } Source.MergeFrom(other.Source); } properties_.Add(other.properties_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 18: { properties_.AddEntriesFrom(input, _repeated_properties_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (source_ == null) { Source = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } input.ReadMessage(Source); break; } case 18: { properties_.AddEntriesFrom(ref input, _repeated_properties_codec); break; } } } } #endif } } #endregion } /// <summary> /// A resource that manages a package repository. /// </summary> public sealed partial class RepositoryResource : pb::IMessage<RepositoryResource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RepositoryResource> _parser = new pb::MessageParser<RepositoryResource>(() => new RepositoryResource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RepositoryResource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Descriptor.NestedTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RepositoryResource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RepositoryResource(RepositoryResource other) : this() { switch (other.RepositoryCase) { case RepositoryOneofCase.Apt: Apt = other.Apt.Clone(); break; case RepositoryOneofCase.Yum: Yum = other.Yum.Clone(); break; case RepositoryOneofCase.Zypper: Zypper = other.Zypper.Clone(); break; case RepositoryOneofCase.Goo: Goo = other.Goo.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RepositoryResource Clone() { return new RepositoryResource(this); } /// <summary>Field number for the "apt" field.</summary> public const int AptFieldNumber = 1; /// <summary> /// An Apt Repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository Apt { get { return repositoryCase_ == RepositoryOneofCase.Apt ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository) repository_ : null; } set { repository_ = value; repositoryCase_ = value == null ? RepositoryOneofCase.None : RepositoryOneofCase.Apt; } } /// <summary>Field number for the "yum" field.</summary> public const int YumFieldNumber = 2; /// <summary> /// A Yum Repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository Yum { get { return repositoryCase_ == RepositoryOneofCase.Yum ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository) repository_ : null; } set { repository_ = value; repositoryCase_ = value == null ? RepositoryOneofCase.None : RepositoryOneofCase.Yum; } } /// <summary>Field number for the "zypper" field.</summary> public const int ZypperFieldNumber = 3; /// <summary> /// A Zypper Repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository Zypper { get { return repositoryCase_ == RepositoryOneofCase.Zypper ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository) repository_ : null; } set { repository_ = value; repositoryCase_ = value == null ? RepositoryOneofCase.None : RepositoryOneofCase.Zypper; } } /// <summary>Field number for the "goo" field.</summary> public const int GooFieldNumber = 4; /// <summary> /// A Goo Repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository Goo { get { return repositoryCase_ == RepositoryOneofCase.Goo ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository) repository_ : null; } set { repository_ = value; repositoryCase_ = value == null ? RepositoryOneofCase.None : RepositoryOneofCase.Goo; } } private object repository_; /// <summary>Enum of possible cases for the "repository" oneof.</summary> public enum RepositoryOneofCase { None = 0, Apt = 1, Yum = 2, Zypper = 3, Goo = 4, } private RepositoryOneofCase repositoryCase_ = RepositoryOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RepositoryOneofCase RepositoryCase { get { return repositoryCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearRepository() { repositoryCase_ = RepositoryOneofCase.None; repository_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RepositoryResource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RepositoryResource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Apt, other.Apt)) return false; if (!object.Equals(Yum, other.Yum)) return false; if (!object.Equals(Zypper, other.Zypper)) return false; if (!object.Equals(Goo, other.Goo)) return false; if (RepositoryCase != other.RepositoryCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (repositoryCase_ == RepositoryOneofCase.Apt) hash ^= Apt.GetHashCode(); if (repositoryCase_ == RepositoryOneofCase.Yum) hash ^= Yum.GetHashCode(); if (repositoryCase_ == RepositoryOneofCase.Zypper) hash ^= Zypper.GetHashCode(); if (repositoryCase_ == RepositoryOneofCase.Goo) hash ^= Goo.GetHashCode(); hash ^= (int) repositoryCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (repositoryCase_ == RepositoryOneofCase.Apt) { output.WriteRawTag(10); output.WriteMessage(Apt); } if (repositoryCase_ == RepositoryOneofCase.Yum) { output.WriteRawTag(18); output.WriteMessage(Yum); } if (repositoryCase_ == RepositoryOneofCase.Zypper) { output.WriteRawTag(26); output.WriteMessage(Zypper); } if (repositoryCase_ == RepositoryOneofCase.Goo) { output.WriteRawTag(34); output.WriteMessage(Goo); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (repositoryCase_ == RepositoryOneofCase.Apt) { output.WriteRawTag(10); output.WriteMessage(Apt); } if (repositoryCase_ == RepositoryOneofCase.Yum) { output.WriteRawTag(18); output.WriteMessage(Yum); } if (repositoryCase_ == RepositoryOneofCase.Zypper) { output.WriteRawTag(26); output.WriteMessage(Zypper); } if (repositoryCase_ == RepositoryOneofCase.Goo) { output.WriteRawTag(34); output.WriteMessage(Goo); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (repositoryCase_ == RepositoryOneofCase.Apt) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Apt); } if (repositoryCase_ == RepositoryOneofCase.Yum) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Yum); } if (repositoryCase_ == RepositoryOneofCase.Zypper) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Zypper); } if (repositoryCase_ == RepositoryOneofCase.Goo) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Goo); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RepositoryResource other) { if (other == null) { return; } switch (other.RepositoryCase) { case RepositoryOneofCase.Apt: if (Apt == null) { Apt = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository(); } Apt.MergeFrom(other.Apt); break; case RepositoryOneofCase.Yum: if (Yum == null) { Yum = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository(); } Yum.MergeFrom(other.Yum); break; case RepositoryOneofCase.Zypper: if (Zypper == null) { Zypper = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository(); } Zypper.MergeFrom(other.Zypper); break; case RepositoryOneofCase.Goo: if (Goo == null) { Goo = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository(); } Goo.MergeFrom(other.Goo); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository(); if (repositoryCase_ == RepositoryOneofCase.Apt) { subBuilder.MergeFrom(Apt); } input.ReadMessage(subBuilder); Apt = subBuilder; break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository(); if (repositoryCase_ == RepositoryOneofCase.Yum) { subBuilder.MergeFrom(Yum); } input.ReadMessage(subBuilder); Yum = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository(); if (repositoryCase_ == RepositoryOneofCase.Zypper) { subBuilder.MergeFrom(Zypper); } input.ReadMessage(subBuilder); Zypper = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository(); if (repositoryCase_ == RepositoryOneofCase.Goo) { subBuilder.MergeFrom(Goo); } input.ReadMessage(subBuilder); Goo = subBuilder; break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository(); if (repositoryCase_ == RepositoryOneofCase.Apt) { subBuilder.MergeFrom(Apt); } input.ReadMessage(subBuilder); Apt = subBuilder; break; } case 18: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.YumRepository(); if (repositoryCase_ == RepositoryOneofCase.Yum) { subBuilder.MergeFrom(Yum); } input.ReadMessage(subBuilder); Yum = subBuilder; break; } case 26: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.ZypperRepository(); if (repositoryCase_ == RepositoryOneofCase.Zypper) { subBuilder.MergeFrom(Zypper); } input.ReadMessage(subBuilder); Zypper = subBuilder; break; } case 34: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.GooRepository(); if (repositoryCase_ == RepositoryOneofCase.Goo) { subBuilder.MergeFrom(Goo); } input.ReadMessage(subBuilder); Goo = subBuilder; break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the RepositoryResource message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Represents a single apt package repository. These will be added to /// a repo file that will be managed at /// `/etc/apt/sources.list.d/google_osconfig.list`. /// </summary> public sealed partial class AptRepository : pb::IMessage<AptRepository> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AptRepository> _parser = new pb::MessageParser<AptRepository>(() => new AptRepository()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AptRepository> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AptRepository() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AptRepository(AptRepository other) : this() { archiveType_ = other.archiveType_; uri_ = other.uri_; distribution_ = other.distribution_; components_ = other.components_.Clone(); gpgKey_ = other.gpgKey_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AptRepository Clone() { return new AptRepository(this); } /// <summary>Field number for the "archive_type" field.</summary> public const int ArchiveTypeFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType archiveType_ = global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified; /// <summary> /// Required. Type of archive files in this repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType ArchiveType { get { return archiveType_; } set { archiveType_ = value; } } /// <summary>Field number for the "uri" field.</summary> public const int UriFieldNumber = 2; private string uri_ = ""; /// <summary> /// Required. URI for this repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Uri { get { return uri_; } set { uri_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "distribution" field.</summary> public const int DistributionFieldNumber = 3; private string distribution_ = ""; /// <summary> /// Required. Distribution of this repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Distribution { get { return distribution_; } set { distribution_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "components" field.</summary> public const int ComponentsFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_components_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> components_ = new pbc::RepeatedField<string>(); /// <summary> /// Required. List of components for this repository. Must contain at least one /// item. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Components { get { return components_; } } /// <summary>Field number for the "gpg_key" field.</summary> public const int GpgKeyFieldNumber = 5; private string gpgKey_ = ""; /// <summary> /// URI of the key file for this repository. The agent maintains a /// keyring at `/etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string GpgKey { get { return gpgKey_; } set { gpgKey_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AptRepository); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AptRepository other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ArchiveType != other.ArchiveType) return false; if (Uri != other.Uri) return false; if (Distribution != other.Distribution) return false; if(!components_.Equals(other.components_)) return false; if (GpgKey != other.GpgKey) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ArchiveType != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified) hash ^= ArchiveType.GetHashCode(); if (Uri.Length != 0) hash ^= Uri.GetHashCode(); if (Distribution.Length != 0) hash ^= Distribution.GetHashCode(); hash ^= components_.GetHashCode(); if (GpgKey.Length != 0) hash ^= GpgKey.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ArchiveType != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) ArchiveType); } if (Uri.Length != 0) { output.WriteRawTag(18); output.WriteString(Uri); } if (Distribution.Length != 0) { output.WriteRawTag(26); output.WriteString(Distribution); } components_.WriteTo(output, _repeated_components_codec); if (GpgKey.Length != 0) { output.WriteRawTag(42); output.WriteString(GpgKey); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ArchiveType != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) ArchiveType); } if (Uri.Length != 0) { output.WriteRawTag(18); output.WriteString(Uri); } if (Distribution.Length != 0) { output.WriteRawTag(26); output.WriteString(Distribution); } components_.WriteTo(ref output, _repeated_components_codec); if (GpgKey.Length != 0) { output.WriteRawTag(42); output.WriteString(GpgKey); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ArchiveType != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ArchiveType); } if (Uri.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Uri); } if (Distribution.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Distribution); } size += components_.CalculateSize(_repeated_components_codec); if (GpgKey.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GpgKey); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AptRepository other) { if (other == null) { return; } if (other.ArchiveType != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType.Unspecified) { ArchiveType = other.ArchiveType; } if (other.Uri.Length != 0) { Uri = other.Uri; } if (other.Distribution.Length != 0) { Distribution = other.Distribution; } components_.Add(other.components_); if (other.GpgKey.Length != 0) { GpgKey = other.GpgKey; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { ArchiveType = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType) input.ReadEnum(); break; } case 18: { Uri = input.ReadString(); break; } case 26: { Distribution = input.ReadString(); break; } case 34: { components_.AddEntriesFrom(input, _repeated_components_codec); break; } case 42: { GpgKey = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { ArchiveType = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Types.AptRepository.Types.ArchiveType) input.ReadEnum(); break; } case 18: { Uri = input.ReadString(); break; } case 26: { Distribution = input.ReadString(); break; } case 34: { components_.AddEntriesFrom(ref input, _repeated_components_codec); break; } case 42: { GpgKey = input.ReadString(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the AptRepository message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Type of archive. /// </summary> public enum ArchiveType { /// <summary> /// Unspecified is invalid. /// </summary> [pbr::OriginalName("ARCHIVE_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Deb indicates that the archive contains binary files. /// </summary> [pbr::OriginalName("DEB")] Deb = 1, /// <summary> /// Deb-src indicates that the archive contains source files. /// </summary> [pbr::OriginalName("DEB_SRC")] DebSrc = 2, } } #endregion } /// <summary> /// Represents a single yum package repository. These are added to a /// repo file that is managed at /// `/etc/yum.repos.d/google_osconfig.repo`. /// </summary> public sealed partial class YumRepository : pb::IMessage<YumRepository> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<YumRepository> _parser = new pb::MessageParser<YumRepository>(() => new YumRepository()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<YumRepository> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YumRepository() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YumRepository(YumRepository other) : this() { id_ = other.id_; displayName_ = other.displayName_; baseUrl_ = other.baseUrl_; gpgKeys_ = other.gpgKeys_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public YumRepository Clone() { return new YumRepository(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; /// <summary> /// Required. A one word, unique name for this repository. This is the `repo /// id` in the yum config file and also the `display_name` if /// `display_name` is omitted. This id is also used as the unique /// identifier when checking for resource conflicts. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 2; private string displayName_ = ""; /// <summary> /// The display name of the repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "base_url" field.</summary> public const int BaseUrlFieldNumber = 3; private string baseUrl_ = ""; /// <summary> /// Required. The location of the repository directory. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string BaseUrl { get { return baseUrl_; } set { baseUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "gpg_keys" field.</summary> public const int GpgKeysFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_gpgKeys_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> gpgKeys_ = new pbc::RepeatedField<string>(); /// <summary> /// URIs of GPG keys. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> GpgKeys { get { return gpgKeys_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as YumRepository); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(YumRepository other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; if (DisplayName != other.DisplayName) return false; if (BaseUrl != other.BaseUrl) return false; if(!gpgKeys_.Equals(other.gpgKeys_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode(); if (BaseUrl.Length != 0) hash ^= BaseUrl.GetHashCode(); hash ^= gpgKeys_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (BaseUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(BaseUrl); } gpgKeys_.WriteTo(output, _repeated_gpgKeys_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (BaseUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(BaseUrl); } gpgKeys_.WriteTo(ref output, _repeated_gpgKeys_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } if (BaseUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BaseUrl); } size += gpgKeys_.CalculateSize(_repeated_gpgKeys_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(YumRepository other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } if (other.BaseUrl.Length != 0) { BaseUrl = other.BaseUrl; } gpgKeys_.Add(other.gpgKeys_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { BaseUrl = input.ReadString(); break; } case 34: { gpgKeys_.AddEntriesFrom(input, _repeated_gpgKeys_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Id = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { BaseUrl = input.ReadString(); break; } case 34: { gpgKeys_.AddEntriesFrom(ref input, _repeated_gpgKeys_codec); break; } } } } #endif } /// <summary> /// Represents a single zypper package repository. These are added to a /// repo file that is managed at /// `/etc/zypp/repos.d/google_osconfig.repo`. /// </summary> public sealed partial class ZypperRepository : pb::IMessage<ZypperRepository> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ZypperRepository> _parser = new pb::MessageParser<ZypperRepository>(() => new ZypperRepository()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ZypperRepository> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Descriptor.NestedTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ZypperRepository() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ZypperRepository(ZypperRepository other) : this() { id_ = other.id_; displayName_ = other.displayName_; baseUrl_ = other.baseUrl_; gpgKeys_ = other.gpgKeys_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ZypperRepository Clone() { return new ZypperRepository(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; /// <summary> /// Required. A one word, unique name for this repository. This is the `repo /// id` in the zypper config file and also the `display_name` if /// `display_name` is omitted. This id is also used as the unique /// identifier when checking for GuestPolicy conflicts. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 2; private string displayName_ = ""; /// <summary> /// The display name of the repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "base_url" field.</summary> public const int BaseUrlFieldNumber = 3; private string baseUrl_ = ""; /// <summary> /// Required. The location of the repository directory. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string BaseUrl { get { return baseUrl_; } set { baseUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "gpg_keys" field.</summary> public const int GpgKeysFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_gpgKeys_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> gpgKeys_ = new pbc::RepeatedField<string>(); /// <summary> /// URIs of GPG keys. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> GpgKeys { get { return gpgKeys_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ZypperRepository); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ZypperRepository other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; if (DisplayName != other.DisplayName) return false; if (BaseUrl != other.BaseUrl) return false; if(!gpgKeys_.Equals(other.gpgKeys_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode(); if (BaseUrl.Length != 0) hash ^= BaseUrl.GetHashCode(); hash ^= gpgKeys_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (BaseUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(BaseUrl); } gpgKeys_.WriteTo(output, _repeated_gpgKeys_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (BaseUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(BaseUrl); } gpgKeys_.WriteTo(ref output, _repeated_gpgKeys_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } if (BaseUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BaseUrl); } size += gpgKeys_.CalculateSize(_repeated_gpgKeys_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ZypperRepository other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } if (other.BaseUrl.Length != 0) { BaseUrl = other.BaseUrl; } gpgKeys_.Add(other.gpgKeys_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { BaseUrl = input.ReadString(); break; } case 34: { gpgKeys_.AddEntriesFrom(input, _repeated_gpgKeys_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Id = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { BaseUrl = input.ReadString(); break; } case 34: { gpgKeys_.AddEntriesFrom(ref input, _repeated_gpgKeys_codec); break; } } } } #endif } /// <summary> /// Represents a Goo package repository. These are added to a repo file /// that is managed at /// `C:/ProgramData/GooGet/repos/google_osconfig.repo`. /// </summary> public sealed partial class GooRepository : pb::IMessage<GooRepository> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GooRepository> _parser = new pb::MessageParser<GooRepository>(() => new GooRepository()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<GooRepository> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.RepositoryResource.Descriptor.NestedTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooRepository() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooRepository(GooRepository other) : this() { name_ = other.name_; url_ = other.url_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GooRepository Clone() { return new GooRepository(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The name of the repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "url" field.</summary> public const int UrlFieldNumber = 2; private string url_ = ""; /// <summary> /// Required. The url of the repository. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Url { get { return url_; } set { url_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as GooRepository); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(GooRepository other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Url != other.Url) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Url.Length != 0) hash ^= Url.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Url.Length != 0) { output.WriteRawTag(18); output.WriteString(Url); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Url.Length != 0) { output.WriteRawTag(18); output.WriteString(Url); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Url.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Url); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(GooRepository other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Url.Length != 0) { Url = other.Url; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 18: { Url = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 18: { Url = input.ReadString(); break; } } } } #endif } } #endregion } /// <summary> /// A resource that allows executing scripts on the VM. /// /// The `ExecResource` has 2 stages: `validate` and `enforce` and both stages /// accept a script as an argument to execute. /// /// When the `ExecResource` is applied by the agent, it first executes the /// script in the `validate` stage. The `validate` stage can signal that the /// `ExecResource` is already in the desired state by returning an exit code /// of `100`. If the `ExecResource` is not in the desired state, it should /// return an exit code of `101`. Any other exit code returned by this stage /// is considered an error. /// /// If the `ExecResource` is not in the desired state based on the exit code /// from the `validate` stage, the agent proceeds to execute the script from /// the `enforce` stage. If the `ExecResource` is already in the desired /// state, the `enforce` stage will not be run. /// Similar to `validate` stage, the `enforce` stage should return an exit /// code of `100` to indicate that the resource in now in its desired state. /// Any other exit code is considered an error. /// /// NOTE: An exit code of `100` was chosen over `0` (and `101` vs `1`) to /// have an explicit indicator of `in desired state`, `not in desired state` /// and errors. Because, for example, Powershell will always return an exit /// code of `0` unless an `exit` statement is provided in the script. So, for /// reasons of consistency and being explicit, exit codes `100` and `101` /// were chosen. /// </summary> public sealed partial class ExecResource : pb::IMessage<ExecResource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ExecResource> _parser = new pb::MessageParser<ExecResource>(() => new ExecResource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ExecResource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Descriptor.NestedTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ExecResource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ExecResource(ExecResource other) : this() { validate_ = other.validate_ != null ? other.validate_.Clone() : null; enforce_ = other.enforce_ != null ? other.enforce_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ExecResource Clone() { return new ExecResource(this); } /// <summary>Field number for the "validate" field.</summary> public const int ValidateFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec validate_; /// <summary> /// Required. What to run to validate this resource is in the desired state. /// An exit code of 100 indicates "in desired state", and exit code of 101 /// indicates "not in desired state". Any other exit code indicates a /// failure running validate. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec Validate { get { return validate_; } set { validate_ = value; } } /// <summary>Field number for the "enforce" field.</summary> public const int EnforceFieldNumber = 2; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec enforce_; /// <summary> /// What to run to bring this resource into the desired state. /// An exit code of 100 indicates "success", any other exit code indicates /// a failure running enforce. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec Enforce { get { return enforce_; } set { enforce_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ExecResource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ExecResource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Validate, other.Validate)) return false; if (!object.Equals(Enforce, other.Enforce)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (validate_ != null) hash ^= Validate.GetHashCode(); if (enforce_ != null) hash ^= Enforce.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (validate_ != null) { output.WriteRawTag(10); output.WriteMessage(Validate); } if (enforce_ != null) { output.WriteRawTag(18); output.WriteMessage(Enforce); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (validate_ != null) { output.WriteRawTag(10); output.WriteMessage(Validate); } if (enforce_ != null) { output.WriteRawTag(18); output.WriteMessage(Enforce); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (validate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Validate); } if (enforce_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Enforce); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ExecResource other) { if (other == null) { return; } if (other.validate_ != null) { if (validate_ == null) { Validate = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } Validate.MergeFrom(other.Validate); } if (other.enforce_ != null) { if (enforce_ == null) { Enforce = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } Enforce.MergeFrom(other.Enforce); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (validate_ == null) { Validate = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } input.ReadMessage(Validate); break; } case 18: { if (enforce_ == null) { Enforce = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } input.ReadMessage(Enforce); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (validate_ == null) { Validate = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } input.ReadMessage(Validate); break; } case 18: { if (enforce_ == null) { Enforce = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec(); } input.ReadMessage(Enforce); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the ExecResource message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// A file or script to execute. /// </summary> public sealed partial class Exec : pb::IMessage<Exec> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Exec> _parser = new pb::MessageParser<Exec>(() => new Exec()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Exec> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Exec() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Exec(Exec other) : this() { args_ = other.args_.Clone(); interpreter_ = other.interpreter_; outputFilePath_ = other.outputFilePath_; switch (other.SourceCase) { case SourceOneofCase.File: File = other.File.Clone(); break; case SourceOneofCase.Script: Script = other.Script; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Exec Clone() { return new Exec(this); } /// <summary>Field number for the "file" field.</summary> public const int FileFieldNumber = 1; /// <summary> /// A remote or local file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File File { get { return sourceCase_ == SourceOneofCase.File ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File) source_ : null; } set { source_ = value; sourceCase_ = value == null ? SourceOneofCase.None : SourceOneofCase.File; } } /// <summary>Field number for the "script" field.</summary> public const int ScriptFieldNumber = 2; /// <summary> /// An inline script. /// The size of the script is limited to 1024 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Script { get { return sourceCase_ == SourceOneofCase.Script ? (string) source_ : ""; } set { source_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); sourceCase_ = SourceOneofCase.Script; } } /// <summary>Field number for the "args" field.</summary> public const int ArgsFieldNumber = 3; private static readonly pb::FieldCodec<string> _repeated_args_codec = pb::FieldCodec.ForString(26); private readonly pbc::RepeatedField<string> args_ = new pbc::RepeatedField<string>(); /// <summary> /// Optional arguments to pass to the source during execution. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Args { get { return args_; } } /// <summary>Field number for the "interpreter" field.</summary> public const int InterpreterFieldNumber = 4; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter interpreter_ = global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified; /// <summary> /// Required. The script interpreter to use. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter Interpreter { get { return interpreter_; } set { interpreter_ = value; } } /// <summary>Field number for the "output_file_path" field.</summary> public const int OutputFilePathFieldNumber = 5; private string outputFilePath_ = ""; /// <summary> /// Only recorded for enforce Exec. /// Path to an output file (that is created by this Exec) whose /// content will be recorded in OSPolicyResourceCompliance after a /// successful run. Absence or failure to read this file will result in /// this ExecResource being non-compliant. Output file size is limited to /// 100K bytes. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OutputFilePath { get { return outputFilePath_; } set { outputFilePath_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } private object source_; /// <summary>Enum of possible cases for the "source" oneof.</summary> public enum SourceOneofCase { None = 0, File = 1, Script = 2, } private SourceOneofCase sourceCase_ = SourceOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SourceOneofCase SourceCase { get { return sourceCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearSource() { sourceCase_ = SourceOneofCase.None; source_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Exec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Exec other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(File, other.File)) return false; if (Script != other.Script) return false; if(!args_.Equals(other.args_)) return false; if (Interpreter != other.Interpreter) return false; if (OutputFilePath != other.OutputFilePath) return false; if (SourceCase != other.SourceCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (sourceCase_ == SourceOneofCase.File) hash ^= File.GetHashCode(); if (sourceCase_ == SourceOneofCase.Script) hash ^= Script.GetHashCode(); hash ^= args_.GetHashCode(); if (Interpreter != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified) hash ^= Interpreter.GetHashCode(); if (OutputFilePath.Length != 0) hash ^= OutputFilePath.GetHashCode(); hash ^= (int) sourceCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (sourceCase_ == SourceOneofCase.File) { output.WriteRawTag(10); output.WriteMessage(File); } if (sourceCase_ == SourceOneofCase.Script) { output.WriteRawTag(18); output.WriteString(Script); } args_.WriteTo(output, _repeated_args_codec); if (Interpreter != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) Interpreter); } if (OutputFilePath.Length != 0) { output.WriteRawTag(42); output.WriteString(OutputFilePath); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (sourceCase_ == SourceOneofCase.File) { output.WriteRawTag(10); output.WriteMessage(File); } if (sourceCase_ == SourceOneofCase.Script) { output.WriteRawTag(18); output.WriteString(Script); } args_.WriteTo(ref output, _repeated_args_codec); if (Interpreter != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) Interpreter); } if (OutputFilePath.Length != 0) { output.WriteRawTag(42); output.WriteString(OutputFilePath); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (sourceCase_ == SourceOneofCase.File) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(File); } if (sourceCase_ == SourceOneofCase.Script) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Script); } size += args_.CalculateSize(_repeated_args_codec); if (Interpreter != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Interpreter); } if (OutputFilePath.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OutputFilePath); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Exec other) { if (other == null) { return; } args_.Add(other.args_); if (other.Interpreter != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter.Unspecified) { Interpreter = other.Interpreter; } if (other.OutputFilePath.Length != 0) { OutputFilePath = other.OutputFilePath; } switch (other.SourceCase) { case SourceOneofCase.File: if (File == null) { File = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } File.MergeFrom(other.File); break; case SourceOneofCase.Script: Script = other.Script; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); if (sourceCase_ == SourceOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } case 18: { Script = input.ReadString(); break; } case 26: { args_.AddEntriesFrom(input, _repeated_args_codec); break; } case 32: { Interpreter = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter) input.ReadEnum(); break; } case 42: { OutputFilePath = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); if (sourceCase_ == SourceOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } case 18: { Script = input.ReadString(); break; } case 26: { args_.AddEntriesFrom(ref input, _repeated_args_codec); break; } case 32: { Interpreter = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.ExecResource.Types.Exec.Types.Interpreter) input.ReadEnum(); break; } case 42: { OutputFilePath = input.ReadString(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the Exec message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// The interpreter to use. /// </summary> public enum Interpreter { /// <summary> /// Defaults to NONE. /// </summary> [pbr::OriginalName("INTERPRETER_UNSPECIFIED")] Unspecified = 0, /// <summary> /// If no interpreter is specified the /// source will be executed directly, which will likely only /// succeed for executables and scripts with shebang lines. /// [Wikipedia /// shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)). /// </summary> [pbr::OriginalName("NONE")] None = 1, /// <summary> /// Indicates that the script will be run with /bin/sh on Linux and /// cmd.exe on windows. /// </summary> [pbr::OriginalName("SHELL")] Shell = 2, /// <summary> /// Indicates that the script will be run with powershell. /// </summary> [pbr::OriginalName("POWERSHELL")] Powershell = 3, } } #endregion } } #endregion } /// <summary> /// A resource that manages the state of a file. /// </summary> public sealed partial class FileResource : pb::IMessage<FileResource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<FileResource> _parser = new pb::MessageParser<FileResource>(() => new FileResource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<FileResource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Descriptor.NestedTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public FileResource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public FileResource(FileResource other) : this() { path_ = other.path_; state_ = other.state_; permissions_ = other.permissions_; switch (other.SourceCase) { case SourceOneofCase.File: File = other.File.Clone(); break; case SourceOneofCase.Content: Content = other.Content; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public FileResource Clone() { return new FileResource(this); } /// <summary>Field number for the "file" field.</summary> public const int FileFieldNumber = 1; /// <summary> /// A remote or local source. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File File { get { return sourceCase_ == SourceOneofCase.File ? (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File) source_ : null; } set { source_ = value; sourceCase_ = value == null ? SourceOneofCase.None : SourceOneofCase.File; } } /// <summary>Field number for the "content" field.</summary> public const int ContentFieldNumber = 2; /// <summary> /// A a file with this content. /// The size of the content is limited to 1024 characters. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Content { get { return sourceCase_ == SourceOneofCase.Content ? (string) source_ : ""; } set { source_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); sourceCase_ = SourceOneofCase.Content; } } /// <summary>Field number for the "path" field.</summary> public const int PathFieldNumber = 3; private string path_ = ""; /// <summary> /// Required. The absolute path of the file within the VM. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Path { get { return path_; } set { path_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "state" field.</summary> public const int StateFieldNumber = 4; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState state_ = global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified; /// <summary> /// Required. Desired state of the file. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState State { get { return state_; } set { state_ = value; } } /// <summary>Field number for the "permissions" field.</summary> public const int PermissionsFieldNumber = 5; private string permissions_ = ""; /// <summary> /// Consists of three octal digits which represent, in /// order, the permissions of the owner, group, and other users for the /// file (similarly to the numeric mode used in the linux chmod /// utility). Each digit represents a three bit number with the 4 bit /// corresponding to the read permissions, the 2 bit corresponds to the /// write bit, and the one bit corresponds to the execute permission. /// Default behavior is 755. /// /// Below are some examples of permissions and their associated values: /// read, write, and execute: 7 /// read and execute: 5 /// read and write: 6 /// read only: 4 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Permissions { get { return permissions_; } set { permissions_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } private object source_; /// <summary>Enum of possible cases for the "source" oneof.</summary> public enum SourceOneofCase { None = 0, File = 1, Content = 2, } private SourceOneofCase sourceCase_ = SourceOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SourceOneofCase SourceCase { get { return sourceCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearSource() { sourceCase_ = SourceOneofCase.None; source_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as FileResource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(FileResource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(File, other.File)) return false; if (Content != other.Content) return false; if (Path != other.Path) return false; if (State != other.State) return false; if (Permissions != other.Permissions) return false; if (SourceCase != other.SourceCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (sourceCase_ == SourceOneofCase.File) hash ^= File.GetHashCode(); if (sourceCase_ == SourceOneofCase.Content) hash ^= Content.GetHashCode(); if (Path.Length != 0) hash ^= Path.GetHashCode(); if (State != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified) hash ^= State.GetHashCode(); if (Permissions.Length != 0) hash ^= Permissions.GetHashCode(); hash ^= (int) sourceCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (sourceCase_ == SourceOneofCase.File) { output.WriteRawTag(10); output.WriteMessage(File); } if (sourceCase_ == SourceOneofCase.Content) { output.WriteRawTag(18); output.WriteString(Content); } if (Path.Length != 0) { output.WriteRawTag(26); output.WriteString(Path); } if (State != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) State); } if (Permissions.Length != 0) { output.WriteRawTag(42); output.WriteString(Permissions); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (sourceCase_ == SourceOneofCase.File) { output.WriteRawTag(10); output.WriteMessage(File); } if (sourceCase_ == SourceOneofCase.Content) { output.WriteRawTag(18); output.WriteString(Content); } if (Path.Length != 0) { output.WriteRawTag(26); output.WriteString(Path); } if (State != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) State); } if (Permissions.Length != 0) { output.WriteRawTag(42); output.WriteString(Permissions); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (sourceCase_ == SourceOneofCase.File) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(File); } if (sourceCase_ == SourceOneofCase.Content) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Content); } if (Path.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Path); } if (State != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State); } if (Permissions.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Permissions); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(FileResource other) { if (other == null) { return; } if (other.Path.Length != 0) { Path = other.Path; } if (other.State != global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState.Unspecified) { State = other.State; } if (other.Permissions.Length != 0) { Permissions = other.Permissions; } switch (other.SourceCase) { case SourceOneofCase.File: if (File == null) { File = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); } File.MergeFrom(other.File); break; case SourceOneofCase.Content: Content = other.Content; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); if (sourceCase_ == SourceOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } case 18: { Content = input.ReadString(); break; } case 26: { Path = input.ReadString(); break; } case 32: { State = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState) input.ReadEnum(); break; } case 42: { Permissions = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File subBuilder = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.File(); if (sourceCase_ == SourceOneofCase.File) { subBuilder.MergeFrom(File); } input.ReadMessage(subBuilder); File = subBuilder; break; } case 18: { Content = input.ReadString(); break; } case 26: { Path = input.ReadString(); break; } case 32: { State = (global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Types.FileResource.Types.DesiredState) input.ReadEnum(); break; } case 42: { Permissions = input.ReadString(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the FileResource message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Desired state of the file. /// </summary> public enum DesiredState { /// <summary> /// Unspecified is invalid. /// </summary> [pbr::OriginalName("DESIRED_STATE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Ensure file at path is present. /// </summary> [pbr::OriginalName("PRESENT")] Present = 1, /// <summary> /// Ensure file at path is absent. /// </summary> [pbr::OriginalName("ABSENT")] Absent = 2, /// <summary> /// Ensure the contents of the file at path matches. If the file does /// not exist it will be created. /// </summary> [pbr::OriginalName("CONTENTS_MATCH")] ContentsMatch = 3, } } #endregion } } #endregion } /// <summary> /// Resource groups provide a mechanism to group OS policy resources. /// /// Resource groups enable OS policy authors to create a single OS policy /// to be applied to VMs running different operating Systems. /// /// When the OS policy is applied to a target VM, the appropriate resource /// group within the OS policy is selected based on the `OSFilter` specified /// within the resource group. /// </summary> public sealed partial class ResourceGroup : pb::IMessage<ResourceGroup> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ResourceGroup> _parser = new pb::MessageParser<ResourceGroup>(() => new ResourceGroup()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ResourceGroup> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Descriptor.NestedTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceGroup() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceGroup(ResourceGroup other) : this() { osFilter_ = other.osFilter_ != null ? other.osFilter_.Clone() : null; resources_ = other.resources_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ResourceGroup Clone() { return new ResourceGroup(this); } /// <summary>Field number for the "os_filter" field.</summary> public const int OsFilterFieldNumber = 1; private global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter osFilter_; /// <summary> /// Used to specify the OS filter for a resource group /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter OsFilter { get { return osFilter_; } set { osFilter_ = value; } } /// <summary>Field number for the "resources" field.</summary> public const int ResourcesFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource> _repeated_resources_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource> resources_ = new pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource>(); /// <summary> /// Required. List of resources configured for this resource group. /// The resources are executed in the exact order specified here. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.Resource> Resources { get { return resources_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ResourceGroup); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ResourceGroup other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(OsFilter, other.OsFilter)) return false; if(!resources_.Equals(other.resources_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (osFilter_ != null) hash ^= OsFilter.GetHashCode(); hash ^= resources_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (osFilter_ != null) { output.WriteRawTag(10); output.WriteMessage(OsFilter); } resources_.WriteTo(output, _repeated_resources_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (osFilter_ != null) { output.WriteRawTag(10); output.WriteMessage(OsFilter); } resources_.WriteTo(ref output, _repeated_resources_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (osFilter_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OsFilter); } size += resources_.CalculateSize(_repeated_resources_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ResourceGroup other) { if (other == null) { return; } if (other.osFilter_ != null) { if (osFilter_ == null) { OsFilter = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter(); } OsFilter.MergeFrom(other.OsFilter); } resources_.Add(other.resources_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (osFilter_ == null) { OsFilter = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter(); } input.ReadMessage(OsFilter); break; } case 18: { resources_.AddEntriesFrom(input, _repeated_resources_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (osFilter_ == null) { OsFilter = new global::Google.Cloud.OsConfig.V1Alpha.OSPolicy.Types.OSFilter(); } input.ReadMessage(OsFilter); break; } case 18: { resources_.AddEntriesFrom(ref input, _repeated_resources_codec); break; } } } } #endif } } #endregion } #endregion } #endregion Designer generated code
47.046824
895
0.546384
[ "Apache-2.0" ]
LaudateCorpus1/google-cloud-dotnet
apis/Google.Cloud.OsConfig.V1Alpha/Google.Cloud.OsConfig.V1Alpha/OsPolicy.g.cs
346,641
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. // Template Source: Templates\CSharp\Requests\EntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; /// <summary> /// The type WorkbookTableColumnsCollectionPage. /// </summary> public partial class WorkbookTableColumnsCollectionPage : CollectionPage<WorkbookTableColumn>, IWorkbookTableColumnsCollectionPage { /// <summary> /// Gets the next page <see cref="IWorkbookTableColumnsCollectionRequest"/> instance. /// </summary> public IWorkbookTableColumnsCollectionRequest NextPageRequest { get; private set; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString) { if (!string.IsNullOrEmpty(nextPageLinkString)) { this.NextPageRequest = new WorkbookTableColumnsCollectionRequest( nextPageLinkString, client, null); } } } }
38.710526
153
0.583277
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookTableColumnsCollectionPage.cs
1,471
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShieldWall : MonoBehaviour { IEnumerator Wall() { SphereCollider Sphere = GetComponent<SphereCollider>(); while (Sphere.radius < 3) { Sphere.radius += Time.deltaTime * 5; yield return null; } yield return null; } private void Start() { StartCoroutine(Wall()); } private void OnCollisionEnter(Collision collision) { if (collision.collider.GetComponent<Projetil>()) { Destroy(collision.collider.gameObject); } } }
19.818182
63
0.593272
[ "Apache-2.0" ]
bruno-pLima/PandoraPlayers
Players/Juninho/Ataques/ShieldWall.cs
656
C#
using UmaMusumeAPI.Controllers; namespace UmaMusumeAPI.Models.Tables { [GeneratedController] public class SingleModeRaceLive { public int Id { get; set; } public long Grade { get; set; } public long RaceInstanceId { get; set; } public long MusicId { get; set; } } }
22.571429
48
0.632911
[ "Apache-2.0" ]
SimpleSandman/UmaMusumeAPI
UmaMusumeAPI/Models/Tables/SingleModeRaceLive.cs
318
C#
using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Configuration; using System.Xml; using YTS.Tools; namespace YTS.Web.UI { /// <summary> /// YTS的HttpModule类 /// </summary> public class HttpModule : System.Web.IHttpModule { /// <summary> /// 实现接口的Init方法 /// </summary> /// <param name="context"></param> public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(ReUrl_BeginRequest); } /// <summary> /// 实现接口的Dispose方法 /// </summary> public void Dispose() { } #region 页面请求事件处理=================================== /// <summary> /// 页面请求事件处理 /// </summary> /// <param name="sender">事件的源</param> /// <param name="e">包含事件数据的 EventArgs</param> private void ReUrl_BeginRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; Model.sysconfig siteConfig = YTS.SystemService.GlobalSystemService.GetInstance().Config.Get<Model.sysconfig>(); string requestPath = context.Request.Path.ToLower();//获得当前页面(含目录) //如果虚拟目录(不含安装目录)与站点根目录名相同则不需要重写 if (IsDirExist(DTKeys.CACHE_SITE_DIRECTORY, siteConfig.webpath, siteConfig.webpath, requestPath)) { return; } string requestDomain = context.Request.Url.Authority.ToLower();//获得当前域名(含端口号) string sitePath = GetSitePath(siteConfig.webpath, requestPath, requestDomain);//获取当前站点目录 string requestPage = CutStringPath(siteConfig.webpath, sitePath, requestPath);//截取除安装、站点目录部分 //检查网站重写状态0表示不开启重写、1开启重写、2生成静态 if (siteConfig.staticstatus == 0) { #region 站点不开启重写处理方法=========================== //遍历URL字典,匹配URL页面部分 foreach (Model.url_rewrite model in SiteUrls.GetUrls().Urls) { //查找到与页面部分匹配的节点 if (model.page == requestPath.Substring(requestPath.LastIndexOf("/") + 1)) { //映射到站点目录下 context.RewritePath(string.Format("{0}{1}/{2}{3}", siteConfig.webpath, DTKeys.DIRECTORY_REWRITE_ASPX, sitePath, requestPage)); } } #endregion } else { #region 站点开启重写或静态处理方法======================= //遍历URL字典 foreach (Model.url_rewrite model in SiteUrls.GetUrls().Urls) { //如果没有重写表达式则不需要重写 if (model.url_rewrite_items.Count == 0 && Utils.GetUrlExtension(model.page, siteConfig.staticextension) == requestPath.Substring(requestPath.LastIndexOf("/") + 1)) { //映射到站点目录 context.RewritePath(string.Format("{0}{1}/{2}/{3}", siteConfig.webpath, DTKeys.DIRECTORY_REWRITE_ASPX, sitePath, model.page)); return; } //遍历URL字典的子节点 foreach (Model.url_rewrite_item item in model.url_rewrite_items) { string newPattern = Utils.GetUrlExtension(item.pattern, siteConfig.staticextension);//替换扩展名 //如果与URL节点匹配则重写 if (Regex.IsMatch(requestPage, string.Format("^/{0}$", newPattern), RegexOptions.None | RegexOptions.IgnoreCase) || (model.page == "index.aspx" && Regex.IsMatch(requestPage, string.Format("^/{0}$", item.pattern), RegexOptions.None | RegexOptions.IgnoreCase))) { //如果开启生成静态、是频道页或首页,则映射重写到HTML目录 if (siteConfig.staticstatus == 2 && (model.channel.Length > 0 || model.page.ToLower() == "index.aspx")) //频道页 { context.RewritePath(siteConfig.webpath + DTKeys.DIRECTORY_REWRITE_HTML + "/" + sitePath + Utils.GetUrlExtension(requestPage, siteConfig.staticextension, true)); return; } else //其它 { string queryString = Regex.Replace(requestPage, string.Format("/{0}", newPattern), item.querystring, RegexOptions.None | RegexOptions.IgnoreCase); context.RewritePath(string.Format("{0}{1}/{2}/{3}", siteConfig.webpath, DTKeys.DIRECTORY_REWRITE_ASPX, sitePath, model.page), string.Empty, queryString); return; } } } } #endregion } } #endregion #region 辅助方法(私有)===================================== /// <summary> /// 获取URL的虚拟目录(除安装目录) /// </summary> /// <param name="webPath">网站安装目录</param> /// <param name="requestPath">当前页面,包含目录</param> /// <returns>String</returns> private string GetFirstPath(string webPath, string requestPath) { if (requestPath.StartsWith(webPath)) { string tempStr = requestPath.Substring(webPath.Length); if (tempStr.IndexOf("/") > 0) { return tempStr.Substring(0, tempStr.IndexOf("/")).ToLower(); } } return string.Empty; } /// <summary> /// 获取当前域名包含的站点目录 /// </summary> /// <param name="requestDomain">获取的域名(含端口号)</param> /// <returns>String</returns> private string GetCurrDomainPath(string requestDomain) { //当前域名是否存在于站点目录列表 if (SiteDomains.GetSiteDomains().Paths.ContainsValue(requestDomain)) { string sitePath = SiteDomains.GetSiteDomains().Domains[requestDomain]; //如果存在,检查是否默认站点,是则还需检查虚拟目录部分 if (sitePath != SiteDomains.GetSiteDomains().DefaultPath) { return sitePath; } } return string.Empty; } /// <summary> /// 获取当前页面包含的站点目录 /// </summary> /// <param name="webPath">网站安装目录</param> /// <param name="requestPath">获取的页面,包含目录</param> /// <returns>String</returns> private string GetCurrPagePath(string webPath, string requestPath) { //获取URL的虚拟目录(除安装目录) string requestFirstPath = GetFirstPath(webPath, requestPath); if (requestFirstPath != string.Empty && SiteDomains.GetSiteDomains().Paths.ContainsKey(requestFirstPath)) { return requestFirstPath; } return string.Empty; } /// <summary> /// 获取站点的目录 /// </summary> /// <param name="webPath">网站安装目录</param> /// <param name="requestPath">获取的页面,包含目录</param> /// <param name="requestDomain">获取的域名(含端口号)</param> /// <returns>String</returns> private string GetSitePath(string webPath, string requestPath, string requestDomain) { //获取当前域名包含的站点目录 string domainPath = GetCurrDomainPath(requestDomain); if (domainPath != string.Empty) { return domainPath; } // 获取当前页面包含的站点目录 string pagePath = GetCurrPagePath(webPath, requestPath); if (pagePath != string.Empty) { return pagePath; } return SiteDomains.GetSiteDomains().DefaultPath; } /// <summary> /// 遍历指定路径目录,如果缓存存在则直接返回 /// </summary> /// <param name="cacheKey">缓存KEY</param> /// <param name="dirPath">指定路径</param> /// <returns>ArrayList</returns> private ArrayList GetSiteDirs(string cacheKey, string dirPath) { ArrayList _cache = CacheHelper.Get<ArrayList>(cacheKey); //从续存中取 if (_cache == null) { _cache = new ArrayList(); DirectoryInfo dirInfo = new DirectoryInfo(Utils.GetMapPath(dirPath)); foreach (DirectoryInfo dir in dirInfo.GetDirectories()) { _cache.Add(dir.Name.ToLower()); } CacheHelper.Insert(cacheKey, _cache, 2); //存入续存,弹性2分钟 } return _cache; } /// <summary> /// 遍历指定路径的子目录,检查是否匹配 /// </summary> /// <param name="cacheKey">缓存KEY</param> /// <param name="webPath">网站安装目录,以“/”结尾</param> /// <param name="dirPath">指定的路径,以“/”结尾</param> /// <param name="requestPath">获取的URL全路径</param> /// <returns>布尔值</returns> private bool IsDirExist(string cacheKey, string webPath, string dirPath, string requestPath) { ArrayList list = GetSiteDirs(cacheKey, dirPath);//取得所有目录 string requestFirstPath = string.Empty;//获得当前页面除站点安装目录的虚拟目录名称 string tempStr = string.Empty;//临时变量 if (requestPath.StartsWith(webPath)) { tempStr = requestPath.Substring(webPath.Length); if (tempStr.IndexOf("/") > 0) { requestFirstPath = tempStr.Substring(0, tempStr.IndexOf("/")); } } if (requestFirstPath.Length > 0 && list.Contains(requestFirstPath.ToLower())) { return true; } return false; } /// <summary> /// 截取安装目录和站点目录部分 /// </summary> /// <param name="webPath">站点安装目录</param> /// <param name="sitePath">站点目录</param> /// <param name="requestPath">当前页面路径</param> /// <returns>String</returns> private string CutStringPath(string webPath, string sitePath, string requestPath) { if (requestPath.StartsWith(webPath)) { requestPath = requestPath.Substring(webPath.Length); } sitePath += "/"; if (requestPath.StartsWith(sitePath)) { requestPath = requestPath.Substring(sitePath.Length); } return "/" + requestPath; } #endregion } #region 站点URL字典信息类=================================== /// <summary> /// 站点伪Url信息类 /// </summary> public class SiteUrls { //属性声明 private static object lockHelper = new object(); private static volatile SiteUrls instance = null; private ArrayList _urls; public ArrayList Urls { get { return _urls; } set { _urls = value; } } //构造函数 private SiteUrls() { Urls = new ArrayList(); BLL.url_rewrite bll = new BLL.url_rewrite(); List<Model.url_rewrite> ls = bll.GetList(""); foreach(Model.url_rewrite model in ls) { foreach (Model.url_rewrite_item item in model.url_rewrite_items) { item.querystring = item.querystring.Replace("^", "&"); } Urls.Add(model); } } //返回URL字典 public static SiteUrls GetUrls() { SiteUrls _cache = CacheHelper.Get<SiteUrls>(DTKeys.CACHE_SITE_HTTP_MODULE); lock (lockHelper) { if (_cache == null) { CacheHelper.Insert(DTKeys.CACHE_SITE_HTTP_MODULE, new SiteUrls(), Utils.GetXmlMapPath(DTKeys.FILE_URL_XML_CONFING)); instance = CacheHelper.Get<SiteUrls>(DTKeys.CACHE_SITE_HTTP_MODULE); } } return instance; } } #endregion #region 站点绑定域名信息类================================== /// <summary> /// 域名字典 /// </summary> public class SiteDomains { private static object lockHelper = new object(); private static volatile SiteDomains instance = null; //默认站点目录 private string _default_path = string.Empty; public string DefaultPath { get { return _default_path; } set { _default_path = value; } } //站点目录列表 private Dictionary<string, string> _paths; public Dictionary<string, string> Paths { get { return _paths; } set { _paths = value; } } //站点域名列表 private Dictionary<string, string> _domains; public Dictionary<string, string> Domains { get { return _domains; } set { _domains = value; } } //所有站点实体 private List<Model.sites> _sitelist; public List<Model.sites> SiteList { get { return _sitelist; } set { _sitelist = value; } } //构造函数 public SiteDomains() { SiteList = new BLL.sites().GetModelList();//所有站点信息 Paths = new Dictionary<string, string>();//所有站点目录 Domains = new Dictionary<string, string>();//所有独立域名列表 if (SiteList != null) { foreach (Model.sites modelt in SiteList) { //所有站点目录赋值 Paths.Add(modelt.build_path, modelt.domain); //所有独立域名列表赋值 if (modelt.domain.Length > 0 && !Domains.ContainsKey(modelt.domain)) { Domains.Add(modelt.domain, modelt.build_path); } //默认站点赋值 if (modelt.is_default == 1 && DefaultPath == string.Empty) { DefaultPath = modelt.build_path; } } } } /// <summary> /// 返回域名字典 /// </summary> public static SiteDomains GetSiteDomains() { SiteDomains _cache = CacheHelper.Get<SiteDomains>(DTKeys.CACHE_SITE_HTTP_DOMAIN); lock (lockHelper) { if (_cache == null) { CacheHelper.Insert(DTKeys.CACHE_SITE_HTTP_DOMAIN, new SiteDomains(), 10); instance = CacheHelper.Get<SiteDomains>(DTKeys.CACHE_SITE_HTTP_DOMAIN); } } return instance; } } #endregion }
37.069307
178
0.503673
[ "Apache-2.0" ]
YellowTulipShow/CSharp
dotnet_framework/YTS.Web.UI/HttpModule.cs
16,436
C#
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System.Collections.Generic; using ServiceStack.DesignPatterns.Model; namespace ServiceStack.Redis.Generic { public interface IRedisHash<TKey, TValue> : IDictionary<TKey, TValue>, IHasStringId { Dictionary<TKey, TValue> GetAll(); } }
23.916667
85
0.71777
[ "BSD-3-Clause" ]
GSerjo/ServiceStack
src/ServiceStack.Interfaces/Redis/Generic/IRedisHash.Generic.cs
551
C#
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql.Models { /// <summary> /// Defines values for TargetElasticPoolEditions. /// </summary> [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public enum TargetElasticPoolEditions { [System.Runtime.Serialization.EnumMember(Value = "Basic")] Basic, [System.Runtime.Serialization.EnumMember(Value = "Standard")] Standard, [System.Runtime.Serialization.EnumMember(Value = "Premium")] Premium } }
31.909091
91
0.696581
[ "Apache-2.0" ]
pbolduc/Azure-Resource-Management-Utilities
src/ResourceManagement/Sql/Microsoft.Azure.Management.Sql/Generated/Models/TargetElasticPoolEditions.cs
702
C#
using AllReady.Areas.Admin.Features.Activities; using AllReady.Models; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using Xunit; namespace AllReady.UnitTest.Activities { public class GetActivityDetail : InMemoryContextTest { protected override void LoadTestData() { var context = ServiceProvider.GetService<AllReadyContext>(); Tenant htb = new Tenant() { Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; Campaign firePrev = new Campaign() { Name = "Neighborhood Fire Prevention Days", ManagingTenant = htb }; htb.Campaigns.Add(firePrev); Activity queenAnne = new Activity() { Id = 1, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = new Location { Id = 1 }, RequiredSkills = new List<ActivitySkill>() }; context.Tenants.Add(htb); context.Activities.Add(queenAnne); context.SaveChanges(); } [Fact] public void ActivityExists() { var context = ServiceProvider.GetService<AllReadyContext>(); var query = new ActivityDetailQuery { ActivityId = 1 }; var handler = new ActivityDetailQueryHandler(context); var result = handler.Handle(query); Assert.NotNull(result); } [Fact] public void ActivityDoesNotExist() { var context = ServiceProvider.GetService<AllReadyContext>(); var query = new ActivityDetailQuery(); var handler = new ActivityDetailQueryHandler(context); var result = handler.Handle(query); Assert.Null(result); } } }
35.69697
86
0.542445
[ "MIT" ]
JesseLiberty/allReady
AllReadyApp/Web-App/AllReady.UnitTest/Activities/GetActivityDetail.cs
2,358
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программным средством. // Версия среды выполнения: 4.0.30319.296 // // Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если // код создан повторно. // </auto-generated> //------------------------------------------------------------------------------ namespace FlowSimulation.Test.Properties { /// <summary> /// Класс ресурсов со строгим типом для поиска локализованных строк и пр. /// </summary> // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder // класс с помощью таких средств, как ResGen или Visual Studio. // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen // с параметром /str или заново постройте свой VS-проект. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FlowSimulation.Test.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Переопределяет свойство CurrentUICulture текущего потока для всех /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.166667
185
0.618603
[ "MIT" ]
nomoreserious/FlowSimulation
FlowSimulation.Test/Properties/Resources.Designer.cs
3,423
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace API.Data.Migrations { public partial class IdentityAdded : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(type: "bit", nullable: false), PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true), SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true), ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true), PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true), PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false), TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false), LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true), LockoutEnabled = table.Column<bool>(type: "bit", nullable: false), AccessFailedCount = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RoleId = table.Column<int>(type: "int", nullable: false), ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<int>(type: "int", nullable: false), ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true), ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false), ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false), ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true), UserId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<int>(type: "int", nullable: false), RoleId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<int>(type: "int", nullable: false), LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false), Name = table.Column<string>(type: "nvarchar(450)", nullable: false), Value = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
45.472973
117
0.494998
[ "MIT" ]
jlamza/MoviesApp
API/Data/Migrations/20201226232138_IdentityAdded.cs
10,097
C#
/* * Copyright (c) 2014-2021 GraphDefined GmbH * This file is part of WWCP OCPP <https://github.com/OpenChargingCloud/WWCP_OCPP> * * 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. */ #region Usings using System; using System.Threading.Tasks; using System.Collections.Generic; using org.GraphDefined.Vanaheimr.Hermod; using cloud.charging.open.protocols.OCPPv1_6.CP; #endregion namespace cloud.charging.open.protocols.OCPPv1_6.CS { /// <summary> /// The common interface of a central system server. /// </summary> public interface ICentralSystemServer : IEventSender { #region Events #region OnBootNotification /// <summary> /// An event sent whenever a boot notification request was received. /// </summary> event BootNotificationRequestDelegate OnBootNotificationRequest; /// <summary> /// An event sent whenever a boot notification was received. /// </summary> event BootNotificationDelegate OnBootNotification; /// <summary> /// An event sent whenever a response to a boot notification was sent. /// </summary> event BootNotificationResponseDelegate OnBootNotificationResponse; #endregion #region OnHeartbeat /// <summary> /// An event sent whenever a heartbeat request was received. /// </summary> event HeartbeatRequestDelegate OnHeartbeatRequest; /// <summary> /// An event sent whenever a heartbeat was received. /// </summary> event HeartbeatDelegate OnHeartbeat; /// <summary> /// An event sent whenever a response to a heartbeat was sent. /// </summary> event HeartbeatResponseDelegate OnHeartbeatResponse; #endregion #region OnAuthorize /// <summary> /// An event sent whenever an authorize request was received. /// </summary> event OnAuthorizeRequestDelegate OnAuthorizeRequest; /// <summary> /// An event sent whenever an authorize request was received. /// </summary> event OnAuthorizeDelegate OnAuthorize; /// <summary> /// An event sent whenever an authorize response was sent. /// </summary> event OnAuthorizeResponseDelegate OnAuthorizeResponse; #endregion #region OnStartTransaction /// <summary> /// An event sent whenever a start transaction request was received. /// </summary> event OnStartTransactionRequestDelegate OnStartTransactionRequest; /// <summary> /// An event sent whenever a start transaction request was received. /// </summary> event OnStartTransactionDelegate OnStartTransaction; /// <summary> /// An event sent whenever a response to a start transaction request was sent. /// </summary> event OnStartTransactionResponseDelegate OnStartTransactionResponse; #endregion #region OnStatusNotification /// <summary> /// An event sent whenever a status notification request was received. /// </summary> event OnStatusNotificationRequestDelegate OnStatusNotificationRequest; /// <summary> /// An event sent whenever a status notification request was received. /// </summary> event OnStatusNotificationDelegate OnStatusNotification; /// <summary> /// An event sent whenever a response to a status notification request was sent. /// </summary> event OnStatusNotificationResponseDelegate OnStatusNotificationResponse; #endregion #region OnMeterValues /// <summary> /// An event sent whenever a meter values request was received. /// </summary> event OnMeterValuesRequestDelegate OnMeterValuesRequest; /// <summary> /// An event sent whenever a meter values request was received. /// </summary> event OnMeterValuesDelegate OnMeterValues; /// <summary> /// An event sent whenever a response to a meter values request was sent. /// </summary> event OnMeterValuesResponseDelegate OnMeterValuesResponse; #endregion #region OnStopTransaction /// <summary> /// An event sent whenever a stop transaction request was received. /// </summary> event OnStopTransactionRequestDelegate OnStopTransactionRequest; /// <summary> /// An event sent whenever a stop transaction request was received. /// </summary> event OnStopTransactionDelegate OnStopTransaction; /// <summary> /// An event sent whenever a response to a stop transaction request was sent. /// </summary> event OnStopTransactionResponseDelegate OnStopTransactionResponse; #endregion #region OnDataTransfer /// <summary> /// An event sent whenever a data transfer request was received. /// </summary> event OnIncomingDataTransferRequestDelegate OnIncomingDataTransferRequest; /// <summary> /// An event sent whenever a data transfer request was received. /// </summary> event OnIncomingDataTransferDelegate OnIncomingDataTransfer; /// <summary> /// An event sent whenever a response to a data transfer request was sent. /// </summary> event OnIncomingDataTransferResponseDelegate OnIncomingDataTransferResponse; #endregion #region OnDiagnosticsStatusNotification /// <summary> /// An event sent whenever a diagnostics status notification request was received. /// </summary> event OnDiagnosticsStatusNotificationRequestDelegate OnDiagnosticsStatusNotificationRequest; /// <summary> /// An event sent whenever a diagnostics status notification request was received. /// </summary> event OnDiagnosticsStatusNotificationDelegate OnDiagnosticsStatusNotification; /// <summary> /// An event sent whenever a response to a diagnostics status notification request was sent. /// </summary> event OnDiagnosticsStatusNotificationResponseDelegate OnDiagnosticsStatusNotificationResponse; #endregion #region OnFirmwareStatusNotification /// <summary> /// An event sent whenever a firmware status notification request was received. /// </summary> event OnFirmwareStatusNotificationRequestDelegate OnFirmwareStatusNotificationRequest; /// <summary> /// An event sent whenever a firmware status notification request was received. /// </summary> event OnFirmwareStatusNotificationDelegate OnFirmwareStatusNotification; /// <summary> /// An event sent whenever a response to a firmware status notification request was sent. /// </summary> event OnFirmwareStatusNotificationResponseDelegate OnFirmwareStatusNotificationResponse; #endregion #endregion } }
32.630252
103
0.652073
[ "Apache-2.0" ]
OpenChargingCloud/WWCP_OCPP
WWCP_OCPPv1.6/CentralSystem/ICentralSystemServer.cs
7,768
C#
using System.Reflection; namespace Eshava.Storm.Models { internal class KeyProperty { public PropertyInfo PropertyInfo { get; set; } public bool AutoGenerated { get; set; } public string ColumnName { get; set; } } }
20.545455
48
0.725664
[ "MIT" ]
MichaelPruefer/storm
Eshava.Storm/Models/KeyProperty.cs
228
C#
using System; using System.Threading; using System.Threading.Tasks; using AutoMapper; using EshopManager.Application.Interfaces.Repositories; using EshopManager.Domain.Contracts; using EshopManager.Shared.Wrapper; using MediatR; namespace EshopManager.Application.Features.ExtendedAttributes.Queries.GetById { public class GetExtendedAttributeByIdQuery<TId, TEntityId, TEntity, TExtendedAttribute> : IRequest<Result<GetExtendedAttributeByIdResponse<TId, TEntityId>>> where TEntity : AuditableEntity<TEntityId>, IEntityWithExtendedAttributes<TExtendedAttribute>, IEntity<TEntityId> where TExtendedAttribute : AuditableEntityExtendedAttribute<TId, TEntityId, TEntity>, IEntity<TId> where TId : IEquatable<TId> { public TId Id { get; set; } } internal class GetExtendedAttributeByIdQueryHandler<TId, TEntityId, TEntity, TExtendedAttribute> : IRequestHandler<GetExtendedAttributeByIdQuery<TId, TEntityId, TEntity, TExtendedAttribute>, Result<GetExtendedAttributeByIdResponse<TId, TEntityId>>> where TEntity : AuditableEntity<TEntityId>, IEntityWithExtendedAttributes<TExtendedAttribute>, IEntity<TEntityId> where TExtendedAttribute : AuditableEntityExtendedAttribute<TId, TEntityId, TEntity>, IEntity<TId> where TId : IEquatable<TId> { private readonly IUnitOfWork<TId> _unitOfWork; private readonly IMapper _mapper; public GetExtendedAttributeByIdQueryHandler(IUnitOfWork<TId> unitOfWork, IMapper mapper) { _unitOfWork = unitOfWork; _mapper = mapper; } public async Task<Result<GetExtendedAttributeByIdResponse<TId, TEntityId>>> Handle(GetExtendedAttributeByIdQuery<TId, TEntityId, TEntity, TExtendedAttribute> query, CancellationToken cancellationToken) { var extendedAttribute = await _unitOfWork.Repository<TExtendedAttribute>().GetByIdAsync(query.Id); var mappedExtendedAttribute = _mapper.Map<GetExtendedAttributeByIdResponse<TId, TEntityId>>(extendedAttribute); return await Result<GetExtendedAttributeByIdResponse<TId, TEntityId>>.SuccessAsync(mappedExtendedAttribute); } } }
51.534884
209
0.75722
[ "MIT" ]
tarafdarmansour/EShopManager
src/Application/Features/ExtendedAttributes/Queries/GetById/GetExtendedAttributeByIdQuery.cs
2,218
C#
using System; using System.Threading.Tasks; namespace MQTTnet.Implementations { public static class PlatformAbstractionLayer { #if NET452 public static Task CompletedTask => Task.FromResult(0); public static byte[] EmptyByteArray { get; } = new byte[0]; #else public static Task CompletedTask => Task.CompletedTask; public static byte[] EmptyByteArray { get; } = Array.Empty<byte>(); #endif public static void Sleep(TimeSpan timeout) { #if !NETSTANDARD1_3 && !WINDOWS_UWP System.Threading.Thread.Sleep(timeout); #else Task.Delay(timeout).Wait(); #endif } } }
23.428571
75
0.652439
[ "MIT" ]
765643729/MQTTnet
Source/MQTTnet/Implementations/PlatformAbstractionLayer.cs
658
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.Win32.SafeHandles; using System.IO; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { /// <summary> /// WARNING: This method does not implicitly handle long paths. Use DeleteVolumeMountPoint. /// </summary> [DllImport(Libraries.Kernel32, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint); internal static bool DeleteVolumeMountPoint(string mountPoint) { mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint); return DeleteVolumeMountPointPrivate(mountPoint); } } }
36.888889
151
0.722892
[ "MIT" ]
06needhamt/runtime
src/libraries/Common/src/Interop/Windows/Kernel32/Interop.DeleteVolumeMountPoint.cs
996
C#
// <copyright file="UsersUnitOfWork.cs" company="YAGNI"> // All rights reserved. // </copyright> // <summary>Holds implementation of UsersUnitOfWork class.</summary> using Bytes2you.Validation; using LibrarySystem.Data.Users; using LibrarySystem.Repositories.Contracts; using LibrarySystem.Repositories.Contracts.Data.Users; using LibrarySystem.Repositories.Contracts.Data.Users.UnitOfWork; namespace LibrarySystem.Repositories.Data.Users.UnitOfWork { /// <summary> /// Represent a <see cref="UsersUnitOfWork"/> class. /// Implementator of <see cref="IUnitOfWork"/> and <see cref="IUsersUnitOfWork"/> interfaces. /// </summary> public class UsersUnitOfWork : IUnitOfWork, IUsersUnitOfWork { /// <summary>Context that provide connection to the database.</summary> private readonly LibrarySystemUsersDbContext usersContext; public UsersUnitOfWork(LibrarySystemUsersDbContext usersContext) { Guard.WhenArgument(usersContext, "usersContext").IsNull().Throw(); this.usersContext = usersContext; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.usersContext.Dispose(); } /// <summary> /// Make a transaction to save the changes of the entities tracked by the context. /// </summary> /// <returns> /// The number of state entries written to the underlying database. This can include /// state entries for entities and/or relationships. Relationship state entries are /// created for many-to-many relationships and relationships where there is no foreign /// key property included in the entity class (often referred to as independent associations). /// </returns> public int Commit() { return this.usersContext.SaveChanges(); } } }
37.962264
116
0.67495
[ "MIT" ]
TeamYAGNI/LibrarySystem
LibrarySystem/LibrarySystem.Repositories/Data.Users/UnitOfWork/UsersUnitOfWork.cs
2,014
C#
using FluentNHibernate.Automapping; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using FluentNHibernate.Conventions.Helpers; using Meganium.Api.Entities; using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NHibernate.Validator.Cfg; using NHibernate.Validator.Engine; namespace Meganium.Api { //Refactor: Repensar neste cara aqui public static class NHibernateBuilder { public static void Reset(string connectionString) { GetConfig(connectionString) .ExposeConfiguration(BuildSchema) .BuildConfiguration(); } public static ISessionFactory GetSessionFactory(string connectionString) { return GetConfig(connectionString) .BuildSessionFactory(); } private static FluentConfiguration GetConfig(string connectionString) { var autoMap = AutoMap.AssemblyOf<PostType>().Where(type => typeof(IHaveId).IsAssignableFrom(type)); autoMap.Conventions.Add(DefaultCascade.All()); autoMap.OverrideAll(map => map.IgnoreProperties(x => x.CanWrite == false)); return Fluently.Configure() .Database(MySQLConfiguration.Standard.ConnectionString(connectionString)) .Mappings(m => m.AutoMappings.Add(autoMap)); } private static void BuildSchema(Configuration config) { var nhvc = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration(); var validator = new ValidatorEngine(); validator.Configure(nhvc); config.Initialize(validator); var schemaExport = new SchemaExport(config); schemaExport.Drop(true, true); schemaExport.Create(true, true); } } }
33.759259
111
0.658804
[ "MIT" ]
afonsof/meganium
Api/NHibernateBuilder.cs
1,825
C#
version https://git-lfs.github.com/spec/v1 oid sha256:184a7e969c764b337260d6dd3d0d48d68f5b4fc01707df46e04bc6d02471a807 size 508
32
75
0.882813
[ "MIT" ]
Vakuzar/Multithreaded-Blood-Sim
Blood/Library/PackageCache/com.unity.shadergraph@8.1.0/Editor/Data/Nodes/IMasterNode.cs
128
C#
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using OrchardCore.Modules; namespace OrchardCore.Mvc.HelloWorld { public class Startup : StartupBase { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; } public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { if (string.IsNullOrEmpty(_configuration["Sample"])) { throw new Exception(":("); } routes.MapAreaControllerRoute ( name: "Home", areaName: "OrchardCore.Mvc.HelloWorld", pattern: "", defaults: new { controller = "Home", action = "Index" } ); } } }
28.028571
131
0.59633
[ "BSD-3-Clause" ]
AkosLukacs/OrchardCore
src/OrchardCore.Modules/OrchardCore.Mvc.HelloWorld/Startup.cs
981
C#
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Swiddler.Converters { public class TreeIndentConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return new Thickness() { Left = (int)value * (int)parameter }; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
25.125
103
0.626866
[ "Apache-2.0" ]
ihonliu/Swiddler
Source/Swiddler/Converters/TreeIndentConverter.cs
605
C#
// // System.CodeDom CodeTypeReferenceExpression Class implementation // // Author: // Daniel Stodden (stodden@in.tum.de) // Marek Safar (marek.safar@seznam.cz) // // (C) 2001 Ximian, Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.InteropServices; using System.Text; namespace System.CodeDom { [Serializable] [ClassInterface(ClassInterfaceType.AutoDispatch)] [ComVisible(true)] public class CodeTypeReference : CodeObject { private string baseType; private CodeTypeReference arrayElementType; private int arrayRank; private bool isInterface; //bool needsFixup; CodeTypeReferenceCollection typeArguments; CodeTypeReferenceOptions referenceOptions; // // Constructors // public CodeTypeReference () { } [MonoTODO("We should parse basetype from right to left in 2.0 profile.")] public CodeTypeReference (string baseType) { Parse (baseType); } [MonoTODO("We should parse basetype from right to left in 2.0 profile.")] public CodeTypeReference (Type baseType) { if (baseType == null) { throw new ArgumentNullException ("baseType"); } if (baseType.IsGenericParameter) { this.baseType = baseType.Name; this.referenceOptions = CodeTypeReferenceOptions.GenericTypeParameter; } else if (baseType.IsGenericTypeDefinition) this.baseType = baseType.FullName; else if (baseType.IsGenericType) { this.baseType = baseType.GetGenericTypeDefinition ().FullName; foreach (Type arg in baseType.GetGenericArguments ()) { if (arg.IsGenericParameter) TypeArguments.Add (new CodeTypeReference (new CodeTypeParameter (arg.Name))); else TypeArguments.Add (new CodeTypeReference (arg)); } } else if (baseType.IsArray) { this.arrayRank = baseType.GetArrayRank (); this.arrayElementType = new CodeTypeReference (baseType.GetElementType ()); this.baseType = arrayElementType.BaseType; } else { Parse (baseType.FullName); } this.isInterface = baseType.IsInterface; } public CodeTypeReference( CodeTypeReference arrayElementType, int arrayRank ) { this.baseType = null; this.arrayRank = arrayRank; this.arrayElementType = arrayElementType; } [MonoTODO("We should parse basetype from right to left in 2.0 profile.")] public CodeTypeReference( string baseType, int arrayRank ) : this (new CodeTypeReference (baseType), arrayRank) { } public CodeTypeReference( CodeTypeParameter typeParameter ) : this (typeParameter.Name) { this.referenceOptions = CodeTypeReferenceOptions.GenericTypeParameter; } public CodeTypeReference( string typeName, CodeTypeReferenceOptions referenceOptions ) : this (typeName) { this.referenceOptions = referenceOptions; } public CodeTypeReference( Type type, CodeTypeReferenceOptions referenceOptions ) : this (type) { this.referenceOptions = referenceOptions; } public CodeTypeReference( string typeName, params CodeTypeReference[] typeArguments ) : this (typeName) { TypeArguments.AddRange (typeArguments); if (this.baseType.IndexOf ('`') < 0) this.baseType += "`" + TypeArguments.Count; } // // Properties // public CodeTypeReference ArrayElementType { get { return arrayElementType; } set { arrayElementType = value; } } public int ArrayRank { get { return arrayRank; } set { arrayRank = value; } } public string BaseType { get { if (arrayElementType != null && arrayRank > 0) { return arrayElementType.BaseType; } if (baseType == null) return String.Empty; return baseType; } set { baseType = value; } } internal bool IsInterface { get { return isInterface; } } private void Parse (string baseType) { if (baseType == null || baseType.Length == 0) { this.baseType = typeof (void).FullName; return; } int array_start = baseType.IndexOf ('['); if (array_start == -1) { this.baseType = baseType; return; } int array_end = baseType.LastIndexOf (']'); if (array_end < array_start) { this.baseType = baseType; return; } int lastAngle = baseType.LastIndexOf ('>'); if (lastAngle != -1 && lastAngle > array_end) { this.baseType = baseType; return; } string[] args = baseType.Substring (array_start + 1, array_end - array_start - 1).Split (','); if ((array_end - array_start) != args.Length) { this.baseType = baseType.Substring (0, array_start); int escapeCount = 0; int scanPos = array_start; StringBuilder tb = new StringBuilder(); while (scanPos < baseType.Length) { char currentChar = baseType[scanPos]; switch (currentChar) { case '[': if (escapeCount > 1 && tb.Length > 0) { tb.Append (currentChar); } escapeCount++; break; case ']': escapeCount--; if (escapeCount > 1 && tb.Length > 0) { tb.Append (currentChar); } if (tb.Length != 0 && (escapeCount % 2) == 0) { TypeArguments.Add (tb.ToString ()); tb.Length = 0; } break; case ',': if (escapeCount > 1) { // skip anything after the type name until we // reach the next separator while (scanPos + 1 < baseType.Length) { if (baseType[scanPos + 1] == ']') { break; } scanPos++; } } else if (tb.Length > 0) { CodeTypeReference typeArg = new CodeTypeReference (tb.ToString ()); TypeArguments.Add (typeArg); tb.Length = 0; } break; default: tb.Append (currentChar); break; } scanPos++; } } else { arrayElementType = new CodeTypeReference (baseType.Substring (0, array_start)); arrayRank = args.Length; } } [ComVisible (false)] public CodeTypeReferenceOptions Options { get { return referenceOptions; } set { referenceOptions = value; } } [ComVisible (false)] public CodeTypeReferenceCollection TypeArguments { get { if (typeArguments == null) typeArguments = new CodeTypeReferenceCollection (); return typeArguments; } } } }
25.942857
97
0.665474
[ "Apache-2.0" ]
121468615/mono
mcs/class/System/System.CodeDom/CodeTypeReference.cs
7,264
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using EnsureThat; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Health.Dicom.Core.Models.Operations; namespace Microsoft.Health.Dicom.Operations.Client.Extensions { internal static class DurableOrchestrationStatusExtensions { public static OperationType GetOperationType(this DurableOrchestrationStatus durableOrchestrationStatus) { EnsureArg.IsNotNull(durableOrchestrationStatus, nameof(durableOrchestrationStatus)); return durableOrchestrationStatus.Name != null && durableOrchestrationStatus.Name.StartsWith(FunctionNames.ReindexInstances, StringComparison.OrdinalIgnoreCase) ? OperationType.Reindex : OperationType.Unknown; } public static OperationRuntimeStatus GetOperationRuntimeStatus(this DurableOrchestrationStatus durableOrchestrationStatus) { EnsureArg.IsNotNull(durableOrchestrationStatus, nameof(durableOrchestrationStatus)); return durableOrchestrationStatus.RuntimeStatus switch { OrchestrationRuntimeStatus.Pending => OperationRuntimeStatus.NotStarted, OrchestrationRuntimeStatus.Running => OperationRuntimeStatus.Running, OrchestrationRuntimeStatus.ContinuedAsNew => OperationRuntimeStatus.Running, OrchestrationRuntimeStatus.Completed => OperationRuntimeStatus.Completed, OrchestrationRuntimeStatus.Failed => OperationRuntimeStatus.Failed, OrchestrationRuntimeStatus.Canceled => OperationRuntimeStatus.Canceled, OrchestrationRuntimeStatus.Terminated => OperationRuntimeStatus.Canceled, _ => OperationRuntimeStatus.Unknown }; } } }
50.232558
130
0.660648
[ "MIT" ]
ChimpPACS/dicom-server
src/Microsoft.Health.Dicom.Operations.Client/Extensions/DurableOrchestrationStatusExtensions.cs
2,162
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20190901 { public static class GetBastionShareableLink { /// <summary> /// Response for all the Bastion Shareable Link endpoints. /// </summary> public static Task<GetBastionShareableLinkResult> InvokeAsync(GetBastionShareableLinkArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetBastionShareableLinkResult>("azure-nextgen:network/v20190901:getBastionShareableLink", args ?? new GetBastionShareableLinkArgs(), options.WithVersion()); } public sealed class GetBastionShareableLinkArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the Bastion Host. /// </summary> [Input("bastionHostName", required: true)] public string BastionHostName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; [Input("vms")] private List<Inputs.BastionShareableLinkArgs>? _vms; /// <summary> /// List of VM references. /// </summary> public List<Inputs.BastionShareableLinkArgs> Vms { get => _vms ?? (_vms = new List<Inputs.BastionShareableLinkArgs>()); set => _vms = value; } public GetBastionShareableLinkArgs() { } } [OutputType] public sealed class GetBastionShareableLinkResult { /// <summary> /// Gets or sets the URL to get the next set of results. /// </summary> public readonly string? NextLink; /// <summary> /// List of Bastion Shareable Links for the request. /// </summary> public readonly ImmutableArray<Outputs.BastionShareableLinkResponseResult> Value; [OutputConstructor] private GetBastionShareableLinkResult( string? nextLink, ImmutableArray<Outputs.BastionShareableLinkResponseResult> value) { NextLink = nextLink; Value = value; } } }
32.220779
210
0.630391
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20190901/GetBastionShareableLink.cs
2,481
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using Umbrella.Utilities; namespace Umbrella.Legacy.WebUtilities.Extensions { //TODO: Add unit tests public static class StringExtensions { /// <summary> /// Converts the provided app-relative path into an absolute Url containing the /// full host name /// </summary> /// <param name="relativeUrl">App-Relative path</param> /// <returns>Provided relativeUrl parameter as fully qualified Url</returns> /// <example>~/path/to/foo to http://www.web.com/path/to/foo</example> public static string ToAbsoluteUrl(this string relativeUrl, Uri requestUri, string schemeOverride = null, string hostOverride = null, int portOverride = 0) { Guard.ArgumentNotNullOrWhiteSpace(relativeUrl, nameof(relativeUrl)); Guard.ArgumentNotNull(requestUri, nameof(requestUri)); if (relativeUrl.StartsWith("/")) relativeUrl = relativeUrl.Insert(0, "~"); if (!relativeUrl.StartsWith("~/")) relativeUrl = relativeUrl.Insert(0, "~/"); var port = portOverride > 0 ? portOverride.ToString() : (requestUri.Port != 80 ? (":" + requestUri.Port) : string.Empty); return string.Format("{0}://{1}{2}{3}", schemeOverride ?? requestUri.Scheme, hostOverride ?? requestUri.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl)); } } }
40.692308
163
0.642722
[ "MIT" ]
Zinofi/umbrella
Legacy/src/Umbrella.Legacy.WebUtilities/Extensions/StringExtensions.cs
1,589
C#
using System; using System.Collections.Generic; using MFiles.VAF.Configuration; using MFilesAPI; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace MFiles.VAF.Extensions.Tests.ExtensionMethods.ObjVerEx { /// <summary> /// Tests <see cref="ObjVerExExtensionMethods.TryGetPropertyText(Common.ObjVerEx, out string, VAF.Configuration.MFIdentifier, string)"/> /// </summary> [TestClass] public class TryGetPropertyText : TestBaseWithVaultMock { #region Class for props params public class PropertyDefTestEnvironment { public PropertyDefTestEnvironment(MFIdentifier prop, Common.ObjVerEx objverEx) { Ident = prop; IsResolved = prop?.IsResolved ?? false; IsAssigned = IsResolved && null != objverEx && objverEx.HasProperty(prop); Value = IsResolved ? objverEx.GetPropertyText(prop) : null; } public MFIdentifier Ident; public bool IsResolved; public bool IsAssigned; public string Value; public override string ToString() { return $"\n- #PropDef: {Ident?.ID.ToString() ?? "null"}" + $"\n- Resolved: {IsResolved}\n- Assigned: {IsAssigned}" + $"\n- Value: {(null == Value ? "null" : "\"" + Value + "\"")}"; } } #endregion #region Initialized MFIdentifier and ObjVerEx objects for properties for testing private Common.ObjVerEx objVerEx; private const Common.ObjVerEx nullObjVerEx = null; private const int idCustomProp = 1111; private const string aliasCustomProp = "PD.Test"; private PropertyDefTestEnvironment envNull; private PropertyDefTestEnvironment envNameOrTitle; private PropertyDefTestEnvironment envKeywords; private PropertyDefTestEnvironment envMessageID; private PropertyDefTestEnvironment envCustomProp; private PropertyDefTestEnvironment envNotResolved; private List<PropertyDefTestEnvironment> ListEnvironments => new List<PropertyDefTestEnvironment>() { envNull, envNameOrTitle, envKeywords, envMessageID, envCustomProp, envNotResolved }; #endregion /// <summary> /// Ensures that a null <see cref="Common.ObjVerEx"/> reference throws an <see cref="ArgumentNullException"/>. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TryGetPropertyText_ThrowsIfNullObjVerEx() => _ = nullObjVerEx.TryGetPropertyText(envNameOrTitle.Ident, out _); /// <summary> /// Ensures that not resolved <see cref="MFIdentifier"/> objects return <see cref="true"/> /// </summary> [TestMethod] public void TryGetPropertyText_ResultForNullIdentifier() => Assert.IsFalse(objVerEx.TryGetPropertyText(envNull.Ident, out _)); /// <summary> /// Ensures that not resolved <see cref="MFIdentifier"/> objects return <see cref="true"/> /// </summary> [TestMethod] public void TryGetPropertyText_ResultForNotResolved() => Assert.IsFalse(objVerEx.TryGetPropertyText(envNotResolved.Ident, out _)); /// <summary> /// Check all return values for all entries /// </summary> [TestMethod] public void TryGetPropertyText_CheckOutputForInitializedEntries() { foreach (PropertyDefTestEnvironment env in ListEnvironments) { Assert.AreEqual(env.IsResolved, objVerEx.TryGetPropertyText(env.Ident, out string result)); Assert.AreEqual(env.Value, result); } } #region Test initialization /// <summary> /// Initialize <see cref="Common.ObjVerEx"/> object with property Name or Title set to <see cref="valueNameOrTitle"/>, /// property MessageID set to <see cref="valueMessageID"/> (null) and property Keywords known but not set. /// </summary> [TestInitialize] public void TryGetPropertyText_Setup() { // Mock the property definition operations object. Mock<VaultPropertyDefOperations> propertyDefinitionsMock = new Mock<VaultPropertyDefOperations>(); propertyDefinitionsMock.Setup(m => m.GetPropertyDefIDByAlias(It.IsAny<string>())) .Returns((string propertyAlias) => { return propertyAlias == aliasCustomProp ? idCustomProp : -1; }) .Verifiable(); propertyDefinitionsMock.Setup(m => m.GetPropertyDef(It.IsAny<int>())) .Returns((int propertyDef) => { switch (propertyDef) { case (int) MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle: case (int) MFBuiltInPropertyDef.MFBuiltInPropertyDefKeywords: case (int) MFBuiltInPropertyDef.MFBuiltInPropertyDefMessageID: case idCustomProp: return new PropertyDef { ID = propertyDef, DataType = MFDataType.MFDatatypeText, Name = $"Property_{propertyDef}", }; default: return null; } }) .Verifiable(); // Mock the vault. Mock<Vault> vaultMock = GetVaultMock(); vaultMock.Setup(m => m.PropertyDefOperations).Returns(propertyDefinitionsMock.Object); // Set up the data for the ObjVerEx. ObjVer objVer = new ObjVer(); objVer.SetIDs((int) MFBuiltInObjectType.MFBuiltInObjectTypeDocument, ID: 1, Version: 1); Mock<ObjectVersion> objectVersionMock = new Mock<ObjectVersion>(); objectVersionMock.SetupGet(m => m.ObjVer).Returns(objVer); // Setup properties for NameOrTitle and MessageID (NOT: Keywords) PropertyValue pv; PropertyValues properties = new PropertyValues(); { // NameOrTitle pv = new PropertyValue { PropertyDef = (int) MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle, }; pv.TypedValue.SetValue(MFDataType.MFDatatypeText, "valueNameOrTitle"); properties.Add(1, pv); // MessageID pv = new PropertyValue { PropertyDef = (int) MFBuiltInPropertyDef.MFBuiltInPropertyDefMessageID, }; pv.TypedValue.SetValue(MFDataType.MFDatatypeText, null); properties.Add(2, pv); // CustomProp pv = new PropertyValue { PropertyDef = idCustomProp, }; pv.TypedValue.SetValue(MFDataType.MFDatatypeText, "valueCustomProp"); properties.Add(3, pv); } // Create the ObjVerEx. objVerEx = new Common.ObjVerEx(vaultMock.Object, objectVersionMock.Object, properties); // Get the test property params object MFIdentifier identCurrent = null; envNull = new PropertyDefTestEnvironment(identCurrent, objVerEx); identCurrent = new MFIdentifier((int) MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle); identCurrent.Resolve(vaultMock.Object, typeof(PropertyDef)); envNameOrTitle = new PropertyDefTestEnvironment(identCurrent, objVerEx); identCurrent = new MFIdentifier((int) MFBuiltInPropertyDef.MFBuiltInPropertyDefKeywords); identCurrent.Resolve(vaultMock.Object, typeof(PropertyDef)); envKeywords = new PropertyDefTestEnvironment(identCurrent, objVerEx); identCurrent = new MFIdentifier((int) MFBuiltInPropertyDef.MFBuiltInPropertyDefMessageID); identCurrent.Resolve(vaultMock.Object, typeof(PropertyDef)); envMessageID= new PropertyDefTestEnvironment(identCurrent, objVerEx); identCurrent = new MFIdentifier(aliasCustomProp); identCurrent.Resolve(vaultMock.Object, typeof(PropertyDef)); envCustomProp = new PropertyDefTestEnvironment(identCurrent, objVerEx); identCurrent = new MFIdentifier("incorrectAlias"); identCurrent.Resolve(vaultMock.Object, typeof(PropertyDef)); envNotResolved = new PropertyDefTestEnvironment(identCurrent, objVerEx); } #endregion } }
35.125604
137
0.734837
[ "MIT" ]
falk-huth-ewerk/VAF.Extensions.Community
MFiles.VAF.Extensions.Tests/ExtensionMethods/ObjVerEx/TryGetPropertyText.cs
7,273
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Caching; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Backgrounds; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Input; using osu.Game.Input.Bindings; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.Toolbar { public abstract class ToolbarButton : OsuClickableContainer, IKeyBindingHandler<GlobalAction> { protected GlobalAction? Hotkey { get; set; } public void SetIcon(Drawable icon) { IconContainer.Icon = icon; IconContainer.Show(); } [Resolved] private TextureStore textures { get; set; } public void SetIcon(string texture) => SetIcon(new Sprite { Texture = textures.Get(texture), }); public string Text { get => DrawableText.Text; set => DrawableText.Text = value; } public string TooltipMain { get => tooltip1.Text; set => tooltip1.Text = value; } public string TooltipSub { get => tooltip2.Text; set => tooltip2.Text = value; } protected virtual Anchor TooltipAnchor => Anchor.TopLeft; protected ConstrainedIconContainer IconContainer; protected SpriteText DrawableText; protected Box HoverBackground; private readonly Box flashBackground; private readonly FillFlowContainer tooltipContainer; private readonly SpriteText tooltip1; private readonly SpriteText tooltip2; private readonly SpriteText keyBindingTooltip; protected FillFlowContainer Flow; [Resolved] private KeyBindingStore keyBindings { get; set; } protected ToolbarButton() : base(HoverSampleSet.Loud) { Width = Toolbar.HEIGHT; RelativeSizeAxes = Axes.Y; Children = new Drawable[] { HoverBackground = new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(80).Opacity(180), Blending = BlendingParameters.Additive, Alpha = 0, }, flashBackground = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0, Colour = Color4.White.Opacity(100), Blending = BlendingParameters.Additive, }, Flow = new FillFlowContainer { Direction = FillDirection.Horizontal, Spacing = new Vector2(5), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Padding = new MarginPadding { Left = Toolbar.HEIGHT / 2, Right = Toolbar.HEIGHT / 2 }, RelativeSizeAxes = Axes.Y, AutoSizeAxes = Axes.X, Children = new Drawable[] { IconContainer = new ConstrainedIconContainer { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Size = new Vector2(26), Alpha = 0, }, DrawableText = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, }, }, tooltipContainer = new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.Both, // stops us being considered in parent's autosize Anchor = TooltipAnchor.HasFlag(Anchor.x0) ? Anchor.BottomLeft : Anchor.BottomRight, Origin = TooltipAnchor, Position = new Vector2(TooltipAnchor.HasFlag(Anchor.x0) ? 5 : -5, 5), Alpha = 0, Children = new Drawable[] { tooltip1 = new OsuSpriteText { Anchor = TooltipAnchor, Origin = TooltipAnchor, Shadow = true, Font = OsuFont.GetFont(size: 22, weight: FontWeight.Bold), }, new FillFlowContainer { AutoSizeAxes = Axes.Both, Anchor = TooltipAnchor, Origin = TooltipAnchor, Direction = FillDirection.Horizontal, Children = new[] { tooltip2 = new OsuSpriteText { Shadow = true }, keyBindingTooltip = new OsuSpriteText { Shadow = true } } } } } }; } private readonly Cached tooltipKeyBinding = new Cached(); [BackgroundDependencyLoader] private void load() { keyBindings.KeyBindingChanged += () => tooltipKeyBinding.Invalidate(); updateKeyBindingTooltip(); } private void updateKeyBindingTooltip() { if (tooltipKeyBinding.IsValid) return; var binding = keyBindings.Query().Find(b => (GlobalAction)b.Action == Hotkey); var keyBindingString = binding?.KeyCombination.ReadableString(); keyBindingTooltip.Text = !string.IsNullOrEmpty(keyBindingString) ? $" ({keyBindingString})" : string.Empty; tooltipKeyBinding.Validate(); } protected override bool OnMouseDown(MouseDownEvent e) => true; protected override bool OnClick(ClickEvent e) { flashBackground.FadeOutFromOne(800, Easing.OutQuint); tooltipContainer.FadeOut(100); return base.OnClick(e); } protected override bool OnHover(HoverEvent e) { updateKeyBindingTooltip(); HoverBackground.FadeIn(200); tooltipContainer.FadeIn(100); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { HoverBackground.FadeOut(200); tooltipContainer.FadeOut(100); } public bool OnPressed(GlobalAction action) { if (action == Hotkey) { Click(); return true; } return false; } public void OnReleased(GlobalAction action) { } } public class OpaqueBackground : Container { public OpaqueBackground() { RelativeSizeAxes = Axes.Both; Masking = true; MaskingSmoothness = 0; EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }; Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(30) }, new Triangles { RelativeSizeAxes = Axes.Both, ColourLight = OsuColour.Gray(40), ColourDark = OsuColour.Gray(20), }, }; } } }
34.365079
120
0.491224
[ "MIT" ]
AaqibAhamed/osu
osu.Game/Overlays/Toolbar/ToolbarButton.cs
8,411
C#
using System; namespace ShopBackend.Dtos { public class UserLoginDto { public UserLoginDto() { } public string Email { get; set; } public string Username { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } } }
17.157895
51
0.564417
[ "MIT" ]
DimitarKazakov/React-Project
backend/ShopBackends/Dtos/UserLoginDto.cs
328
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.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Rest Client Runtime Tests")] [assembly: AssemblyDescription("Tests for the Microsoft Rest Client Runtime.")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.4.2.0")] [assembly: AssemblyInformationalVersion("1.4.2.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft AutoRest ClientRuntime Tests")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
42.842105
95
0.77887
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ClientRuntime/Microsoft.Rest.ClientRuntime.Tests/Properties/AssemblyInfo.cs
814
C#
using System.Collections.Concurrent; namespace Csla.Channels.RabbitMq { internal static class Wip { public static readonly ConcurrentDictionary<string, WipItem> WorkInProgress = new ConcurrentDictionary<string, WipItem>(); } internal class WipItem { public Csla.Reflection.AsyncManualResetEvent ResetEvent { get; set; } public byte[] Response { get; set; } } }
23.235294
82
0.726582
[ "MIT" ]
Alstig/csla
Source/Csla.Channels.RabbitMq/WorkInProgress.cs
397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace api.importacao { 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.777778
70
0.645115
[ "Apache-2.0" ]
claudiocasa/Importacao
api.importacao/Program.cs
696
C#
// CivOne // // To the extent possible under law, the person who associated CC0 with // CivOne has waived all copyright and related or neighboring rights // to CivOne. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. using System; using System.Linq; using CivOne.Enums; using CivOne.Events; using CivOne.Graphics; using CivOne.IO; using CivOne.UserInterface; using static CivOne.Enums.AspectRatio; using static CivOne.Enums.CursorType; using static CivOne.Enums.DestroyAnimation; using static CivOne.Enums.GraphicsMode; namespace CivOne.Screens { [Break, Expand] internal class Setup : BaseScreen { private const int MenuFont = 6; private bool _update = true; protected override bool HasUpdate(uint gameTick) { if (!_update) return false; _update = false; if (!HasMenu) { MainMenu(); } return false; } private void BrowseForSoundFiles(object sender, MenuItemEventArgs<int> args) { string path = Runtime.BrowseFolder("Location of Civilization for Windows sound files"); if (path == null) { // User pressed cancel return; } FileSystem.CopySoundFiles(path); } private void BrowseForPlugins(object sender, MenuItemEventArgs<int> args) { string path = Runtime.BrowseFolder("Location of CivOne plugin(s)"); if (path == null) { // User pressed cancel return; } CloseMenus(); MainMenu(2); FileSystem.CopyPlugins(path); } private void CreateMenu(string title, int activeItem, MenuItemEventHandler<int> always, params MenuItem<int>[] items) => AddMenu(new Menu("Setup", Palette) { Title = $"{title.ToUpper()}:", TitleColour = 15, ActiveColour = 11, TextColour = 5, DisabledColour = 8, FontId = MenuFont, IndentTitle = 2 } .Items(items) .Always(always) .Center(this) .SetActiveItem(activeItem) ); private void CreateMenu(string title, MenuItemEventHandler<int> always, params MenuItem<int>[] items) => CreateMenu(title, -1, always, items); private void CreateMenu(string title, int activeItem, params MenuItem<int>[] items) => CreateMenu(title, activeItem, null, items); private void CreateMenu(string title, params MenuItem<int>[] items) => CreateMenu(title, -1, null, items); private MenuItemEventHandler<int> GotoMenu(Action<int> action, int selectedItem = 0) => (s, a) => { CloseMenus(); action(selectedItem); }; private MenuItemEventHandler<int> GotoMenu(Action action) => (s, a) => { CloseMenus(); action(); }; private MenuItemEventHandler<int> GotoScreen<T>(Action doneAction) where T : IScreen, new() => (s, a) => { CloseMenus(); T screen = new T(); screen.Closed += (sender, args) => doneAction(); Common.AddScreen(screen); }; private MenuItemEventHandler<int> CloseScreen(Action action = null) => (s, a) => { Destroy(); if (action != null) action(); }; private void ChangeWindowTitle() { RuntimeHandler.Runtime.WindowTitle = Settings.WindowTitle; SettingsMenu(0); } private void MainMenu(int activeItem = 0) => CreateMenu("CivOne Setup", activeItem, MenuItem.Create("Settings").OnSelect(GotoMenu(SettingsMenu)), MenuItem.Create("Patches").OnSelect(GotoMenu(PatchesMenu)), MenuItem.Create("Plugins").OnSelect(GotoMenu(PluginsMenu)), MenuItem.Create("Game Options").OnSelect(GotoMenu(GameOptionsMenu)), MenuItem.Create("Launch Game").OnSelect(CloseScreen()), MenuItem.Create("Quit").OnSelect(CloseScreen(Runtime.Quit)) ); private void SettingsMenu(int activeItem = 0) => CreateMenu("Settings", activeItem, MenuItem.Create($"Window Title: {Settings.WindowTitle}").OnSelect(GotoScreen<WindowTitle>(ChangeWindowTitle)), MenuItem.Create($"Graphics Mode: {Settings.GraphicsMode.ToText()}").OnSelect(GotoMenu(GraphicsModeMenu)), MenuItem.Create($"Aspect Ratio: {Settings.AspectRatio.ToText()}").OnSelect(GotoMenu(AspectRatioMenu)), MenuItem.Create($"Full Screen: {Settings.FullScreen.YesNo()}").OnSelect(GotoMenu(FullScreenMenu)), MenuItem.Create($"Window Scale: {Settings.Scale}x").OnSelect(GotoMenu(WindowScaleMenu)), MenuItem.Create("In-game sound").OnSelect(GotoMenu(SoundMenu)), MenuItem.Create($"Back").OnSelect(GotoMenu(MainMenu, 0)) ); private void GraphicsModeMenu() => CreateMenu("Graphics Mode", GotoMenu(SettingsMenu, 1), MenuItem.Create($"{Graphics256.ToText()} (default)").OnSelect((s, a) => Settings.GraphicsMode = Graphics256).SetActive(() => Settings.GraphicsMode == Graphics256), MenuItem.Create(Graphics16.ToText()).OnSelect((s, a) => Settings.GraphicsMode = Graphics16).SetActive(() => Settings.GraphicsMode == Graphics16), MenuItem.Create("Back") ); private void AspectRatioMenu() => CreateMenu("Aspect Ratio", GotoMenu(SettingsMenu, 2), MenuItem.Create($"{Auto.ToText()} (default)").OnSelect((s, a) => Settings.AspectRatio = Auto).SetActive(() => Settings.AspectRatio == Auto), MenuItem.Create(Fixed.ToText()).OnSelect((s, a) => Settings.AspectRatio = Fixed).SetActive(() => Settings.AspectRatio == Fixed), MenuItem.Create(Scaled.ToText()).OnSelect((s, a) => Settings.AspectRatio = Scaled).SetActive(() => Settings.AspectRatio == Scaled), MenuItem.Create(ScaledFixed.ToText()).OnSelect((s, a) => Settings.AspectRatio = ScaledFixed).SetActive(() => Settings.AspectRatio == ScaledFixed), MenuItem.Create(AspectRatio.Expand.ToText()).OnSelect((s, a) => Settings.AspectRatio = AspectRatio.Expand).SetActive(() => Settings.AspectRatio == AspectRatio.Expand), MenuItem.Create("Back") ); private void FullScreenMenu() => CreateMenu("Full Screen", GotoMenu(SettingsMenu, 3), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.FullScreen = false).SetActive(() => !Settings.FullScreen), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.FullScreen = true).SetActive(() => Settings.FullScreen), MenuItem.Create("Back") ); private void WindowScaleMenu() => CreateMenu("Window Scale", GotoMenu(SettingsMenu, 4), MenuItem.Create("1x").OnSelect((s, a) => Settings.Scale = 1).SetActive(() => Settings.Scale == 1), MenuItem.Create("2x (default)").OnSelect((s, a) => Settings.Scale = 2).SetActive(() => Settings.Scale == 2), MenuItem.Create("3x").OnSelect((s, a) => Settings.Scale = 3).SetActive(() => Settings.Scale == 3), MenuItem.Create("4x").OnSelect((s, a) => Settings.Scale = 4).SetActive(() => Settings.Scale == 4), MenuItem.Create("Back") ); private void SoundMenu() => CreateMenu("In-game sound", GotoMenu(SettingsMenu, 5), MenuItem.Create("Browse for files...").OnSelect(BrowseForSoundFiles).SetEnabled(!FileSystem.SoundFilesExist()), MenuItem.Create("Back") ); private void PatchesMenu(int activeItem = 0) => CreateMenu("Patches", activeItem, MenuItem.Create($"Reveal world: {Settings.RevealWorld.YesNo()}").OnSelect(GotoMenu(RevealWorldMenu)), MenuItem.Create($"Side bar location: {(Settings.RightSideBar ? "right" : "left")}").OnSelect(GotoMenu(SideBarMenu)), MenuItem.Create($"Debug menu: {Settings.DebugMenu.YesNo()}").OnSelect(GotoMenu(DebugMenuMenu)), MenuItem.Create($"Cursor type: {Settings.CursorType.ToText()}").OnSelect(GotoMenu(CursorTypeMenu)), MenuItem.Create($"Destroy animation: {Settings.DestroyAnimation.ToText()}").OnSelect(GotoMenu(DestroyAnimationMenu)), MenuItem.Create($"Enable Deity difficulty: {Settings.DeityEnabled.YesNo()}").OnSelect(GotoMenu(DeityEnabledMenu)), MenuItem.Create($"Enable (no keypad) arrow helper: {Settings.ArrowHelper.YesNo()}").OnSelect(GotoMenu(ArrowHelperMenu)), MenuItem.Create($"Custom map sizes (experimental): {Settings.CustomMapSize.YesNo()}").OnSelect(GotoMenu(CustomMapSizeMenu)), MenuItem.Create($"Use smart PathFinding for \"goto\": {Settings.PathFinding.YesNo()}").OnSelect(GotoMenu(PathFindingMenu)), MenuItem.Create($"Use auto-settlers-cheat: {Settings.AutoSettlers.YesNo()}").OnSelect(GotoMenu(AutoSettlersMenu)), MenuItem.Create("Back").OnSelect(GotoMenu(MainMenu, 1)) ); private void RevealWorldMenu() => CreateMenu("Reveal world", GotoMenu(PatchesMenu, 0), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.RevealWorld = false).SetActive(() => !Settings.RevealWorld), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.RevealWorld = true).SetActive(() => Settings.RevealWorld), MenuItem.Create("Back") ); private void SideBarMenu() => CreateMenu("Side bar location", GotoMenu(PatchesMenu, 1), MenuItem.Create("Left (default)").OnSelect((s, a) => Settings.RightSideBar = false).SetActive(() => !Settings.RightSideBar), MenuItem.Create("Right").OnSelect((s, a) => Settings.RightSideBar = true).SetActive(() => Settings.RightSideBar), MenuItem.Create("Back") ); private void DebugMenuMenu() => CreateMenu("Show debug menu", GotoMenu(PatchesMenu, 2), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.DebugMenu = false).SetActive(() => !Settings.DebugMenu), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.DebugMenu = true).SetActive(() => Settings.DebugMenu), MenuItem.Create("Back") ); private void CursorTypeMenu() => CreateMenu("Mouse cursor type", GotoMenu(PatchesMenu, 3), MenuItem.Create(Default.ToText()).OnSelect((s, a) => Settings.CursorType = Default).SetActive(() => Settings.CursorType == Default && FileSystem.DataFilesExist(FileSystem.MouseCursorFiles)).SetEnabled(FileSystem.DataFilesExist(FileSystem.MouseCursorFiles)), MenuItem.Create(Builtin.ToText()).OnSelect((s, a) => Settings.CursorType = Builtin).SetActive(() => Settings.CursorType == Builtin || (Settings.CursorType == Default && !FileSystem.DataFilesExist(FileSystem.MouseCursorFiles))), MenuItem.Create(Native.ToText()).OnSelect((s, a) => Settings.CursorType = Native).SetActive(() => Settings.CursorType == Native), MenuItem.Create("Back") ); private void DestroyAnimationMenu() => CreateMenu("Destroy animation", GotoMenu(PatchesMenu, 4), MenuItem.Create(Sprites.ToText()).OnSelect((s, a) => Settings.DestroyAnimation = Sprites).SetActive(() => Settings.DestroyAnimation == Sprites), MenuItem.Create(Noise.ToText()).OnSelect((s, a) => Settings.DestroyAnimation = Noise).SetActive(() => Settings.DestroyAnimation == Noise), MenuItem.Create("Back") ); private void DeityEnabledMenu() => CreateMenu("Enable Deity difficulty", GotoMenu(PatchesMenu, 5), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.DeityEnabled = false).SetActive(() => !Settings.DeityEnabled), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.DeityEnabled = true).SetActive(() => Settings.DeityEnabled), MenuItem.Create("Back") ); private void ArrowHelperMenu() => CreateMenu("Enable (no keypad) arrow helper", GotoMenu(PatchesMenu, 6), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.ArrowHelper = false).SetActive(() => !Settings.ArrowHelper), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.ArrowHelper = true).SetActive(() => Settings.ArrowHelper), MenuItem.Create("Back") ); private void CustomMapSizeMenu() => CreateMenu("Custom map sizes (experimental)", GotoMenu(PatchesMenu, 7), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.CustomMapSize = false).SetActive(() => !Settings.CustomMapSize), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.CustomMapSize = true).SetActive(() => Settings.CustomMapSize), MenuItem.Create("Back") ); private void PathFindingMenu() => CreateMenu("Use smart PathFinding for \"goto\"", GotoMenu(PatchesMenu, 8), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.PathFinding = false).SetActive(() => !Settings.PathFinding), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.PathFinding = true).SetActive(() => Settings.PathFinding), MenuItem.Create("Back") ); private void AutoSettlersMenu() => CreateMenu("Use auto settlers cheat", GotoMenu(PatchesMenu, 9), MenuItem.Create($"{false.YesNo()} (default)").OnSelect((s, a) => Settings.AutoSettlers = false).SetActive(() => !Settings.AutoSettlers), MenuItem.Create(true.YesNo()).OnSelect((s, a) => Settings.AutoSettlers = true).SetActive(() => Settings.AutoSettlers), MenuItem.Create("Back") ); private void PluginsMenu(int activeItem = 0) => CreateMenu("Plugins", activeItem, new MenuItem<int>[0] .Concat( Reflect.Plugins().Any() ? Reflect.Plugins().Select(x => MenuItem.Create(x.ToString()).SetEnabled(!x.Deleted).OnSelect(GotoMenu(PluginMenu(x.Id, x)))) : new [] { MenuItem.Create("No plugins installed").Disable() } ) .Concat(new [] { MenuItem.Create(null).Disable(), MenuItem.Create("Add plugins").OnSelect(BrowseForPlugins), MenuItem.Create("Back").OnSelect(GotoMenu(MainMenu, 2)) }).ToArray() ); private Action PluginMenu(int item, Plugin plugin) => () => CreateMenu(plugin.Name, 0, MenuItem.Create($"Version: {plugin.Version}").Disable(), MenuItem.Create($"Author: {plugin.Author}").Disable(), MenuItem.Create($"Status: {plugin.Enabled.EnabledDisabled()}").OnSelect(GotoMenu(PluginStatusMenu(item, plugin))), MenuItem.Create($"Delete plugin").OnSelect(GotoMenu(PluginDeleteMenu(item, plugin))), MenuItem.Create("Back").OnSelect(GotoMenu(PluginsMenu, item)) ); private Action PluginStatusMenu(int item, Plugin plugin) => () => CreateMenu($"{plugin.Name} Status", (plugin.Enabled ? 1 : 0), GotoMenu(PluginMenu(item, plugin)), MenuItem.Create(false.EnabledDisabled()).OnSelect((s, a) => plugin.Enabled = false), MenuItem.Create(true.EnabledDisabled()).OnSelect((s, a) => plugin.Enabled = true), MenuItem.Create("Back") ); private Action PluginDeleteMenu(int item, Plugin plugin) => () => CreateMenu($"Delete {plugin.Name} from disk?", 0, MenuItem.Create(false.YesNo()).OnSelect(GotoMenu(PluginsMenu, item)), MenuItem.Create(true.YesNo()).OnSelect((s, a) => plugin.Delete()).OnSelect(GotoMenu(PluginsMenu, item)) ); private void GameOptionsMenu(int activeItem = 0) => CreateMenu("Game Options", activeItem, MenuItem.Create($"Instant Advice: {Settings.InstantAdvice.ToText()}").OnSelect(GotoMenu(GameOptionMenu(0, "Instant Advice", () => Settings.InstantAdvice, (GameOption option) => Settings.InstantAdvice = option))), MenuItem.Create($"AutoSave: {Settings.AutoSave.ToText()}").OnSelect(GotoMenu(GameOptionMenu(1, "AutoSave", () => Settings.AutoSave, (GameOption option) => Settings.AutoSave = option))), MenuItem.Create($"End of Turn: {Settings.EndOfTurn.ToText()}").OnSelect(GotoMenu(GameOptionMenu(2, "End of Turn", () => Settings.EndOfTurn, (GameOption option) => Settings.EndOfTurn = option))), MenuItem.Create($"Animations: {Settings.Animations.ToText()}").OnSelect(GotoMenu(GameOptionMenu(3, "Animations", () => Settings.Animations, (GameOption option) => Settings.Animations = option))), MenuItem.Create($"Sound: {Settings.Sound.ToText()}").OnSelect(GotoMenu(GameOptionMenu(4, "Sound", () => Settings.Sound, (GameOption option) => Settings.Sound = option))), MenuItem.Create($"Enemy Moves: {Settings.EnemyMoves.ToText()}").OnSelect(GotoMenu(GameOptionMenu(5, "Enemy Moves", () => Settings.EnemyMoves, (GameOption option) => Settings.EnemyMoves = option))), MenuItem.Create($"Civilopedia Text: {Settings.CivilopediaText.ToText()}").OnSelect(GotoMenu(GameOptionMenu(6, "Civilopedia Text", () => Settings.CivilopediaText, (GameOption option) => Settings.CivilopediaText = option))), MenuItem.Create($"Palace: {Settings.Palace.ToText()}").OnSelect(GotoMenu(GameOptionMenu(7, "Palace", () => Settings.Palace, (GameOption option) => Settings.Palace = option))), MenuItem.Create($"Tax Rate: {Settings.TaxRate * 10}%").OnSelect(GotoMenu(TaxRateMenu)), MenuItem.Create("Back").OnSelect(GotoMenu(MainMenu, 3)) ); private Action GameOptionMenu(int item, string title, Func<GameOption> getOption, Action<GameOption> setOption) => () => CreateMenu(title, GotoMenu(GameOptionsMenu, item), MenuItem.Create(GameOption.Default.ToText()).OnSelect((s, a) => setOption(GameOption.Default)).SetActive(() => getOption() == GameOption.Default), MenuItem.Create(GameOption.On.ToText()).OnSelect((s, a) => setOption(GameOption.On)).SetActive(() => getOption() == GameOption.On), MenuItem.Create(GameOption.Off.ToText()).OnSelect((s, a) => setOption(GameOption.Off)).SetActive(() => getOption() == GameOption.Off), MenuItem.Create("Back") ); private void TaxRateMenu() => CreateMenu("Window Scale", GotoMenu(GameOptionsMenu, 8), MenuItem.Create(" 0% Tax, 100% Science").OnSelect((s,a)=> Settings.TaxRate = 0).SetActive(() => Settings.TaxRate == 0), MenuItem.Create("10% Tax, 90% Science").OnSelect((s,a)=> Settings.TaxRate = 1).SetActive(() => Settings.TaxRate == 1), MenuItem.Create("20% Tax, 80% Science").OnSelect((s,a)=> Settings.TaxRate = 2).SetActive(() => Settings.TaxRate == 2), MenuItem.Create("30% Tax, 70% Science").OnSelect((s,a)=> Settings.TaxRate = 3).SetActive(() => Settings.TaxRate == 3), MenuItem.Create("40% Tax, 60% Science").OnSelect((s,a)=> Settings.TaxRate = 4).SetActive(() => Settings.TaxRate == 4), MenuItem.Create("50% Tax, 50% Science").OnSelect((s,a)=> Settings.TaxRate = 5).SetActive(() => Settings.TaxRate == 5), MenuItem.Create("60% Tax, 40% Science").OnSelect((s,a)=> Settings.TaxRate = 6).SetActive(() => Settings.TaxRate == 6), MenuItem.Create("70% Tax, 30% Science").OnSelect((s,a)=> Settings.TaxRate = 7).SetActive(() => Settings.TaxRate == 7), MenuItem.Create("80% Tax, 20% Science").OnSelect((s,a)=> Settings.TaxRate = 8).SetActive(() => Settings.TaxRate == 8), MenuItem.Create("90% Tax, 10% Science").OnSelect((s,a)=> Settings.TaxRate = 9).SetActive(() => Settings.TaxRate == 9), MenuItem.Create("100% Tax, 0% Science").OnSelect((s,a)=> Settings.TaxRate = 10).SetActive(() => Settings.TaxRate == 10), MenuItem.Create("Back") ); private void Resize(object sender, ResizeEventArgs args) { this.Clear(3); foreach (Menu menu in Menus["Setup"]) { menu.Center(this).ForceUpdate(); } _update = true; } public Setup() : base(MouseCursor.Pointer) { OnResize += Resize; Palette = Common.GetPalette256; this.Clear(3); } } }
54.486804
260
0.694456
[ "CC0-1.0" ]
Andersw88/CivOne
src/Screens/Setup.cs
18,580
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AutoCompare.Console")] [assembly: AssemblyTrademark("")] // 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("826cb065-1386-45f3-9dbe-85a58627e33e")]
41.45
84
0.782871
[ "Apache-2.0" ]
anandtpatel/AutoCompare
src/AutoCompare.Console/Properties/AssemblyInfo.cs
831
C#
using System.Reflection; 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("AWSSDK.MediaConvert")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Elemental MediaConvert. AWS Elemental MediaConvert is a file-based video conversion service that transforms media into formats required for traditional broadcast and for internet streaming to multi-screen devices.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.9.6")]
49.125
297
0.758906
[ "Apache-2.0" ]
InsiteVR/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/MediaConvert/Properties/AssemblyInfo.cs
1,572
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SportsFinal { public abstract class Sport : ISport, IScoring { public string Name { get; private set; } public string Description { get; private set; } public List<Score> MatchHistory { get; private set; } public Sport(string name = "Sport", string description = "SportsBall") { Name = name; Description = description; MatchHistory = new List<Score>(); } public void NewDescription(string description) { Description = description; } public void NewName(string name) { Name = name; } public virtual bool HasWin(int home, int away, int round) { if((home >= 10 || away >= 10) && home != away) return true; return false; } public virtual string ScoreToString(int home, int away, int round) { return $"Round: {round} | Home: {home}pts | Away: {away}pts"; } public virtual ITeam WhoWon(int home, int away, int round, ITeam homeTeam, ITeam awayTeam) { if(!HasWin(home, away, round)) return null; if (home > away) return homeTeam; return awayTeam; } } }
24.913793
98
0.542561
[ "MIT" ]
sim2kid/PROG-301-FA21
SportsFinal/Sport.cs
1,447
C#
using Abp; using Topshelf.HostConfigurators; using Topshelf.Logging; namespace Topshelf.Abp { public static class HostConfiguratorExtensions { public static HostConfigurator UseAbp(this HostConfigurator configurator, AbpBootstrapper abpBootstrapper) { var log = HostLogger.Get(typeof(HostConfiguratorExtensions)); log.Info("[Topshelf.Abp] Integration Started in host."); configurator.AddConfigurator(new AbpBuilderConfigurator(abpBootstrapper)); return configurator; } } }
29.473684
114
0.705357
[ "MIT" ]
a-merson/Topshelf.Abp.Integrations
src/Topshelf.Abp/HostConfiguratorExtensions.cs
562
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PlanningPoker2018_backend_2.Models; namespace PlanningPoker2018_backend_2.Controllers { [Produces("application/json")] [Route("api/RoomParticipants")] public class RoomParticipantsController : Controller { private readonly DatabaseContext _context; public RoomParticipantsController(DatabaseContext context) { _context = context; } // GET: api/RoomParticipants [HttpGet] public IEnumerable<RoomParticipant> GetRoomParticipant() { return _context.RoomParticipant; } // GET: api/RoomParticipants/5 [HttpGet("{id}")] public async Task<IActionResult> GetRoomParticipant([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var roomParticipant = await _context.RoomParticipant.SingleOrDefaultAsync(m => m.id == id); if (roomParticipant == null) { return NotFound(); } return Ok(roomParticipant); } // PUT: api/RoomParticipants/5 [HttpPut("{id}")] public async Task<IActionResult> PutRoomParticipant([FromRoute] int id, [FromBody] RoomParticipant roomParticipant) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != roomParticipant.id) { return BadRequest(); } _context.Entry(roomParticipant).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RoomParticipantExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/RoomParticipants [HttpPost] public async Task<IActionResult> PostRoomParticipant([FromBody] RoomParticipant roomParticipant) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.RoomParticipant.Add(roomParticipant); await _context.SaveChangesAsync(); return CreatedAtAction("GetRoomParticipant", new {roomParticipant.id }, roomParticipant); } // DELETE: api/RoomParticipants/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteRoomParticipant([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var roomParticipant = await _context.RoomParticipant.SingleOrDefaultAsync(m => m.id == id); if (roomParticipant == null) { return NotFound(); } _context.RoomParticipant.Remove(roomParticipant); await _context.SaveChangesAsync(); return Ok(roomParticipant); } private bool RoomParticipantExists(int id) { return _context.RoomParticipant.Any(e => e.id == id); } } }
28.317073
123
0.548665
[ "MIT" ]
Mieta/se2018-poker-backend
PlanningPoker2018-backend-2/Controllers/RoomParticipantsController.cs
3,485
C#
using Net.FreeORM.Logic.BaseDal; namespace Net.FreeORM.TestWFA.Source.DL { public class MainPostgreSqlDL: BaseDL { public MainPostgreSqlDL() : base("mainPgSql") { } } }
17.416667
40
0.617225
[ "Apache-2.0" ]
mustafasacli/Net.FreeORM.Data.Repo
Net.FreeORM.Test/Net.FreeORM.TestWFA/Source/DL/MainPostgreSqlDL.cs
211
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; namespace Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Runtime.Json { public class TokenReader : IDisposable { private readonly JsonTokenizer tokenizer; private JsonToken current; internal TokenReader(JsonTokenizer tokenizer) { this.tokenizer = tokenizer ?? throw new ArgumentNullException(nameof(tokenizer)); } internal void Next() { current = tokenizer.ReadNext(); } internal JsonToken Current => current; internal void Ensure(TokenKind kind, string readerName) { if (current.Kind != kind) { throw new ParserException($"Expected {kind} while reading {readerName}). Was {current}."); } } public void Dispose() { tokenizer.Dispose(); } } }
32.692308
107
0.497255
[ "MIT" ]
AlanFlorance/azure-powershell
src/HealthcareApis/generated/runtime/Parser/TokenReader.cs
1,239
C#
/** * Author: dyx1001 * Email: dyx1001@126.com * License: MIT * Git URL: https://github.com/dyx1001/BigBlueButtonAPI.NET */ using System; using System.Collections.Generic; using System.Linq; namespace BigBlueButtonAPI.Core { /// <summary> /// It contains the config data for the BigBlueButton API. /// Please visit the following site for details: /// http://docs.bigbluebutton.org/dev/api.html /// </summary> public class BigBlueButtonAPISettings { /// <summary> /// The BigBlueButton server API endpoint (usually the server’s hostname followed by <b>/bigbluebutton/api/</b>, for example: http://yourserver.com/bigbluebutton/api/ ). /// </summary> public string ServerAPIUrl { get; set; } /// <summary> /// The shared secret code that is needed for the BigBlueButton server API. /// You can retrieve it using the command in your BigBlueButton server: /// $ bbb-conf --secret /// </summary> public string SharedSecret { get; set; } } }
33.15625
177
0.641847
[ "MIT" ]
dyx1001/BigBlueButtonAPI.NET
Source/BigBlueButtonAPI.NET/Core/BigBlueButtonAPISettings.cs
1,065
C#
using System; using System.Collections.Generic; namespace Naticon.Handlers { /// <summary>System.DateTime.Parse based handler. To be used as a fallback mechanism.</summary> public class BCLDateTimeHandler : IHandler { public Span Handle(IList<Token> tokens, Options options) { var time = DateTime.Parse(options.OriginalPhrase); return new Span(time, time.AddSeconds(1)); } } }
26.2
96
0.745547
[ "MIT" ]
risadams/Naticon
src/Naticon/Handlers/BCLDateTimeHandler.cs
393
C#
/* * Copyright (C) 2016-2021 Kerygma Digital Co. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at https://mozilla.org/MPL/2.0/. */ using System.Collections.Generic; using System.Threading.Tasks; using BibleBot.Lib; namespace BibleBot.Backend.Models { public interface IBibleProvider { string Name { get; set; } Task<Verse> GetVerse(Reference reference, bool titlesEnabled, bool verseNumbersEnabled); Task<Verse> GetVerse(string reference, bool titlesEnabled, bool verseNumbersEnabled, Version version); Task<List<SearchResult>> Search(string query, Version version); } }
32.173913
110
0.725676
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
tenaciousprime/bahaibot
src/BibleBot.Backend/Models/BibleProvider.cs
740
C#
namespace HyperMapper.Vocab { public class FieldName { } }
11.666667
27
0.642857
[ "MIT" ]
mcintyre321/HyperMapper
HyperMapper/Vocab/FieldName.cs
70
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataLake.Store { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Creates an Azure Data Lake Store account management client. /// </summary> public partial class DataLakeStoreAccountManagementClient : ServiceClient<DataLakeStoreAccountManagementClient>, IDataLakeStoreAccountManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// The preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout in seconds for Long Running Operations. Default value is /// 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Whether a unique x-ms-client-request-id should be generated. When set to /// true a unique x-ms-client-request-id value is generated and included in /// each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAccountsOperations. /// </summary> public virtual IAccountsOperations Accounts { get; private set; } /// <summary> /// Gets the IFirewallRulesOperations. /// </summary> public virtual IFirewallRulesOperations FirewallRules { get; private set; } /// <summary> /// Gets the IVirtualNetworkRulesOperations. /// </summary> public virtual IVirtualNetworkRulesOperations VirtualNetworkRules { get; private set; } /// <summary> /// Gets the ITrustedIdProvidersOperations. /// </summary> public virtual ITrustedIdProvidersOperations TrustedIdProviders { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the ILocationsOperations. /// </summary> public virtual ILocationsOperations Locations { get; private set; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='httpClient'> /// HttpClient to be used /// </param> /// <param name='disposeHttpClient'> /// True: will dispose the provided httpClient on calling DataLakeStoreAccountManagementClient.Dispose(). False: will not dispose provided httpClient</param> protected DataLakeStoreAccountManagementClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreAccountManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeStoreAccountManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataLakeStoreAccountManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataLakeStoreAccountManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='httpClient'> /// HttpClient to be used /// </param> /// <param name='disposeHttpClient'> /// True: will dispose the provided httpClient on calling DataLakeStoreAccountManagementClient.Dispose(). False: will not dispose provided httpClient</param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeStoreAccountManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Accounts = new AccountsOperations(this); FirewallRules = new FirewallRulesOperations(this); VirtualNetworkRules = new VirtualNetworkRulesOperations(this); TrustedIdProviders = new TrustedIdProvidersOperations(this); Operations = new Operations(this); Locations = new LocationsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2016-11-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
40.916031
209
0.599316
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/datalake-store/Microsoft.Azure.Management.DataLake.Store/src/Generated/DataLakeStoreAccountManagementClient.cs
16,080
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { return VisitConditionalAccess(node, used: true); } // null when currently enclosing conditional access node // is not supposed to be lowered. private BoundExpression currentConditionalAccessTarget = null; private enum ConditionalAccessLoweringKind { None, NoCapture, CaptureReceiverByVal, CaptureReceiverByRef, DuplicateCode } // in simple cases could be left unlowered. // IL gen can generate more compact code for unlowered conditional accesses // by utilizing stack dup/pop instructions internal BoundExpression VisitConditionalAccess(BoundConditionalAccess node, bool used) { Debug.Assert(!this.inExpressionLambda); var loweredReceiver = this.VisitExpression(node.Receiver); var receiverType = loweredReceiver.Type; //TODO: if AccessExpression does not contain awaits, the node could be left unlowered (saves a temp), // but there seem to be no way of knowing that without walking AccessExpression. // For now we will just check that we are in an async method, but it would be nice // to have something more precise. var isAsync = this.factory.CurrentMethod.IsAsync; ConditionalAccessLoweringKind loweringKind; if (!receiverType.IsValueType && !isAsync && !node.Type.IsDynamic()) { // trivial cases can be handled more efficiently in IL gen loweringKind = ConditionalAccessLoweringKind.None; } else if(NeedsTemp(loweredReceiver, localsMayBeAssigned: false)) { if (receiverType.IsReferenceType || receiverType.IsNullableType()) { loweringKind = ConditionalAccessLoweringKind.CaptureReceiverByVal; } else { loweringKind = isAsync ? ConditionalAccessLoweringKind.DuplicateCode : ConditionalAccessLoweringKind.CaptureReceiverByRef; } } else { // locals do not need to be captured loweringKind = ConditionalAccessLoweringKind.NoCapture; } var previousConditionalAccesTarget = currentConditionalAccessTarget; LocalSymbol temp = null; BoundExpression unconditionalAccess = null; switch (loweringKind) { case ConditionalAccessLoweringKind.None: currentConditionalAccessTarget = null; break; case ConditionalAccessLoweringKind.NoCapture: currentConditionalAccessTarget = loweredReceiver; break; case ConditionalAccessLoweringKind.DuplicateCode: currentConditionalAccessTarget = loweredReceiver; unconditionalAccess = used? this.VisitExpression(node.AccessExpression) : this.VisitUnusedExpression(node.AccessExpression); goto case ConditionalAccessLoweringKind.CaptureReceiverByVal; case ConditionalAccessLoweringKind.CaptureReceiverByVal: temp = factory.SynthesizedLocal(receiverType); currentConditionalAccessTarget = factory.Local(temp); break; case ConditionalAccessLoweringKind.CaptureReceiverByRef: temp = factory.SynthesizedLocal(receiverType, refKind: RefKind.Ref); currentConditionalAccessTarget = factory.Local(temp); break; } BoundExpression loweredAccessExpression = used ? this.VisitExpression(node.AccessExpression) : this.VisitUnusedExpression(node.AccessExpression); currentConditionalAccessTarget = previousConditionalAccesTarget; TypeSymbol type = this.VisitType(node.Type); TypeSymbol nodeType = node.Type; TypeSymbol accessExpressionType = loweredAccessExpression.Type; if (accessExpressionType != nodeType && nodeType.IsNullableType()) { Debug.Assert(accessExpressionType == nodeType.GetNullableUnderlyingType()); loweredAccessExpression = factory.New((NamedTypeSymbol)nodeType, loweredAccessExpression); } else { Debug.Assert(accessExpressionType == nodeType || (accessExpressionType.SpecialType == SpecialType.System_Void && !used)); } BoundExpression result; var objectType = compilation.GetSpecialType(SpecialType.System_Object); switch (loweringKind) { case ConditionalAccessLoweringKind.None: Debug.Assert(!receiverType.IsValueType); result = node.Update(loweredReceiver, loweredAccessExpression, type); break; case ConditionalAccessLoweringKind.CaptureReceiverByVal: // capture the receiver into a temp loweredReceiver = factory.AssignmentExpression(factory.Local(temp), loweredReceiver); goto case ConditionalAccessLoweringKind.NoCapture; case ConditionalAccessLoweringKind.NoCapture: { // (object)r != null ? access : default(T) var condition = receiverType.IsNullableType() ? MakeOptimizedHasValue(loweredReceiver.Syntax, loweredReceiver) : factory.ObjectNotEqual( factory.Convert(objectType, loweredReceiver), factory.Null(objectType)); var consequence = loweredAccessExpression; var alternative = factory.Default(nodeType); result = RewriteConditionalOperator(node.Syntax, condition, consequence, alternative, null, nodeType); if (temp != null) { result = factory.Sequence(temp, result); } } break; case ConditionalAccessLoweringKind.CaptureReceiverByRef: // {ref T r; T v; // r = ref receiver; // (isClass && { v = r; r = ref v; v == null } ) ? // null; // r.Foo()} { var v = factory.SynthesizedLocal(receiverType); BoundExpression captureRef = factory.AssignmentExpression(factory.Local(temp), loweredReceiver, refKind: RefKind.Ref); BoundExpression isNull = factory.LogicalAnd( IsClass(receiverType, objectType), factory.Sequence( factory.AssignmentExpression(factory.Local(v), factory.Local(temp)), factory.AssignmentExpression(factory.Local(temp), factory.Local(v), RefKind.Ref), factory.ObjectEqual(factory.Convert(objectType, factory.Local(v)), factory.Null(objectType))) ); result = RewriteConditionalOperator(node.Syntax, isNull, factory.Default(nodeType), loweredAccessExpression, null, nodeType); result = factory.Sequence( ImmutableArray.Create(temp, v), captureRef, result ); } break; case ConditionalAccessLoweringKind.DuplicateCode: { Debug.Assert(!receiverType.IsNullableType()); // if we have a class, do regular conditional access via a val temp loweredReceiver = factory.AssignmentExpression(factory.Local(temp), loweredReceiver); BoundExpression ifClass = RewriteConditionalOperator(node.Syntax, factory.ObjectNotEqual( factory.Convert(objectType, loweredReceiver), factory.Null(objectType)), loweredAccessExpression, factory.Default(nodeType), null, nodeType); if (temp != null) { ifClass = factory.Sequence(temp, ifClass); } // if we have a struct, then just access unconditionally BoundExpression ifStruct = unconditionalAccess; // (object)(default(T)) != null ? ifStruct: ifClass result = RewriteConditionalOperator(node.Syntax, IsClass(receiverType, objectType), ifClass, ifStruct, null, nodeType); } break; default: throw ExceptionUtilities.Unreachable; } return result; } private BoundBinaryOperator IsClass(TypeSymbol receiverType, NamedTypeSymbol objectType) { return factory.ObjectEqual( factory.Convert(objectType, factory.Default(receiverType)), factory.Null(objectType)); } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { if (currentConditionalAccessTarget == null) { return node; } var newtarget = currentConditionalAccessTarget; if (newtarget.Type.IsNullableType()) { newtarget = MakeOptimizedGetValueOrDefault(node.Syntax, newtarget); } return newtarget; } } }
42.688645
184
0.522482
[ "Apache-2.0" ]
semihokur/pattern-matching-csharp
Src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ConditionalAccess.cs
11,656
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Text; using Silk.NET.Core.Native; using Ultz.SuperInvoke; namespace Silk.NET.Vulkan { public unsafe struct DeviceGroupSubmitInfo { public DeviceGroupSubmitInfo ( StructureType sType = StructureType.DeviceGroupSubmitInfo, void* pNext = default, uint waitSemaphoreCount = default, uint* pWaitSemaphoreDeviceIndices = default, uint commandBufferCount = default, uint* pCommandBufferDeviceMasks = default, uint signalSemaphoreCount = default, uint* pSignalSemaphoreDeviceIndices = default ) { SType = sType; PNext = pNext; WaitSemaphoreCount = waitSemaphoreCount; PWaitSemaphoreDeviceIndices = pWaitSemaphoreDeviceIndices; CommandBufferCount = commandBufferCount; PCommandBufferDeviceMasks = pCommandBufferDeviceMasks; SignalSemaphoreCount = signalSemaphoreCount; PSignalSemaphoreDeviceIndices = pSignalSemaphoreDeviceIndices; } /// <summary></summary> public StructureType SType; /// <summary></summary> public void* PNext; /// <summary></summary> public uint WaitSemaphoreCount; /// <summary></summary> public uint* PWaitSemaphoreDeviceIndices; /// <summary></summary> public uint CommandBufferCount; /// <summary></summary> public uint* PCommandBufferDeviceMasks; /// <summary></summary> public uint SignalSemaphoreCount; /// <summary></summary> public uint* PSignalSemaphoreDeviceIndices; } }
31.842105
73
0.667769
[ "MIT" ]
mcavanagh/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/DeviceGroupSubmitInfo.gen.cs
1,815
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Acs0; using AElf.Contracts.Deployer; using AElf.Contracts.Genesis; using AElf.Cryptography.ECDSA; using AElf.CSharp.Core; using AElf.Kernel; using AElf.Kernel.Blockchain.Application; using AElf.Kernel.Blockchain.Domain; using AElf.Kernel.SmartContract.Application; using AElf.Types; using Google.Protobuf; using MartinCostello.Logging.XUnit; using Microsoft.Extensions.DependencyInjection; using Volo.Abp; using Volo.Abp.Threading; using Xunit; using Xunit.Abstractions; namespace AElf.Contracts.TestKit { public class ContractTestBase : ContractTestBase<ContractTestModule> { } public class ContractTestBase<TModule> : AbpIntegratedTest<TModule> where TModule : ContractTestModule { private IReadOnlyDictionary<string, byte[]> _codes; public IReadOnlyDictionary<string, byte[]> Codes => _codes ??= ContractsDeployer.GetContractCodes<TModule>(); protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) { options.UseAutofac(); } protected void SetTestOutputHelper(ITestOutputHelper testOutputHelper) { GetRequiredService<ITestOutputHelperAccessor>().OutputHelper = testOutputHelper; } protected ISmartContractAddressService ContractAddressService => Application.ServiceProvider.GetRequiredService<ISmartContractAddressService>(); protected Address ContractZeroAddress => ContractAddressService.GetZeroSmartContractAddress(); public ContractTestBase() { var blockchainService = Application.ServiceProvider.GetService<IBlockchainService>(); var chain = AsyncHelper.RunSync(() => blockchainService.GetChainAsync()); var block = AsyncHelper.RunSync(()=>blockchainService.GetBlockByHashAsync(chain.GenesisBlockHash)); var transactionResultManager = Application.ServiceProvider.GetService<ITransactionResultManager>(); var transactionResults = AsyncHelper.RunSync(() => transactionResultManager.GetTransactionResultsAsync(block.Body.TransactionIds, block.GetHash())); foreach (var transactionResult in transactionResults) { Assert.True(transactionResult.Status == TransactionResultStatus.Mined, transactionResult.Error); } } protected async Task<Address> DeployContractAsync(int category, byte[] code, Hash name, ECKeyPair senderKey) { var zeroStub = GetTester<BasicContractZeroContainer.BasicContractZeroStub>(ContractZeroAddress, senderKey); var res = await zeroStub.DeploySmartContract.SendAsync(new ContractDeploymentInput() { Category = category, Code = ByteString.CopyFrom(code) }); return res.Output; } protected async Task<Address> DeploySystemSmartContract(int category, byte[] code, Hash name, ECKeyPair senderKey) { var zeroStub = GetTester<BasicContractZeroContainer.BasicContractZeroStub>(ContractZeroAddress, senderKey); var res = await zeroStub.DeploySystemSmartContract.SendAsync(new SystemContractDeploymentInput { Category = category, Code = ByteString.CopyFrom(code), Name = name, TransactionMethodCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList() }); if (res.TransactionResult == null || res.TransactionResult.Status != TransactionResultStatus.Mined) { throw new Exception($"DeploySystemSmartContract failed: {res.TransactionResult}"); } var address = await zeroStub.GetContractAddressByName.CallAsync(name); ContractAddressService.SetAddress(name, address); return res.Output; } protected T GetTester<T>(Address contractAddress, ECKeyPair senderKey) where T : ContractStubBase, new() { var factory = Application.ServiceProvider.GetRequiredService<IContractTesterFactory>(); return factory.Create<T>(contractAddress, senderKey); } protected IReadOnlyDictionary<string, byte[]> GetPatchedCodes(string dir) { return ContractsDeployer.GetContractCodes<TModule>(dir, true); } // byte[] ReadPatchedContractCode(Type contractType) // { // return ReadCode(ContractPatchedDllDir + contractType.Module + ".patched"); // } // // byte[] ReadCode(string path) // { // return File.Exists(path) // ? File.ReadAllBytes(path) // : throw new FileNotFoundException("Contract DLL cannot be found. " + path); // } } }
40.57377
119
0.67798
[ "MIT" ]
ezaruba/AElf
src/AElf.Contracts.TestKit/ContractTestBase.cs
4,950
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class RuleGroupRuleStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchSingleHeaderGetArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public RuleGroupRuleStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchSingleHeaderGetArgs() { } } }
35.653846
158
0.728155
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/RuleGroupRuleStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchSingleHeaderGetArgs.cs
927
C#
namespace Models { public class SampleDataModel : QueenModel { public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public byte Age { get; set; } } }
21.727273
45
0.560669
[ "MIT" ]
ephe09/RabbitMQ_helperServices-master
Models/SampleDataModel.cs
241
C#
using System; using System.Collections.Generic; using Inventor; public class MotionLimits { private Dictionary<ComponentOccurrence, bool> oldContactState = new Dictionary<ComponentOccurrence, bool>(); private Dictionary<ComponentOccurrence, bool> oldVisibleState = new Dictionary<ComponentOccurrence, bool>(); public void DoIsolation(ComponentOccurrence occ, bool isolate) { if (occ.SubOccurrences == null || occ.SubOccurrences.Count == 0) { if (isolate) { oldVisibleState[occ] = occ.Visible; occ.Visible = false; } else { occ.Visible = oldVisibleState[occ]; } } else { foreach (ComponentOccurrence oc in occ.SubOccurrences) { DoIsolation(oc, isolate); } } } public static ComponentOccurrence GetParent(ComponentOccurrence cO) { if (cO.ParentOccurrence != null) { return GetParent(cO.ParentOccurrence); } else { return cO; } } public void DoContactSetup(bool enable, params CustomRigidGroup[] groups) { if (enable) { oldContactState.Clear(); oldVisibleState.Clear(); } HashSet<AssemblyComponentDefinition> roots = new HashSet<AssemblyComponentDefinition>(); foreach (CustomRigidGroup group in groups) { foreach (ComponentOccurrence cO in group.occurrences) { roots.Add(GetParent(cO).Parent); } } foreach (AssemblyComponentDefinition cO in roots) { foreach (ComponentOccurrence cOo in cO.Occurrences) { DoIsolation(cOo, enable); } } foreach (CustomRigidGroup group in groups) { foreach (ComponentOccurrence cO in group.occurrences) { if (enable) { cO.Visible = true; oldContactState[cO] = cO.ContactSet; try { cO.ContactSet = true; } catch (Exception) { // Ignore } } else { cO.Visible = oldVisibleState[cO]; try { cO.ContactSet = oldContactState[cO]; } catch (Exception) { // Ignore } } } } } public static bool DID_COLLIDE = false; public static void OnCollisionEvent() { DID_COLLIDE = true; } }
27.514019
112
0.467052
[ "Apache-2.0" ]
NWalker1208/synthesis
exporters/BxDRobotExporter/robot_exporter/JointResolver/SkeletalStructure/MotionLimits.cs
2,946
C#
using Discord; using Discord.Audio; using ProGraduaatBot.Utilities; namespace ProGraduaatBot.Modules.Voice.Streaming { public class QueueStreamer : IEmbeddable { private CancellationTokenSource _cancellationTokenSource; private IVoiceChannel _voiceChannel; private IAudioClient _audioClient; private Thread _playThread; public readonly VoiceQueue Queue = new(); public QueueStreamer() { Queue.Pushed += OnQueuePushed; Queue.Popped += OnQueuePopped; Queue.Cleared += OnItemsCleared; Finished += OnFinished; } public IStreamable Current { get; private set; } public bool Loop { get; private set; } public IGuild Guild { get; private set; } // Events public event EventHandler Finished; public event EventHandler FinishedStream; public event EventHandler CurrentChanged; public event EventHandler ItemAdded; public event EventHandler ItemRemoved; public event EventHandler ItemsCleared; public event EventHandler Started; public event EventHandler Stopped; public event EventHandler Skipped; public event EventHandler Connected; public event EventHandler Disconnected; public event EventHandler LoopToggled; private Task OnDisconnected(Exception e) { Dispose(); Disconnected?.Invoke(this, EventArgs.Empty); return Task.CompletedTask; } private void OnFinished(object sender, EventArgs e) { _playThread = null; } private void OnQueuePushed(object sender, EventArgs e) { ItemAdded?.Invoke(this, new()); } private void OnItemsCleared(object sender, EventArgs e) { ItemsCleared?.Invoke(this, new()); } private void OnQueuePopped(object sender, EventArgs e) { ItemRemoved?.Invoke(this, new()); } public bool IsPlaying() { return _playThread != null; } public void ToggleLoop() { Loop = !Loop; LoopToggled?.Invoke(this, EventArgs.Empty); } private async Task Connect(IVoiceChannel channel) { if (_audioClient == null || _audioClient.ConnectionState != ConnectionState.Connected) { _audioClient = await channel.ConnectAsync(selfDeaf: true); _audioClient.Disconnected += OnDisconnected; Guild = channel.Guild; Connected?.Invoke(this, EventArgs.Empty); } } public async Task Play(IVoiceChannel channel) { if (IsPlaying()) { return; } _voiceChannel = channel; await Connect(_voiceChannel); _playThread = new(async () => { Started?.Invoke(this, EventArgs.Empty); while (_audioClient.ConnectionState == ConnectionState.Connected && (Queue.Count > 0 || Loop)) { if (Current == null || !Loop) { Current = Queue.Pop(); CurrentChanged?.Invoke(this, EventArgs.Empty); } _cancellationTokenSource = new(); try { await StreamManager.SendAsync(_audioClient, Current.GetStream(), _cancellationTokenSource.Token); } catch { } Current = null; FinishedStream?.Invoke(this, EventArgs.Empty); } Finished?.Invoke(this, EventArgs.Empty); }); _playThread.Start(); } public void Skip() { if (!IsPlaying() || _cancellationTokenSource == null) { return; } _cancellationTokenSource.Cancel(); Skipped?.Invoke(this, EventArgs.Empty); } public void Stop() { _voiceChannel.DisconnectAsync(); Stopped?.Invoke(this, EventArgs.Empty); } public void Dispose() { if (_audioClient != null) { _audioClient.Dispose(); } Queue.Clear(); } public EmbedBuilder GetEmbedBuilder() { EmbedBuilder builder = new(); builder.WithTitle("Queue"); builder.WithDescription("De muziek queue van deze guild"); builder.WithColor(Program.Configuration.GetDiscordColor()); if (Current != null) { string loopstring = String.Empty; if (Loop) { loopstring = "(Looping)"; } builder.AddField($"Nu {loopstring}", $"[{Current}]({Current.GetUrl()})"); builder.WithThumbnailUrl(Current.GetThumbnail()); } if (Queue.Count < 1) { builder.AddField("Queue", "Queue is leeg!"); return builder; } string items = String.Empty; int counter = 1; foreach (var item in Queue.GetList()) { string r = items + $"{counter}. [{item}]({item.GetUrl()})\n\n"; if (r.Length > 1024) { break; } items = r; counter++; } builder.AddField($"Queue ({Queue.Count})", items); return builder; } public Embed BuildEmbed() { return GetEmbedBuilder().Build(); } } }
23.147368
120
0.683947
[ "MIT" ]
Ho-Gent/ProGraduaat-Gent
src/ProGraduaatBot/Modules/Voice/Streaming/QueueStreamer.cs
4,400
C#