content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace OpenSleigh.Persistence.InMemory.Tests.Unit
{
internal class FakeLogger<T> : ILogger<T>
{
private readonly List<(LogLevel, string, Exception)> _logs = new();
public void Log<TState>(LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
{
_logs.Add((logLevel, state.ToString(), exception));
}
public IReadOnlyCollection<(LogLevel level, string message, Exception ex)> Logs => _logs;
public bool IsEnabled(LogLevel logLevel) => true;
public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}
}
} | 29.482759 | 97 | 0.625731 | [
"Apache-2.0"
] | Magicianred/OpenSleigh | tests/OpenSleigh.Persistence.InMemory.Tests/Unit/FakeLogger.cs | 857 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using FubuCore;
using StoryTeller.Engine;
namespace StoryTeller.Domain
{
public class Section : ITestPart, IPartHolder
{
private readonly List<ITestPart> _parts = new List<ITestPart>();
private FixtureLoader _loader;
private Section()
{
}
public Section(string fixtureName)
{
_loader = new FixtureKeyLoader(fixtureName, this);
}
public IList<ITestPart> Parts
{
get { return _parts; }
}
public string Description { get; set; }
public string FixtureName { get { return _loader.GetName(); } }
public string Label { get; set; }
#region ITestPart Members
public void AcceptVisitor(ITestVisitor visitor)
{
visitor.StartSection(this);
_parts.ForEach(x => x.AcceptVisitor(visitor));
visitor.EndSection(this);
}
public int StepCount()
{
return _parts.Sum(x => x.StepCount());
}
public IEnumerable<ITestPart> Children
{
get
{
foreach (ITestPart child in _parts)
{
yield return child;
foreach (ITestPart descendent in child.Children)
{
yield return descendent;
}
}
}
}
#endregion
public static Section For<T>() where T : IFixture, new()
{
var section = new Section();
section._loader = new FixtureLoader<T>(section);
return section;
}
public static Section For<T>(IList<ITestPart> list) where T : IFixture, new()
{
Section section = For<T>();
section._parts.AddRange(list);
return section;
}
public void StartFixture(ITestContext context)
{
_loader.LoadFixture(context);
}
public Section WithStep(string key, string data)
{
Step step = new Step(key).With(data);
_parts.Add(step);
return this;
}
public Section WithStep(string key, Action<Step> action)
{
var step = new Step(key);
_parts.Add(step);
action(step);
return this;
}
public Section WithStep(string key)
{
var step = new Step(key);
_parts.Add(step);
return this;
}
public string GetName()
{
return Label ?? _loader.GetName();
}
public Section WithComment(string text)
{
var comment = new Comment
{
Text = text
};
_parts.Add(comment);
return this;
}
public Section WithDescription(string text)
{
Description = text;
return this;
}
public override string ToString()
{
return string.Format("Section: {0}", GetName());
}
#region Nested type: FixtureKeyLoader
internal class FixtureKeyLoader : FixtureLoader
{
private readonly string _fixtureName;
private readonly Section _section;
public FixtureKeyLoader(string fixtureName, Section section)
{
_fixtureName = fixtureName;
_section = section;
}
#region FixtureLoader Members
public void LoadFixture(ITestContext context)
{
context.LoadFixture(_fixtureName, _section);
}
public string GetName()
{
return _fixtureName;
}
#endregion
}
#endregion
#region Nested type: FixtureLoader
internal interface FixtureLoader
{
void LoadFixture(ITestContext context);
string GetName();
}
internal class FixtureLoader<T> : FixtureLoader where T : IFixture, new()
{
private readonly Section _section;
public FixtureLoader(Section section)
{
_section = section;
}
#region FixtureLoader Members
public void LoadFixture(ITestContext context)
{
context.LoadFixture<T>(_section);
}
public string GetName()
{
return typeof(T).GetFixtureAlias();
}
#endregion
}
#endregion
}
} | 23.663507 | 86 | 0.483677 | [
"Apache-2.0"
] | mtscout6/StoryTeller2 | src/StoryTeller/Domain/Section.cs | 4,993 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using PizzaBox.Domain.Models;
using PizzaBox.Domain;
using System.Net.Mime;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace PizzaBox.Service.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PizzaSizeController : ControllerBase
{
private readonly IRepository _repository;
public PizzaSizeController(IRepository repository)
{
_repository = repository;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<APizzaSize> Get()
{
try
{
return Ok(_repository.GetAllPizzaSizes());
}
catch (Exception e)
{
return StatusCode(400, e.Message);
}
}
[HttpGet("{id}")]//https://localhost:5001/api/Store/5
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<APizzaSize> GetById([FromRoute] int id)
{
try
{
var x = _repository.GetPizzaSize(id);
if (x == null)
{
return NotFound($"The item with id {id} was not found in the database.");
}
return Ok(x);
}
catch (Exception e)
{
return StatusCode(400, e.Message);
}
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Consumes(MediaTypeNames.Application.Json)]
public IActionResult Post([FromBody] APizzaSize x)
{
try
{
if (x == null)
return BadRequest("Data is invalid or null");
_repository.AddPizzaSize(x);
return NoContent();
}
catch (Exception e)
{
return StatusCode(400, e.Message);
}
}
[HttpPut]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Consumes(MediaTypeNames.Application.Json)]
public IActionResult Put([FromBody] APizzaSize x)
{
try
{
if (x == null)
return BadRequest("Data is invalid or null");
_repository.UpdatePizzaSize(x);
return NoContent();
}
catch (Exception e)
{
return StatusCode(400, e.Message);
}
}
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult Delete([FromRoute] int id)
{
try
{
if (_repository.GetPizzaSize(id) == null)
return BadRequest("Item does not exist");
_repository.DeletePizzaSize(id);
return NoContent();
}
catch (Exception e)
{
return StatusCode(400, e.Message);
}
}
}
}
| 30.72807 | 112 | 0.53811 | [
"MIT"
] | 210329-UTA-SH-UiPath/P1_Miles_Plurad | PizzaBox.Service/Controllers/PizzaSizeController.cs | 3,505 | C# |
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Server.Messages;
namespace OmniSharp.Extensions.LanguageServer.Server.Messages
{
public class ServerNotInitialized : RpcError
{
internal ServerNotInitialized(string method) : base(null, method, new ErrorMessage(-32002, "Server Not Initialized"))
{
}
}
}
| 27.923077 | 125 | 0.730028 | [
"MIT"
] | Devils-Knight/csharp-language-server-protocol | src/Server/Messages/ServerNotInitialized.cs | 365 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Bm.V20180423.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeUserCmdsRequest : AbstractModel
{
/// <summary>
/// 偏移量
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// 数量限制
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// 排序字段,支持: OsType,CreateTime,ModifyTime
/// </summary>
[JsonProperty("OrderField")]
public string OrderField{ get; set; }
/// <summary>
/// 排序方式,取值: 1倒序,0顺序;默认倒序
/// </summary>
[JsonProperty("Order")]
public ulong? Order{ get; set; }
/// <summary>
/// 关键字搜索,可搜索ID或别名,支持模糊搜索
/// </summary>
[JsonProperty("SearchKey")]
public string SearchKey{ get; set; }
/// <summary>
/// 查询的脚本ID
/// </summary>
[JsonProperty("CmdId")]
public string CmdId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamSimple(map, prefix + "OrderField", this.OrderField);
this.SetParamSimple(map, prefix + "Order", this.Order);
this.SetParamSimple(map, prefix + "SearchKey", this.SearchKey);
this.SetParamSimple(map, prefix + "CmdId", this.CmdId);
}
}
}
| 30.468354 | 83 | 0.592023 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Bm/V20180423/Models/DescribeUserCmdsRequest.cs | 2,519 | C# |
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
[UnityEngine.AddComponentMenu("Wwise/AkSpatialAudioEmitter")]
[UnityEngine.RequireComponent(typeof(AkGameObj))]
///@brief Add this script on the GameObject which represents an emitter that uses the Spatial Audio API.
public class AkSpatialAudioEmitter : AkSpatialAudioBase
{
[UnityEngine.Header("Early Reflections")]
[UnityEngine.Tooltip("The Auxiliary Bus with a Reflect plug-in Effect applied.")]
/// The Auxiliary Bus with a Reflect plug-in Effect applied.
public AK.Wwise.AuxBus reflectAuxBus;
[UnityEngine.Tooltip("A heuristic to stop the computation of reflections. Should be no longer (and possibly shorter for less CPU usage) than the maximum attenuation of the sound emitter.")]
/// A heuristic to stop the computation of reflections. Should be no longer (and possibly shorter for less CPU usage) than the maximum attenuation of the sound emitter.
public float reflectionMaxPathLength = 1000;
[UnityEngine.Range(0, 1)]
[UnityEngine.Tooltip("The gain [0, 1] applied to the reflect auxiliary bus.")]
/// The gain [0, 1] applied to the reflect auxiliary bus.
public float reflectionsAuxBusGain = 1;
[UnityEngine.Range(1, 4)]
[UnityEngine.Tooltip("The maximum number of reflections that will be processed for a sound path before it reaches the listener.")]
/// The maximum number of reflections that will be processed for a sound path before it reaches the listener.
/// Reflection processing grows exponentially with the order of reflections, so this number should be kept low. Valid range: 1-4.
public uint reflectionsOrder = 1;
[UnityEngine.Header("Rooms")] [UnityEngine.Range(0, 1)]
[UnityEngine.Tooltip("Send gain (0.f-1.f) that is applied when sending to the aux bus associated with the room that the emitter is in.")]
/// Send gain (0.f-1.f) that is applied when sending to the aux bus associated with the room that the emitter is in.
public float roomReverbAuxBusGain = 1;
[UnityEngine.Header("Geometric Diffraction (Experimental)")]
[UnityEngine.Tooltip("The maximum number of edges that the sound can diffract around between the emitter and the listener.")]
/// The maximum number of edges that the sound can diffract around between the emitter and the listener.
public uint diffractionMaxEdges = 0;
[UnityEngine.Tooltip("The maximum number of paths to the listener that the sound can take around obstacles.")]
/// The maximum number of paths to the listener that the sound can take around obstacles.
public uint diffractionMaxPaths = 0;
[UnityEngine.Tooltip("The maximum length that a diffracted sound can travel.")]
/// The maximum length that a diffracted sound can travel. Should be no longer (and possibly shorter for less CPU usage) than the maximum attenuation of the sound emitter.
public uint diffractionMaxPathLength = 0;
private void OnEnable()
{
var emitterSettings = new AkEmitterSettings();
emitterSettings.reflectAuxBusID = reflectAuxBus.Id;
emitterSettings.reflectionMaxPathLength = reflectionMaxPathLength;
emitterSettings.reflectionsAuxBusGain = reflectionsAuxBusGain;
emitterSettings.reflectionsOrder = reflectionsOrder;
emitterSettings.reflectorFilterMask = unchecked((uint) -1);
emitterSettings.roomReverbAuxBusGain = roomReverbAuxBusGain;
emitterSettings.useImageSources = 0;
emitterSettings.diffractionMaxEdges = diffractionMaxEdges;
emitterSettings.diffractionMaxPaths = diffractionMaxPaths;
emitterSettings.diffractionMaxPathLength = diffractionMaxPathLength;
if (AkSoundEngine.RegisterEmitter(gameObject, emitterSettings) == AKRESULT.AK_Success)
SetGameObjectInRoom();
}
private void OnDisable()
{
AkSoundEngine.UnregisterEmitter(gameObject);
}
#if UNITY_EDITOR
[UnityEngine.Header("Debug Draw")]
/// This allows you to visualize first order reflection sound paths.
public bool drawFirstOrderReflections = false;
/// This allows you to visualize second order reflection sound paths.
public bool drawSecondOrderReflections = false;
/// This allows you to visualize third or higher order reflection sound paths.
public bool drawHigherOrderReflections = false;
/// This allows you to visualize geometric diffraction sound paths between an obstructed emitter and the listener.
public bool drawGeometricDiffraction = false;
/// This allows you to visualize sound propagation paths through portals.
public bool drawSoundPropagation = false;
private const uint kMaxIndirectPaths = 64;
private readonly AkReflectionPathInfoArray indirectPathInfoArray = new AkReflectionPathInfoArray((int) kMaxIndirectPaths);
private readonly AkPropagationPathInfoArray propagationPathInfoArray =
new AkPropagationPathInfoArray((int)AkPropagationPathInfo.kMaxNodes);
private readonly AkDiffractionPathInfoArray diffractionPathInfoArray =
new AkDiffractionPathInfoArray((int)AkDiffractionPathInfo.kMaxNodes);
private readonly AkPathParams pathsParams = new AkPathParams();
private readonly UnityEngine.Color32 colorLightBlue = new UnityEngine.Color32(157, 235, 243, 255);
private readonly UnityEngine.Color32 colorDarkBlue = new UnityEngine.Color32(24, 96, 103, 255);
private readonly UnityEngine.Color32 colorLightYellow = new UnityEngine.Color32(252, 219, 162, 255);
private readonly UnityEngine.Color32 colorDarkYellow = new UnityEngine.Color32(169, 123, 39, 255);
private readonly UnityEngine.Color32 colorLightRed = new UnityEngine.Color32(252, 177, 162, 255);
private readonly UnityEngine.Color32 colorDarkRed = new UnityEngine.Color32(169, 62, 39, 255);
private readonly UnityEngine.Color32 colorLightGrey = new UnityEngine.Color32(75, 75, 75, 255);
private readonly UnityEngine.Color32 colorDarkGrey = new UnityEngine.Color32(35, 35, 35, 255);
private readonly UnityEngine.Color32 colorPurple = new UnityEngine.Color32(73, 46, 116, 255);
private readonly UnityEngine.Color32 colorGreen = new UnityEngine.Color32(38, 113, 88, 255);
private readonly UnityEngine.Color32 colorRed = new UnityEngine.Color32(170, 67, 57, 255);
private readonly float radiusSphere = 0.25f;
private readonly float radiusSphereMin = 0.1f;
private readonly float radiusSphereMax = 0.4f;
private void OnDrawGizmos()
{
if (UnityEngine.Application.isPlaying && AkSoundEngine.IsInitialized())
{
if (drawFirstOrderReflections || drawSecondOrderReflections || drawHigherOrderReflections)
DebugDrawEarlyReflections();
if (drawGeometricDiffraction)
DebugDrawDiffraction();
if (drawSoundPropagation)
DebugDrawSoundPropagation();
}
}
private UnityEngine.Vector3 ConvertVector(AkVector vec)
{
return new UnityEngine.Vector3(vec.X, vec.Y, vec.Z);
}
private static void DrawLabelInFrontOfCam(UnityEngine.Vector3 position, string name, float distance,
UnityEngine.Color c)
{
var style = new UnityEngine.GUIStyle();
var oncam = UnityEngine.Camera.current.WorldToScreenPoint(position);
if (oncam.x >= 0 && oncam.x <= UnityEngine.Camera.current.pixelWidth && oncam.y >= 0 &&
oncam.y <= UnityEngine.Camera.current.pixelHeight && oncam.z > 0 && oncam.z < distance)
{
style.normal.textColor = c;
UnityEditor.Handles.Label(position, name, style);
}
}
private void DebugDrawEarlyReflections()
{
if (AkSoundEngine.QueryIndirectPaths(gameObject, pathsParams, indirectPathInfoArray,
(uint) indirectPathInfoArray.Count()) == AKRESULT.AK_Success)
{
for (var idxPath = (int)pathsParams.numValidPaths - 1; idxPath >= 0; --idxPath)
{
var path = indirectPathInfoArray[idxPath];
var order = path.numReflections;
if (drawFirstOrderReflections && order == 1 || drawSecondOrderReflections && order == 2 ||
drawHigherOrderReflections && order > 2)
{
UnityEngine.Color32 colorLight;
UnityEngine.Color32 colorDark;
switch (order - 1)
{
case 0:
colorLight = colorLightBlue;
colorDark = colorDarkBlue;
break;
case 1:
colorLight = colorLightYellow;
colorDark = colorDarkYellow;
break;
case 2:
default:
colorLight = colorLightRed;
colorDark = colorDarkRed;
break;
}
var emitterPos = ConvertVector(pathsParams.emitterPos);
var listenerPt = ConvertVector(pathsParams.listenerPos);
for (var idxSeg = (int) path.numPathPoints - 1; idxSeg >= 0; --idxSeg)
{
var pt = ConvertVector(path.GetPathPoint((uint) idxSeg));
UnityEngine.Debug.DrawLine(listenerPt, pt, path.isOccluded ? colorLightGrey : colorLight);
UnityEngine.Gizmos.color = path.isOccluded ? colorLightGrey : colorLight;
UnityEngine.Gizmos.DrawWireSphere(pt, radiusSphere / 2 / order);
if (!path.isOccluded)
{
var surface = path.GetAcousticSurface((uint) idxSeg);
DrawLabelInFrontOfCam(pt, surface.strName, 100000, colorDark);
}
float dfrnAmount = path.GetDiffraction((uint)idxSeg);
if (dfrnAmount > 0)
{
string dfrnAmountStr = dfrnAmount.ToString("0.#%");
DrawLabelInFrontOfCam(pt, dfrnAmountStr, 100000, colorDark);
}
listenerPt = pt;
}
if (!path.isOccluded)
{
// Finally the last path segment towards the emitter.
UnityEngine.Debug.DrawLine(listenerPt, emitterPos, path.isOccluded ? colorLightGrey : colorLight);
}
else
{
var occlusionPt = ConvertVector(path.occlusionPoint);
UnityEngine.Gizmos.color = colorDarkGrey;
UnityEngine.Gizmos.DrawWireSphere(occlusionPt, radiusSphere / order);
}
}
}
}
}
private void DebugDrawDiffraction()
{
if (AkSoundEngine.QueryDiffractionPaths(gameObject, pathsParams, diffractionPathInfoArray,
(uint)diffractionPathInfoArray.Count()) == AKRESULT.AK_Success)
{
for (var idxPath = (int)pathsParams.numValidPaths - 1; idxPath >= 0; --idxPath)
{
var path = diffractionPathInfoArray[idxPath];
var emitterPos = ConvertVector(pathsParams.emitterPos);
var prevPt = ConvertVector(pathsParams.listenerPos);
if (path.nodeCount > 0)
{
for (var idxSeg = 0; idxSeg < (int)path.nodeCount; ++idxSeg)
{
var pt = ConvertVector(path.GetNodes((uint)idxSeg));
UnityEngine.Debug.DrawLine(prevPt, pt, colorGreen);
float angle = path.GetAngles((uint)idxSeg) / UnityEngine.Mathf.PI;
if (angle > 0)
{
string angleStr = angle.ToString("0.#%");
DrawLabelInFrontOfCam(pt, angleStr, 100000, colorGreen);
}
prevPt = pt;
}
UnityEngine.Debug.DrawLine(prevPt, emitterPos, colorGreen);
}
}
}
}
private void DebugDrawSoundPropagation()
{
if (AkSoundEngine.QuerySoundPropagationPaths(gameObject, pathsParams, propagationPathInfoArray,
(uint)propagationPathInfoArray.Count()) == AKRESULT.AK_Success)
{
for (var idxPath = (int)pathsParams.numValidPaths - 1; idxPath >= 0; --idxPath)
{
var path = propagationPathInfoArray[idxPath];
var emitterPos = ConvertVector(pathsParams.emitterPos);
var prevPt = ConvertVector(pathsParams.listenerPos);
for (var idxSeg = 0; idxSeg < (int)path.numNodes; ++idxSeg)
{
var portalPt = ConvertVector(path.GetNodePoint((uint)idxSeg));
UnityEngine.Debug.DrawLine(prevPt, portalPt, colorPurple);
var radWet = radiusSphereMin + (1.0f - path.wetDiffraction) * (radiusSphereMax - radiusSphereMin);
var radDry = radiusSphereMin + (1.0f - path.dryDiffraction) * (radiusSphereMax - radiusSphereMin);
UnityEngine.Gizmos.color = colorGreen;
UnityEngine.Gizmos.DrawWireSphere(portalPt, radWet);
UnityEngine.Gizmos.color = colorRed;
UnityEngine.Gizmos.DrawWireSphere(portalPt, radDry);
prevPt = portalPt;
}
UnityEngine.Debug.DrawLine(prevPt, emitterPos, colorPurple);
}
}
}
#endif
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. | 41.207358 | 191 | 0.725347 | [
"MIT"
] | Xenation/SHMUP-Swarm | Assets/Wwise/Deployment/Components/AkSpatialAudioEmitter.cs | 12,321 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using DddEfteling.ParkTests.Entities;
using DddEfteling.Shared.Controls;
using DddEfteling.Shared.Entities;
using Geolocation;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace DddEfteling.ParkTests.Controls
{
public class LocationServiceTest
{
private LocationImpl location1 = new LocationImpl(new Coordinate(5.0, 49.0));
private LocationImpl location2 = new LocationImpl(new Coordinate(8.0, 51.0));
private LocationImpl location3 = new LocationImpl(new Coordinate(6.0, 49.5));
private LocationImpl location4 = new LocationImpl(new Coordinate(7.0, 50.5));
private LocationImpl location5 = new LocationImpl(new Coordinate(9.0, 51.5));
private LocationService locationService;
public LocationServiceTest()
{
this.locationService = new LocationService(Mock.Of<ILogger<LocationService>>(), new Random());
}
[Fact]
public void CalculateLocationDistances_GivenLocations_ExpectDistancesAdded()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locations.First(loc => loc.Coordinates.Latitude.Equals(5.0));
Assert.Equal(location3.Guid, result.DistanceToOthers.ElementAt(0).Value);
Assert.Equal(location4.Guid, result.DistanceToOthers.ElementAt(1).Value);
Assert.Equal(location2.Guid, result.DistanceToOthers.ElementAt(2).Value);
}
[Fact]
public void CalculateLocationDistances_GivenEmptyList_ExpectNothingHappens()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>();
locationService.CalculateLocationDistances(locations);
Assert.NotNull(locations);
}
[Fact]
public void NearestLocation_LocationWithNearbyLocationWithoutExclusion_ExpectNearestLocation()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locationService.NearestLocation(location1, locations, new List<Guid>());
Assert.Equal(location3, result);
}
[Fact]
public void NearestLocation_NoNearbyLocation_ExpectException()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4};
Assert.Throws<InvalidOperationException>(() =>
locationService.NearestLocation(location1, locations, new List<Guid>()));
}
[Fact]
public void NearestLocation_LocationWithNearbyLocationWithExclusion_ExpectNearestLocation()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locationService.NearestLocation(location1, locations,
new List<Guid>(){ location3.Guid });
Assert.Equal(location4, result);
}
[Fact]
public void NextLocation_LocationWithNearbyLocationWithoutExclusion_ExpectNearestLocation()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4, location5};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locationService.NextLocation(location1, locations, new List<Guid>());
Assert.Contains(result, new List<LocationImpl>(){ location2, location3, location4});
}
[Fact]
public void NextLocation_LocationWithNearbyLocationWithExclusion_ExpectNearestLocation()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4, location5};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locationService.NextLocation(location1, locations,
new List<Guid>() {location3.Guid});
Assert.Contains(result, new List<LocationImpl>(){ location2, location5, location4});
}
[Fact]
public void NextLocation_NoNearbyLocation_ExpectNull()
{
ConcurrentBag<LocationImpl> locations = new ConcurrentBag<LocationImpl>()
{location1, location2, location3, location4, location5};
locationService.CalculateLocationDistances(locations);
LocationImpl result = locationService.NextLocation(location1, locations,
new List<Guid>() {location2.Guid, location3.Guid, location4.Guid, location5.Guid});
Assert.Null(result);
}
}
} | 40.222222 | 106 | 0.650092 | [
"MIT"
] | Ruubmeister/DddEfteling | DddEfteling.UnitTests/DddEfteling.ParkTests/Shared/Locations/Controls/LocationServiceTest.cs | 5,430 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 04:45:49 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using @unsafe = go.@unsafe_package;
#nullable enable
namespace go
{
public static partial class runtime_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
private partial struct timespec
{
// Constructors
public timespec(NilType _)
{
this.tv_sec = default;
this.tv_nsec = default;
this.pad_cgo_0 = default;
}
public timespec(long tv_sec = default, int tv_nsec = default, array<byte> pad_cgo_0 = default)
{
this.tv_sec = tv_sec;
this.tv_nsec = tv_nsec;
this.pad_cgo_0 = pad_cgo_0;
}
// Enable comparisons between nil and timespec struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(timespec value, NilType nil) => value.Equals(default(timespec));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(timespec value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, timespec value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, timespec value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator timespec(NilType nil) => default(timespec);
}
[GeneratedCode("go2cs", "0.1.0.0")]
private static timespec timespec_cast(dynamic value)
{
return new timespec(value.tv_sec, value.tv_nsec, value.pad_cgo_0);
}
}
} | 35.230769 | 107 | 0.587773 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/runtime/defs_freebsd_arm_timespecStruct.cs | 2,290 | 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 codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeCommit.Model
{
/// <summary>
/// Represents the output of a get repository triggers operation.
/// </summary>
public partial class GetRepositoryTriggersResponse : AmazonWebServiceResponse
{
private string _configurationId;
private List<RepositoryTrigger> _triggers = new List<RepositoryTrigger>();
/// <summary>
/// Gets and sets the property ConfigurationId.
/// <para>
/// The system-generated unique ID for the trigger.
/// </para>
/// </summary>
public string ConfigurationId
{
get { return this._configurationId; }
set { this._configurationId = value; }
}
// Check to see if ConfigurationId property is set
internal bool IsSetConfigurationId()
{
return this._configurationId != null;
}
/// <summary>
/// Gets and sets the property Triggers.
/// <para>
/// The JSON block of configuration information for each trigger.
/// </para>
/// </summary>
public List<RepositoryTrigger> Triggers
{
get { return this._triggers; }
set { this._triggers = value; }
}
// Check to see if Triggers property is set
internal bool IsSetTriggers()
{
return this._triggers != null && this._triggers.Count > 0;
}
}
} | 30.657895 | 108 | 0.636052 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/GetRepositoryTriggersResponse.cs | 2,330 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using OpenDreamShared;
using OpenDreamShared.Network.Messages;
using Robust.Shared.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Network;
namespace OpenDreamRuntime.Resources
{
public class DreamResourceManager
{
[Dependency] private readonly IServerNetManager _netManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
public string RootPath { get; private set; }
private readonly Dictionary<string, DreamResource> _resourceCache = new();
public void Initialize()
{
var fullPath = Path.GetFullPath(_cfg.GetCVar(OpenDreamCVars.JsonPath));
RootPath = Path.GetDirectoryName(fullPath);
Logger.DebugS("opendream.res", $"Resource root path is {RootPath}");
_netManager.RegisterNetMessage<MsgRequestResource>(RxRequestResource);
_netManager.RegisterNetMessage<MsgResource>();
}
public bool DoesFileExist(string resourcePath) {
return File.Exists(Path.Combine(RootPath, resourcePath));
}
public DreamResource LoadResource(string resourcePath) {
if (resourcePath == "") return new ConsoleOutputResource(); //An empty resource path is the console
if (!_resourceCache.TryGetValue(resourcePath, out DreamResource resource)) {
resource = new DreamResource(Path.Combine(RootPath, resourcePath), resourcePath);
_resourceCache.Add(resourcePath, resource);
}
return resource;
}
public void RxRequestResource(MsgRequestResource pRequestResource) {
DreamResource resource = LoadResource(pRequestResource.ResourcePath);
if (resource.ResourceData != null)
{
var msg = _netManager.CreateNetMessage<MsgResource>();
msg.ResourcePath = resource.ResourcePath;
msg.ResourceData = resource.ResourceData;
pRequestResource.MsgChannel.SendMessage(msg);
} else {
Logger.WarningS("opendream.res", $"User {pRequestResource.MsgChannel} requested resource '{pRequestResource.ResourcePath}', which doesn't exist");
}
}
public bool DeleteFile(string filePath) {
try {
File.Delete(Path.Combine(RootPath, filePath));
} catch (Exception) {
return false;
}
return true;
}
public bool DeleteDirectory(string directoryPath) {
try {
Directory.Delete(Path.Combine(RootPath, directoryPath), true);
} catch (Exception) {
return false;
}
return true;
}
public bool SaveTextToFile(string filePath, string text) {
try {
File.WriteAllText(Path.Combine(RootPath, filePath), text);
} catch (Exception) {
return false;
}
return true;
}
public bool CopyFile(string sourceFilePath, string destinationFilePath) {
try {
File.Copy(Path.Combine(RootPath, sourceFilePath), Path.Combine(RootPath, destinationFilePath));
} catch (Exception) {
return false;
}
return true;
}
public string[] EnumerateListing(string path)
{
string directory = Path.Combine(RootPath, Path.GetDirectoryName(path));
string searchPattern = Path.GetFileName(path);
var entries = Directory.GetFileSystemEntries(directory, searchPattern);
for (var i = 0; i < entries.Length; i++) {
var relPath = Path.GetRelativePath(directory, entries[i]);
if (Directory.Exists(entries[i])) relPath += "/";
entries[i] = relPath;
}
return entries;
}
}
}
| 34.57265 | 162 | 0.603708 | [
"MIT"
] | TemporalOroboros/OpenDream | OpenDreamRuntime/Resources/DreamResourceManager.cs | 4,047 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
namespace Azure.ResourceManager.Network
{
internal class VirtualNetworkGatewayNatRuleOperationSource : IOperationSource<VirtualNetworkGatewayNatRule>
{
private readonly ArmClient _client;
internal VirtualNetworkGatewayNatRuleOperationSource(ArmClient client)
{
_client = client;
}
VirtualNetworkGatewayNatRule IOperationSource<VirtualNetworkGatewayNatRule>.CreateResult(Response response, CancellationToken cancellationToken)
{
using var document = JsonDocument.Parse(response.ContentStream);
var data = VirtualNetworkGatewayNatRuleData.DeserializeVirtualNetworkGatewayNatRuleData(document.RootElement);
return new VirtualNetworkGatewayNatRule(_client, data);
}
async ValueTask<VirtualNetworkGatewayNatRule> IOperationSource<VirtualNetworkGatewayNatRule>.CreateResultAsync(Response response, CancellationToken cancellationToken)
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var data = VirtualNetworkGatewayNatRuleData.DeserializeVirtualNetworkGatewayNatRuleData(document.RootElement);
return new VirtualNetworkGatewayNatRule(_client, data);
}
}
}
| 38.682927 | 174 | 0.760404 | [
"MIT"
] | AntonioVT/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/LongRunningOperation/VirtualNetworkGatewayNatRuleOperationSource.cs | 1,586 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Favalon - An Interactive Shell Based on a Typed Lambda Calculus.
// Copyright (c) 2018-2020 Kouji Matsui (@kozy_kekyo, @kekyo2)
//
// 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 Favalet.Contexts;
using Favalet.Expressions;
using Favalet.Expressions.Operators;
using Favalet.Expressions.Specialized;
using Favalet.Contexts.Unifiers;
using Favalet.Ranges;
using Favalet.Internal;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Favalet
{
[Flags]
public enum BoundAttributes
{
PrefixLeftToRight = 0x00,
PrefixRightToLeft = 0x02,
InfixLeftToRight = 0x01,
InfixRightToLeft = 0x03,
InfixMask = 0x01,
RightToLeftMask = 0x02,
}
public interface IEnvironments :
IScopeContext
{
ITopology? LastTopology { get; }
void MutableBind(BoundAttributes attributes, IBoundVariableTerm symbol, IExpression expression);
}
public class Environments :
ScopeContext, IEnvironments, IPlaceholderProvider
{
private UnifyContext? lastContext;
private int placeholderIndex = -1;
private readonly bool saveLastTopology;
[EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerStepThrough]
public Environments(
ITypeCalculator typeCalculator, bool saveLastTopology) :
base(null)
{
this.TypeCalculator = typeCalculator;
this.saveLastTopology = saveLastTopology;
}
[EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerStepThrough]
public Environments(bool saveLastTopology) :
this(Favalet.TypeCalculator.Instance, saveLastTopology)
{
}
public override ITypeCalculator TypeCalculator { get; }
[EditorBrowsable(EditorBrowsableState.Never)]
public ITopology? LastTopology =>
this.lastContext;
protected virtual void OnReset() =>
this.MutableBindDefaults();
public void Reset()
{
this.CopyInDefaultRegistry(null, true);
this.placeholderIndex = -1;
}
[DebuggerStepThrough]
internal IExpression CreatePlaceholder(
PlaceholderOrderHints orderHint)
{
var oh = Math.Min(
(int)PlaceholderOrderHints.DeadEnd,
Math.Max(0, (int)orderHint));
var count = Math.Min(
(int)PlaceholderOrderHints.DeadEnd - oh,
(int)PlaceholderOrderHints.Fourth);
var indexList =
Enumerable.Range(0, count).
Select(_ => Interlocked.Increment(ref this.placeholderIndex)).
Memoize();
return indexList.
Reverse().
Aggregate(
(IExpression)DeadEndTerm.Instance,
(agg, index) => PlaceholderTerm.Create(index, agg, TextRange.Unknown)); // TODO: range
}
[DebuggerStepThrough]
IExpression IPlaceholderProvider.CreatePlaceholder(
PlaceholderOrderHints orderHint) =>
this.CreatePlaceholder(orderHint);
private IExpression InternalInfer(
UnifyContext unifyContext,
ReduceContext context,
IExpression expression)
{
Debug.WriteLine($"Infer[{context.GetHashCode()}:before] :");
Debug.WriteLine(expression.GetXml());
var transposed = context.Transpose(expression);
unifyContext.SetTargetRoot(transposed);
Debug.WriteLine($"Infer[{context.GetHashCode()}:transposed] :");
Debug.WriteLine(transposed.GetXml());
var rewritable = context.MakeRewritable(transposed);
unifyContext.SetTargetRoot(rewritable);
Debug.WriteLine($"Infer[{context.GetHashCode()}:rewritable] :");
Debug.WriteLine(rewritable.GetXml());
var inferred = context.Infer(rewritable);
unifyContext.SetTargetRoot(inferred);
Debug.WriteLine($"Infer[{context.GetHashCode()}:inferred] :");
Debug.WriteLine(inferred.GetXml());
var fixedup = context.Fixup(inferred);
//unifyContext.SetTargetRoot(fixedup);
Debug.WriteLine($"Infer[{context.GetHashCode()}:fixedup] :");
Debug.WriteLine(fixedup.GetXml());
return fixedup;
}
public IExpression Infer(IExpression expression)
{
var unifyContext = UnifyContext.Create(this.TypeCalculator, expression);
var context = ReduceContext.Create(this, this, unifyContext);
var inferred = this.InternalInfer(unifyContext, context, expression);
if (this.saveLastTopology)
{
this.lastContext = unifyContext;
}
return inferred;
}
public IExpression Reduce(IExpression expression)
{
var unifyContext = UnifyContext.Create(this.TypeCalculator, expression);
var context = ReduceContext.Create(this, this, unifyContext);
var inferred = this.InternalInfer(unifyContext, context, expression);
var reduced = context.Reduce(inferred);
Debug.WriteLine($"Reduce[{context.GetHashCode()}:reduced] :");
Debug.WriteLine(reduced.GetXml());
if (this.saveLastTopology)
{
this.lastContext = unifyContext;
}
return reduced;
}
[DebuggerStepThrough]
public void MutableBind(
BoundAttributes attributes,
IBoundVariableTerm symbol,
IExpression expression) =>
base.MutableBind(attributes, symbol, expression, false);
[DebuggerStepThrough]
public static Environments Create(
#if DEBUG
bool saveLastTopology = true
#else
bool saveLastTopology = false
#endif
)
{
var environments =
new Environments(Favalet.TypeCalculator.Instance, saveLastTopology);
environments.MutableBindDefaults();
return environments;
}
}
[DebuggerStepThrough]
public static class EnvironmentsExtension
{
public static void MutableBind(
this IEnvironments environments,
BoundAttributes attributes,
string symbol,
IExpression expression) =>
environments.MutableBind(
attributes,
BoundVariableTerm.Create(symbol, TextRange.Unknown),
expression);
public static void MutableBind(
this IEnvironments environments,
BoundAttributes attributes,
string symbol,
TextRange range,
IExpression expression) =>
environments.MutableBind(
attributes,
BoundVariableTerm.Create(symbol, range),
expression);
public static void MutableBind(
this IEnvironments environments,
IBoundVariableTerm symbol,
IExpression expression) =>
environments.MutableBind(
BoundAttributes.PrefixLeftToRight,
symbol,
expression);
public static void MutableBind(
this IEnvironments environment,
string symbol,
IExpression expression) =>
environment.MutableBind(
BoundVariableTerm.Create(symbol, TextRange.Unknown),
expression);
public static void MutableBind(
this IEnvironments environment,
string symbol,
TextRange range,
IExpression expression) =>
environment.MutableBind(
BoundVariableTerm.Create(symbol, range),
expression);
public static void MutableBindDefaults(
this IEnvironments environments)
{
// Unspecified symbol.
environments.MutableBind(
BoundAttributes.PrefixLeftToRight, "_",
TextRange.Internal, UnspecifiedTerm.Instance);
// Type fourth symbol.
environments.MutableBind(
BoundAttributes.PrefixLeftToRight, "#",
TextRange.Internal, FourthTerm.Instance);
// Type kind symbol.
//environments.MutableBind(
// BoundAttributes.PrefixLeftToRight, "*",
// TextRange.Internal, TypeKindTerm.Instance);
// Lambda operator.
environments.MutableBind(
BoundAttributes.InfixMask | BoundAttributes.RightToLeftMask, "->",
TextRange.Internal, LambdaOperatorExpression.Instance);
}
}
}
| 33.647059 | 107 | 0.587618 | [
"Apache-2.0"
] | kekyo/Favalon | Favalet.Core/Environments.cs | 9,724 | C# |
using MiauCore.IO.Areas.Admin.Models;
using MiauCore.IO.Domain.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MiauCore.IO.Controllers
{
[Route("api/[controller]")]
public class LoginController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
public LoginController(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] User user)
{
if (user == null)
{
return Unauthorized();
}
var result = await _signInManager.PasswordSignInAsync(user.Login, user.Password, false, false);
if (result.Succeeded)
{
return Ok();
}
else
{
return Unauthorized();
}
}
}
}
| 24.906977 | 107 | 0.593838 | [
"MIT"
] | MIAUUUUUUU/Sticky.io | src/MiauCore.IO/Controllers/AccountController.cs | 1,073 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Enum
{
[TestClass]
public class EnumTest
{
private enum Animal //Value type that is a set of named constants
{
Dog,
Bear
}
[TestMethod]
public void EnumComparison()
{
Animal animal = Animal.Bear;
Assert.AreEqual(animal, Animal.Bear); //Less expensive than String comparison since it is an integer value
Assert.AreNotEqual(animal, Animal.Dog);
}
}
}
| 22.833333 | 118 | 0.583942 | [
"MIT"
] | MartinChavez/CSharp | SchoolOfCSharp/Enum/EnumTest.cs | 550 | C# |
namespace ClosedXML.Excel
{
//Use the class to store magic strings or variables.
public static class XLConstants
{
public const string PivotTableValuesSentinalLabel = "{{Values}}";
public const int NumberOfBuiltInStyles = 163;
internal static class Comment
{
internal const string ShapeTypeId = "#_x0000_t202";
internal const string AlternateShapeTypeId = "#_xssf_cell_comment";
}
}
}
| 30.0625 | 80 | 0.636175 | [
"MIT"
] | monoblaine/ClosedXML | ClosedXML/Excel/XLConstants.cs | 466 | C# |
using System.Collections.Generic;
namespace WebApplication.Models.Options
{
public class SecurityRoleAssignments
{
public bool IsSubjectAreaScoped { get; set; }
public string SecurityGroupId { get; set; }
public List<string> AllowActions { get; set; } = new List<string>();
}
}
| 26.333333 | 76 | 0.677215 | [
"MIT"
] | JonHarding/azure-data-services-go-fast-codebase | solution/WebApplication/WebApplication/Models/Options/SecurityRoleAssignments.cs | 318 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Breeze.Sharp;
using Breeze.Sharp.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Foo;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Net.Http;
namespace Breeze.Sharp.Tests {
[TestClass]
public class MetadataTests {
private String _serviceName;
[TestInitialize]
public void TestInitializeMethod() {
Configuration.Instance.ProbeAssemblies(typeof(Customer).Assembly);
_serviceName = TestFns.serviceName;
}
[TestCleanup]
public void TearDown() {
}
[TestMethod]
public async Task SelfAndSubtypes() {
var em = await TestFns.NewEm(_serviceName);
var allOrders = em.GetEntities(typeof(Order), typeof(InternationalOrder));
var orderEntityType = em.MetadataStore.GetEntityType(typeof (Order));
var allOrders2 = em.GetEntities(orderEntityType.SelfAndSubEntityTypes.Select(et => et.ClrType));
Assert.IsTrue(allOrders.Count() == allOrders2.Count());
}
[TestMethod]
public async Task HttpClientHandler() {
var httpClient = new HttpClient(new HttpClientHandler() {
UseDefaultCredentials = true
});
var ds = new DataService(_serviceName, httpClient);
var em = new EntityManager(ds);
em.MetadataStore.AllowedMetadataMismatchTypes = MetadataMismatchTypes.MissingCLREntityType;
var md = await em.FetchMetadata(ds);
Assert.IsTrue(md != null);
}
// Creates a convention that removes underscores from server property names
// Remembers them in a private dictionary so it can restore them
// when going from client to server
// Warning: use only with metadata loaded directly from server
public class UnderscoreRemovallNamingConvention : NamingConvention {
private Dictionary<String, String> _clientServerPropNameMap = new Dictionary<string, string>();
public override String ServerPropertyNameToClient(String serverPropertyName, StructuralType parentType) {
if (serverPropertyName.IndexOf("_", StringComparison.InvariantCulture) != -1) {
var clientPropertyName = serverPropertyName.Replace("_", "");
_clientServerPropNameMap[clientPropertyName] = serverPropertyName;
return clientPropertyName;
} else {
return base.ServerPropertyNameToClient(serverPropertyName, parentType);
}
}
public override string ClientPropertyNameToServer(string clientPropertyName, StructuralType parentType) {
String serverPropertyName;
if (_clientServerPropNameMap.TryGetValue(clientPropertyName, out serverPropertyName)) {
serverPropertyName = clientPropertyName;
}
return serverPropertyName;
}
}
}
}
| 30.010101 | 111 | 0.715921 | [
"MIT"
] | Breeze/breeze.sharp | Tests/Internal/Tests/MetadataTests.cs | 2,973 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ForgedOnce.GlslLanguageServices.LanguageModels.Ast
{
public abstract class AstNode
{
protected Dictionary<string, string> annotations;
public const string PrintableUnknownName = "$unnamed$";
protected AstNode parent;
private bool isReadonly;
protected List<AstNode> childNodes = new List<AstNode>();
public AstNode Parent
{
get
{
return this.parent;
}
set
{
if (this.parent != null)
{
this.parent.EnsureIsEditable();
this.parent.childNodes.Remove(this);
}
if (value != null)
{
value.EnsureIsEditable();
value.childNodes.Add(this);
}
this.parent = value;
}
}
public void SetAnnotation(string key, string value)
{
if (this.annotations == null)
{
this.annotations = new Dictionary<string, string>();
}
if (this.annotations.ContainsKey(key))
{
this.annotations[key] = value;
}
else
{
this.annotations.Add(key, value);
}
}
public bool HasAnnotation(string key)
{
return this.annotations != null && this.annotations.ContainsKey(key);
}
public string GetAnnotation(string key)
{
if (this.annotations == null || !this.annotations.ContainsKey(key))
{
return null;
}
return this.annotations[key];
}
protected void SetAsParentFor(AstNode oldValue, AstNode newValue)
{
if (oldValue != null)
{
oldValue.Parent = null;
}
if (newValue != null)
{
newValue.Parent = this;
}
}
public virtual int GetChildIndex(AstNode child)
{
return -1;
}
public bool EqualsOrSubNodeOf(AstNode node)
{
if (this == node)
{
return true;
}
if (this.Parent != null)
{
return this.Parent.EqualsOrSubNodeOf(node);
}
return false;
}
public void MakeReadonly()
{
this.isReadonly = true;
foreach (var item in this.childNodes)
{
item.MakeReadonly();
}
}
protected void EnsureIsEditable()
{
if (this.isReadonly)
{
throw new InvalidOperationException("Attempt to modify a readonly node.");
}
}
}
}
| 24.582677 | 91 | 0.43786 | [
"MIT"
] | YevgenNabokov/ForgedOnce.GLSLLanguageServices | ForgedOnce.GlslLanguageServices.LanguageModels/Ast/AstNode.cs | 3,124 | C# |
/****************************************************************************
* Copyright 2019 Nreal Techonology Limited. All rights reserved.
*
* This file is part of NRSDK.
*
* https://www.nreal.ai/
*
*****************************************************************************/
namespace NRKernal.Record
{
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary> A frame capture context. </summary>
public class FrameCaptureContext
{
/// <summary> The blender. </summary>
private BlenderBase m_Blender;
/// <summary> The encoder. </summary>
private IEncoder m_Encoder;
/// <summary> Options for controlling the camera. </summary>
private CameraParameters m_CameraParameters;
/// <summary> The frame provider. </summary>
private AbstractFrameProvider m_FrameProvider;
/// <summary> The capture behaviour. </summary>
private CaptureBehaviourBase m_CaptureBehaviour;
/// <summary> True if is initialize, false if not. </summary>
private bool m_IsInitialized = false;
private List<IFrameConsumer> m_FrameConsumerList;
/// <summary> Gets the preview texture. </summary>
/// <value> The preview texture. </value>
public Texture PreviewTexture
{
get
{
return m_Blender?.BlendTexture;
}
}
/// <summary> Gets the behaviour. </summary>
/// <returns> The behaviour. </returns>
public CaptureBehaviourBase GetBehaviour()
{
return m_CaptureBehaviour;
}
/// <summary> Gets frame provider. </summary>
/// <returns> The frame provider. </returns>
public AbstractFrameProvider GetFrameProvider()
{
return m_FrameProvider;
}
/// <summary> Gets the blender. </summary>
/// <returns> The blender. </returns>
public BlenderBase GetBlender()
{
return m_Blender;
}
/// <summary> Request camera parameter. </summary>
/// <returns> The CameraParameters. </returns>
public CameraParameters RequestCameraParam()
{
return m_CameraParameters;
}
/// <summary> Gets the encoder. </summary>
/// <returns> The encoder. </returns>
public IEncoder GetEncoder()
{
return m_Encoder;
}
/// <summary> Constructor. </summary>
public FrameCaptureContext() { }
/// <summary> Starts capture mode. </summary>
/// <param name="param"> The parameter.</param>
public void StartCaptureMode(CameraParameters param)
{
if (m_IsInitialized)
{
this.Release();
NRDebugger.Warning("[CaptureContext] Capture context has been started already, release it and restart a new one.");
}
NRDebugger.Info("[CaptureContext] Create...");
if (m_CaptureBehaviour == null)
{
this.m_CaptureBehaviour = this.GetCaptureBehaviourByMode(param.camMode);
}
this.m_CameraParameters = param;
this.m_Encoder = GetEncoderByMode(param.camMode);
this.m_Encoder.Config(param);
this.m_Blender = new ExtraFrameBlender();
this.m_Blender.Init(m_CaptureBehaviour.CaptureCamera, m_Encoder, param);
this.m_CaptureBehaviour.Init(this);
this.m_FrameProvider = CreateFrameProviderByMode(param.blendMode, param.frameRate);
this.m_FrameProvider.OnUpdate += UpdateFrame;
this.m_FrameConsumerList = new List<IFrameConsumer>();
this.Sequence(m_CaptureBehaviour)
.Sequence(m_Blender);
this.m_IsInitialized = true;
}
private FrameCaptureContext Sequence(IFrameConsumer consummer)
{
this.m_FrameConsumerList.Add(consummer);
return this;
}
private void UpdateFrame(UniversalTextureFrame frame)
{
for (int i = 0; i < m_FrameConsumerList.Count; i++)
{
m_FrameConsumerList[i].OnFrame(frame);
}
}
/// <summary> Gets capture behaviour by mode. </summary>
/// <exception cref="Exception"> Thrown when an exception error condition occurs.</exception>
/// <param name="mode"> The mode.</param>
/// <returns> The capture behaviour by mode. </returns>
private CaptureBehaviourBase GetCaptureBehaviourByMode(CamMode mode)
{
if (mode == CamMode.PhotoMode)
{
NRCaptureBehaviour capture = GameObject.FindObjectOfType<NRCaptureBehaviour>();
var headParent = NRSessionManager.Instance.NRSessionBehaviour.transform.parent;
if (capture == null)
{
capture = GameObject.Instantiate(Resources.Load<NRCaptureBehaviour>("Record/Prefabs/NRCaptureBehaviour"), headParent);
}
GameObject.DontDestroyOnLoad(capture.gameObject);
return capture;
}
else if (mode == CamMode.VideoMode)
{
NRRecordBehaviour capture = GameObject.FindObjectOfType<NRRecordBehaviour>();
var headParent = NRSessionManager.Instance.NRSessionBehaviour.transform.parent;
if (capture == null)
{
capture = GameObject.Instantiate(Resources.Load<NRRecordBehaviour>("Record/Prefabs/NRRecorderBehaviour"), headParent);
}
GameObject.DontDestroyOnLoad(capture.gameObject);
return capture;
}
else
{
throw new Exception("CamMode need to be set correctly for capture behaviour!");
}
}
private AbstractFrameProvider CreateFrameProviderByMode(BlendMode mode, int fps)
{
AbstractFrameProvider provider;
switch (mode)
{
case BlendMode.Blend:
case BlendMode.RGBOnly:
#if UNITY_EDITOR
provider = new EditorFrameProvider();
#else
provider = new RGBCameraFrameProvider();
#endif
break;
case BlendMode.VirtualOnly:
default:
provider = new NullDataFrameProvider(fps);
break;
}
return provider;
}
/// <summary> Gets encoder by mode. </summary>
/// <exception cref="Exception"> Thrown when an exception error condition occurs.</exception>
/// <param name="mode"> The mode.</param>
/// <returns> The encoder by mode. </returns>
private IEncoder GetEncoderByMode(CamMode mode)
{
if (mode == CamMode.PhotoMode)
{
return new ImageEncoder();
}
else if (mode == CamMode.VideoMode)
{
return new VideoEncoder();
}
else
{
throw new Exception("CamMode need to be set correctly for encoder!");
}
}
/// <summary> Stops capture mode. </summary>
public void StopCaptureMode()
{
this.Release();
}
/// <summary> Starts a capture. </summary>
public void StartCapture()
{
if (!m_IsInitialized)
{
return;
}
NRDebugger.Info("[CaptureContext] Start...");
m_Encoder?.Start();
m_FrameProvider?.Play();
}
/// <summary> Stops a capture. </summary>
public void StopCapture()
{
if (!m_IsInitialized)
{
return;
}
NRDebugger.Info("[CaptureContext] Stop...");
// Need stop encoder firstly.
m_Encoder?.Stop();
m_FrameProvider?.Stop();
}
/// <summary> Releases this object. </summary>
public void Release()
{
if (!m_IsInitialized)
{
return;
}
NRDebugger.Info("[CaptureContext] Release begin...");
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
if (m_FrameProvider != null)
{
m_FrameProvider.OnUpdate -= this.m_CaptureBehaviour.OnFrame;
m_FrameProvider?.Release();
}
m_Blender?.Dispose();
m_Encoder?.Release();
if (m_CaptureBehaviour != null)
{
GameObject.DestroyImmediate(m_CaptureBehaviour.gameObject);
m_CaptureBehaviour = null;
}
NRDebugger.Info("[CaptureContext] Release end, cost:{0} ms", stopwatch.ElapsedMilliseconds);
m_IsInitialized = false;
}
}
}
| 35.408922 | 156 | 0.518215 | [
"MIT"
] | PlanBGmbH/PlanB.-Famous-Cube | Nreal/Assets/NRSDK/Scripts/Capture/FrameCaptureContext.cs | 9,527 | 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 System.Windows.Forms {
// Defined in such a way that you can cast the relation to an AnchorStyle and the direction of
// the AnchorStyle points to where the image goes. (e.g., (AnchorStyle)ImageBeforeText -> Left))
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation"]/*' />
public enum TextImageRelation {
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation.Overlay"]/*' />
Overlay = AnchorStyles.None,
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation.ImageBeforeText"]/*' />
ImageBeforeText = AnchorStyles.Left,
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation.TextBeforeImage"]/*' />
TextBeforeImage = AnchorStyles.Right,
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation.ImageAboveText"]/*' />
ImageAboveText = AnchorStyles.Top,
/// <include file='doc\TextImageRelation.uex' path='docs/doc[@for="TextImageRelation.TextAboveImage"]/*' />
TextAboveImage = AnchorStyles.Bottom
};
}
| 62.363636 | 116 | 0.697522 | [
"MIT"
] | HankiDesign/winforms | src/System.Windows.Forms/src/System/Windows/Forms/TextImageRelation.cs | 1,374 | C# |
using Microsoft.Extensions.Configuration;
namespace SFA.DAS.QnA.Configuration.Infrastructure
{
public static class AzureTableStorageConfigurationExtensions
{
public static IConfigurationBuilder AddAzureTableStorageConfiguration(this IConfigurationBuilder builder, string connection, string appName, string environment, string version)
{
return builder.Add(new AzureTableStorageConfigurationSource(connection,appName, environment, version));
}
}
}
| 38.153846 | 184 | 0.778226 | [
"MIT"
] | SkillsFundingAgency/das-qna-api | src/SFA.DAS.QnA.Configuration/Infrastructure/AzureTableStorageConfigurationExtensions.cs | 496 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using LinqToDB;
using LinqToDB.DataProvider.Firebird;
using LinqToDB.Mapping;
using NUnit.Framework;
namespace Tests.Linq
{
using Model;
[TestFixture]
public class DynamicColumnsTests : TestBase
{
// Introduced to ensure that we process not only constants in column names
static string IDColumn = "ID";
static string DiagnosisColumn = "Diagnosis";
static string PatientColumn = "Patient";
[Test]
public void SqlPropertyWithNonDynamicColumn([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var result = db.GetTable<Person>()
.Where(x => Sql.Property<int>(x, IDColumn) == 1)
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual("John", result.Single().FirstName);
}
}
[Test]
public void SqlPropertyWithNavigationalNonDynamicColumn([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var result = db.GetTable<Person>()
.Where(x => Sql.Property<string>(x.Patient, DiagnosisColumn) ==
"Hallucination with Paranoid Bugs\' Delirium of Persecution")
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual("Tester", result.Single().FirstName);
}
}
[Test]
public void SqlPropertyWithNonDynamicAssociation([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var result = db.GetTable<Person>()
.Where(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn) ==
"Hallucination with Paranoid Bugs\' Delirium of Persecution")
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual("Tester", result.Single().FirstName);
}
}
[Test]
public void SqlPropertyWithNonDynamicAssociationViaObject1([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var result = db.GetTable<Person>()
.Where(x => (string)Sql.Property<object>(Sql.Property<object>(x, PatientColumn), DiagnosisColumn) ==
"Hallucination with Paranoid Bugs\' Delirium of Persecution")
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual("Tester", result.Single().FirstName);
}
}
[ActiveIssue(Configurations = new[] { ProviderName.SapHana })]
[Test]
public void SqlPropertyWithNonDynamicAssociationViaObject2([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var expected = Person.Select(p => p.Patient?.Diagnosis).ToList();
var result = db.GetTable<Person>()
.Select(x => Sql.Property<object>(Sql.Property<object>(x, PatientColumn), DiagnosisColumn))
.ToList();
Assert.IsTrue(result.OrderBy(_ => _ as string).SequenceEqual(expected.OrderBy(_ => _)));
}
}
[Test]
public void SqlPropertyWithDynamicColumn([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var result = db.GetTable<PersonWithDynamicStore>()
.Where(x => Sql.Property<string>(x, "FirstName") == "John")
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(1, result.Single().ID);
}
}
[Test]
public void SqlPropertyWithDynamicAssociation([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var result = db.GetTable<PersonWithDynamicStore>()
.Where(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn) ==
"Hallucination with Paranoid Bugs\' Delirium of Persecution")
.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(2, result.Single().ID);
}
}
[Test]
public void SqlPropertySelectAll([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Select(p => p.FirstName).ToList();
var result = db.GetTable<PersonWithDynamicStore>().ToList().Select(p => p.ExtendedProperties["FirstName"]).ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[Test]
public void SqlPropertySelectOne([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Select(p => p.FirstName).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.Select(x => Sql.Property<string>(x, "FirstName"))
.ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[Test]
public void SqlPropertySelectProject([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Select(p => new
{
PersonId = p.ID,
Name = p.FirstName
}).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.Select(x => new
{
PersonId = x.ID,
Name = Sql.Property<string>(x, "FirstName")
})
.ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[ActiveIssue(Configurations = new[] { ProviderName.SapHana })]
[Test]
public void SqlPropertySelectAssociated([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Select(p => p.Patient?.Diagnosis).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.Select(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn))
.ToList();
Assert.IsTrue(result.OrderBy(_ => _).SequenceEqual(expected.OrderBy(_ => _)));
}
}
[Test]
public void SqlPropertyWhere([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Where(p => p.FirstName == "John").Select(p => p.ID).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.Where(x => Sql.Property<string>(x, "FirstName") == "John")
.Select(x => x.ID)
.ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[Test]
public void SqlPropertyWhereAssociated([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Where(p => p.Patient?.Diagnosis != null).Select(p => p.ID).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.Where(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn) != null)
.Select(x => x.ID)
.ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[Test]
public void SqlPropertyOrderBy([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.OrderByDescending(p => p.FirstName).Select(p => p.ID).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.OrderByDescending(x => Sql.Property<string>(x, "FirstName"))
.Select(x => x.ID)
.ToList();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
[Test]
public void SqlPropertyOrderByAssociated([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.OrderBy(p => p.Patient?.Diagnosis).Select(p => p.ID).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.OrderBy(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn))
.Select(x => x.ID)
.ToList();
Assert.IsTrue(result.OrderBy(_ => _).SequenceEqual(expected.OrderBy(_ => _)));
}
}
[Test]
public void SqlPropertyGroupBy([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.GroupBy(p => p.FirstName).Select(p => new {p.Key, Count = p.Count()}).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.GroupBy(x => Sql.Property<string>(x, "FirstName"))
.Select(p => new {p.Key, Count = p.Count()})
.ToList();
Assert.IsTrue(result.OrderBy(_ => _.Key).SequenceEqual(expected.OrderBy(_ => _.Key)));
}
}
[ActiveIssue(Configurations = new[] { ProviderName.SapHana })]
[Test]
public void SqlPropertyGroupByAssociated([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.GroupBy(p => p.Patient?.Diagnosis).Select(p => new {p.Key, Count = p.Count()}).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.GroupBy(x => Sql.Property<string>(Sql.Property<Patient>(x, PatientColumn), DiagnosisColumn))
.Select(p => new {p.Key, Count = p.Count()})
.ToList();
Assert.IsTrue(result.OrderBy(_ => _.Key).SequenceEqual(expected.OrderBy(_ => _.Key)));
}
}
[Test]
public void SqlPropertyJoin([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected =
from p in Person
join pa in Patient on p.FirstName equals pa.Diagnosis
select p;
var result =
from p in db.Person
join pa in db.Patient on Sql.Property<string>(p, "FirstName") equals Sql.Property<string>(pa, DiagnosisColumn)
select p;
Assert.IsTrue(result.ToList().SequenceEqual(expected.ToList()));
}
}
[Test]
public void SqlPropertyLoadWith([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected = Person.Select(p => p.Patient?.Diagnosis).ToList();
var result = db.GetTable<PersonWithDynamicStore>()
.LoadWith(x => Sql.Property<Patient>(x, "Patient"))
.ToList()
.Select(p => ((Patient)p.ExtendedProperties[PatientColumn])?.Diagnosis)
.ToList();
Assert.IsTrue(result.OrderBy(_ => _).SequenceEqual(expected.OrderBy(_ => _)));
}
}
[Test]
public void SqlPropertyNoStoreGrouping1([DataSources] string context)
{
using (var db = GetDataContext(context, ConfigureDynamicClass()))
{
var expected =
from p in Person
group p by p.FirstName into g
select new
{
FirstName = g.Key,
Count = g.Count()
};
var result =
from p in db.GetTable<PersonWithDynamicStore>()
group p by Sql.Property<string>(p, "FirstName") into g
select new
{
FirstName = g.Key,
Count = g.Count()
};
AreEqual(result.OrderBy(_ => _.FirstName), expected.OrderBy(_ => _.FirstName));
}
}
[Test]
public void SqlPropertyNoStoreGrouping2([DataSources] string context)
{
using (var db = GetDataContext(context))
{
var expected =
from p in Person
group p by new { p.FirstName, p.LastName } into g
select new
{
g.Key.FirstName,
g.Key.LastName,
Count = g.Count()
};
var result =
from p in db.GetTable<PersonWithoutDynamicStore>()
group p by new { FirstName = Sql.Property<string>(p, "FirstName"), LastName = Sql.Property<string>(p, "LastName")} into g
select new
{
g.Key.FirstName,
g.Key.LastName,
Count = g.Count()
};
AreEqual(result.OrderBy(_ => _.FirstName), expected.OrderBy(_ => _.FirstName));
}
}
public void CreateTestTable<T>(IDataContext db, string tableName = null)
{
db.DropTable<T>(tableName, throwExceptionIfNotExists: false);
db.CreateTable<T>(tableName);
}
[ActiveIssue(":NEW as parameter", Configurations = new[] { ProviderName.OracleNative })]
[Test]
public void SqlPropertyNoStoreNonIdentifier([DataSources] string context)
{
using (new FirebirdQuoteMode(FirebirdIdentifierQuoteMode.Auto))
using (var db = GetDataContext(context))
{
CreateTestTable<DynamicTablePrototype>(db);
try
{
db.Insert(new DynamicTablePrototype { NotIdentifier = 77 });
var query =
from d in db.GetTable<DynamicTable>()
select new
{
NI = Sql.Property<int>(d, "Not Identifier")
};
var result = query.ToArray();
Assert.AreEqual(77, result[0].NI);
}
finally
{
db.DropTable<DynamicTablePrototype>();
}
}
}
[ActiveIssue(":NEW as parameter", Configurations = new[] { ProviderName.OracleNative })]
[Test]
public void SqlPropertyNoStoreNonIdentifierGrouping([DataSources] string context)
{
using (new FirebirdQuoteMode(FirebirdIdentifierQuoteMode.Auto))
using (var db = GetDataContext(context))
{
CreateTestTable<DynamicTablePrototype>(db);
try
{
db.Insert(new DynamicTablePrototype { NotIdentifier = 77, Value = 5 });
db.Insert(new DynamicTablePrototype { NotIdentifier = 77, Value = 5 });
var query =
from d in db.GetTable<DynamicTable>()
group d by new { NI = Sql.Property<int>(d, "Not Identifier") }
into g
select new
{
g.Key.NI,
Count = g.Count(),
Sum = g.Sum(i => Sql.Property<int>(i, "Some Value"))
};
var result = query.ToArray();
Assert.AreEqual(77, result[0].NI);
Assert.AreEqual(2, result[0].Count);
Assert.AreEqual(10, result[0].Sum);
}
finally
{
db.DropTable<DynamicTablePrototype>();
}
}
}
private MappingSchema ConfigureDynamicClass()
{
var ms = new MappingSchema();
ms.GetFluentMappingBuilder()
.Entity<PersonWithDynamicStore>().HasTableName("Person")
.HasPrimaryKey(x => Sql.Property<int>(x, "ID"))
.Property(x => Sql.Property<string>(x, "FirstName")).IsNullable(false)
.Property(x => Sql.Property<string>(x, "LastName")).IsNullable(false)
.Property(x => Sql.Property<string>(x, "MiddleName"))
.Association(x => Sql.Property<Patient>(x, "Patient"), x => Sql.Property<int>(x, "ID"), x => x.PersonID);
return ms;
}
public class PersonWithDynamicStore
{
[Column("PersonID"), Identity]
public int ID { get; set; }
[DynamicColumnsStore]
public IDictionary<string, object> ExtendedProperties { get; set; }
}
[Table("Person")]
public class PersonWithoutDynamicStore
{
[Column("PersonID"), Identity, PrimaryKey]
public int ID { get; set; }
}
[Table("DynamicTable")]
public class DynamicTablePrototype
{
[Column, Identity, PrimaryKey]
public int ID { get; set; }
[Column("Not Identifier")]
public int NotIdentifier { get; set; }
[Column("Some Value")]
public int Value { get; set; }
}
[Table("DynamicTable")]
public class DynamicTable
{
[Column, Identity, PrimaryKey]
public int ID { get; set; }
}
public class SomeClassWithDynamic
{
public string Description { get; set; }
private sealed class SomeClassEqualityComparer : IEqualityComparer<SomeClassWithDynamic>
{
public bool Equals(SomeClassWithDynamic x, SomeClassWithDynamic y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (!string.Equals(x.Description, y.Description))
return false;
if (x.ExtendedProperties == null && y.ExtendedProperties == null)
return true;
if (x.ExtendedProperties == null || y.ExtendedProperties == null)
return false;
bool CompareValues(IDictionary<string, object> values1, IDictionary<string, object> values2)
{
foreach (var property in values1)
{
var value1 = property.Value as string ?? string.Empty;
values2.TryGetValue(property.Key, out var value);
var value2 = value as string ?? string.Empty;
if (!string.Equals(value1, value2))
return false;
}
return true;
}
return CompareValues(x.ExtendedProperties, y.ExtendedProperties) &&
CompareValues(y.ExtendedProperties, x.ExtendedProperties);
}
public int GetHashCode(SomeClassWithDynamic obj)
{
return (obj.Description != null ? obj.Description.GetHashCode() : 0);
}
}
public static IEqualityComparer<SomeClassWithDynamic> SomeClassComparer { get; } = new SomeClassEqualityComparer();
[DynamicColumnsStore]
public IDictionary<string, object> ExtendedProperties { get; set; }
}
[Test]
public void TestConcatWithDynamic([IncludeDataSources(true, ProviderName.SQLiteClassic)] string context)
{
var mappingSchema = new MappingSchema();
var builder = mappingSchema.GetFluentMappingBuilder()
.Entity<SomeClassWithDynamic>();
builder.Property(x => x.Description).HasColumnName("F066_04");
builder.Property(x => Sql.Property<string>(x, "F066_05"));
builder.Property(x => Sql.Property<string>(x, "F066_00"));
var testData1 = new[]
{
new SomeClassWithDynamic{Description = "Desc1", ExtendedProperties = new Dictionary<string, object>{{"F066_05", "v1"}}},
new SomeClassWithDynamic{Description = "Desc2", ExtendedProperties = new Dictionary<string, object>{{"F066_05", "v2"}}},
};
var testData2 = new[]
{
new SomeClassWithDynamic{Description = "Desc3", ExtendedProperties = new Dictionary<string, object>{{"F066_00", "v3"}}},
new SomeClassWithDynamic{Description = "Desc4", ExtendedProperties = new Dictionary<string, object>{{"F066_00", "v4"}}},
};
using (var dataContext = GetDataContext(context, mappingSchema))
{
using (dataContext.CreateLocalTable("M998_T066", testData1))
using (dataContext.CreateLocalTable("M998_T000", testData2))
{
var expected = testData1.Concat(testData2);
var result =
dataContext.GetTable<SomeClassWithDynamic>().TableName("M998_T066")
.Concat(dataContext.GetTable<SomeClassWithDynamic>().TableName("M998_T000"))
.ToList();
AreEqual(expected, result, SomeClassWithDynamic.SomeClassComparer);
}
}
}
}
}
| 30.945671 | 127 | 0.644977 | [
"MIT"
] | Partiolainen/linq2db | Tests/Linq/Linq/DynamicColumnsTests.cs | 18,229 | C# |
/*************************************************************************
* Copyright ? 2018-2019 Mogoson. All rights reserved.
*------------------------------------------------------------------------
* File : HermiteHoseEditor.cs
* Description : Editor for HermiteHose component.
*------------------------------------------------------------------------
* Author : Mogoson
* Version : 1.0
* Date : 3/20/2018
* Description : Initial development version.
*************************************************************************/
using MGS.SkinnedMesh;
using UnityEditor;
using UnityEngine;
namespace MGS.SkinnedMeshEditor
{
[CustomEditor(typeof(HermiteHose), true)]
[CanEditMultipleObjects]
public class HermiteHoseEditor : MonoCurveHoseEditor
{
#region Field and Property
protected new HermiteHose Target { get { return target as HermiteHose; } }
#endregion
#region Protected Method
protected override void OnSceneGUI()
{
base.OnSceneGUI();
if (Application.isPlaying)
{
return;
}
DrawHermiteCurveEditor();
}
protected override void DrawHoseCenterCurve()
{
Handles.color = Blue;
var scaleDelta = Mathf.Max(Delta, Delta * GetHandleSize(Target.transform.position));
for (float t = 0; t < Target.MaxKey; t += scaleDelta)
{
Handles.DrawLine(Target.GetPointAt(t), Target.GetPointAt(Mathf.Min(Target.MaxKey, t + scaleDelta)));
}
}
protected void DrawHermiteCurveEditor()
{
for (int i = 0; i < Target.AnchorsCount; i++)
{
var anchorItem = Target.GetAnchorAt(i);
if (Event.current.alt)
{
Handles.color = Color.green;
DrawAdaptiveButton(anchorItem, Quaternion.identity, NodeSize, NodeSize, SphereCap, () =>
{
var offset = Vector3.zero;
if (i > 0)
{
offset = (anchorItem - Target.GetAnchorAt(i - 1)).normalized * GetHandleSize(anchorItem);
}
else
{
offset = Vector3.forward * GetHandleSize(anchorItem);
}
Target.InsertAnchor(i + 1, anchorItem + offset);
Target.Rebuild();
});
}
else if (Event.current.shift)
{
Handles.color = Color.red;
DrawAdaptiveButton(anchorItem, Quaternion.identity, NodeSize, NodeSize, SphereCap, () =>
{
if (Target.AnchorsCount > 1)
{
Target.RemoveAnchorAt(i);
Target.Rebuild();
}
});
}
else
{
Handles.color = Blue;
DrawFreeMoveHandle(anchorItem, Quaternion.identity, NodeSize, MoveSnap, SphereCap, position =>
{
Target.SetAnchorAt(i, position);
Target.Rebuild();
});
}
}
}
#endregion
}
} | 36.760417 | 117 | 0.4259 | [
"Apache-2.0"
] | mogoson/CodeProject | SkinnedMeshEditor/CurveHose/HermiteHoseEditor.cs | 3,529 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Equinor.ProCoSys.Preservation.Command.EventHandlers.HistoryEvents;
using Equinor.ProCoSys.Preservation.Domain;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.HistoryAggregate;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.JourneyAggregate;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.ModeAggregate;
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.ResponsibleAggregate;
using Equinor.ProCoSys.Preservation.Domain.Events;
using Equinor.ProCoSys.Preservation.Test.Common.ExtensionMethods;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Equinor.ProCoSys.Preservation.Command.Tests.EventHandlers.HistoryEvents
{
[TestClass]
public class StepChangedEventHandlerTests
{
private readonly string TestPlant = "TestPlant";
private readonly string Journey1 = "TestJourney1";
private readonly string Journey2 = "TestJourney2";
private readonly string FromStep = "TestStep1";
private readonly string ToStepInJourney1 = "TestStep2";
private readonly string ToStepInJourney2 = "TestStep3";
private readonly int Journey1Id = 12;
private readonly int Journey2Id = 13;
private readonly int FromStepId = 1;
private readonly int ToStepIdInJourney1 = 2;
private readonly int ToStepIdInJourney2 = 3;
private Mock<IHistoryRepository> _historyRepositoryMock;
private StepChangedEventHandler _dut;
private History _historyAdded;
private Mock<IJourneyRepository> _journeyRepositoryMock;
[TestInitialize]
public void Setup()
{
var modeMock = new Mock<Mode>();
modeMock.SetupGet(m => m.Plant).Returns(TestPlant);
var respMock = new Mock<Responsible>();
respMock.SetupGet(m => m.Plant).Returns(TestPlant);
// Arrange
var fromStep = new Step(TestPlant, FromStep, modeMock.Object, respMock.Object);
fromStep.SetProtectedIdForTesting(FromStepId);
var toStepInJourney1 = new Step(TestPlant, ToStepInJourney1, modeMock.Object, respMock.Object);
toStepInJourney1.SetProtectedIdForTesting(ToStepIdInJourney1);
var toStepInJourney2 = new Step(TestPlant, ToStepInJourney2, modeMock.Object, respMock.Object);
toStepInJourney2.SetProtectedIdForTesting(ToStepIdInJourney2);
var journey1 = new Journey(TestPlant, Journey1);
journey1.SetProtectedIdForTesting(Journey1Id);
journey1.AddStep(fromStep);
journey1.AddStep(toStepInJourney1);
var journey2 = new Journey(TestPlant, Journey2);
journey2.SetProtectedIdForTesting(Journey2Id);
journey2.AddStep(toStepInJourney2);
_historyRepositoryMock = new Mock<IHistoryRepository>();
_historyRepositoryMock
.Setup(repo => repo.Add(It.IsAny<History>()))
.Callback<History>(history =>
{
_historyAdded = history;
});
_journeyRepositoryMock = new Mock<IJourneyRepository>();
_journeyRepositoryMock
.Setup(repo => repo.GetJourneysByStepIdsAsync(new List<int>{FromStepId, ToStepIdInJourney1}))
.Returns(Task.FromResult(new List<Journey> { journey1, journey1 }));
_journeyRepositoryMock
.Setup(repo => repo.GetJourneysByStepIdsAsync(new List<int>{FromStepId, ToStepIdInJourney2}))
.Returns(Task.FromResult(new List<Journey> { journey1, journey2 }));
_dut = new StepChangedEventHandler(_historyRepositoryMock.Object, _journeyRepositoryMock.Object);
}
[TestMethod]
public async Task Handle_ShouldAddStepChangedHistoryRecord_WhenStepsInSameJourney()
{
// Arrange
Assert.IsNull(_historyAdded);
// Act
var objectGuid = Guid.NewGuid();
await _dut.Handle(new StepChangedEvent(TestPlant, objectGuid, FromStepId, ToStepIdInJourney1), default);
// Assert
var expectedDescription = $"{EventType.StepChanged.GetDescription()} - From '{FromStep}' to '{ToStepInJourney1}' in journey '{Journey1}'";
Assert.IsNotNull(_historyAdded);
Assert.AreEqual(TestPlant, _historyAdded.Plant);
Assert.AreEqual(objectGuid, _historyAdded.ObjectGuid);
Assert.IsNotNull(_historyAdded.Description);
Assert.AreEqual(EventType.StepChanged, _historyAdded.EventType);
Assert.AreEqual(ObjectType.Tag, _historyAdded.ObjectType);
Assert.AreEqual(expectedDescription, _historyAdded.Description);
Assert.IsFalse(_historyAdded.PreservationRecordGuid.HasValue);
Assert.IsFalse(_historyAdded.DueInWeeks.HasValue);
}
[TestMethod]
public async Task Handle_ShouldAddJourneyChangedHistoryRecord_WhenStepsInDifferentJourneys()
{
// Arrange
Assert.IsNull(_historyAdded);
// Act
var objectGuid = Guid.NewGuid();
await _dut.Handle(new StepChangedEvent(TestPlant, objectGuid, FromStepId, ToStepIdInJourney2), default);
// Assert
var expectedDescription = $"{EventType.JourneyChanged.GetDescription()} - From journey '{Journey1}' / step '{FromStep}' to journey '{Journey2}' / step '{ToStepInJourney2}'";
Assert.IsNotNull(_historyAdded);
Assert.AreEqual(TestPlant, _historyAdded.Plant);
Assert.AreEqual(objectGuid, _historyAdded.ObjectGuid);
Assert.IsNotNull(_historyAdded.Description);
Assert.AreEqual(EventType.JourneyChanged, _historyAdded.EventType);
Assert.AreEqual(ObjectType.Tag, _historyAdded.ObjectType);
Assert.AreEqual(expectedDescription, _historyAdded.Description);
Assert.IsFalse(_historyAdded.PreservationRecordGuid.HasValue);
Assert.IsFalse(_historyAdded.DueInWeeks.HasValue);
}
}
}
| 48.140625 | 185 | 0.685005 | [
"MIT"
] | equinor/pcs-preservation-api | src/tests/Equinor.ProCoSys.Preservation.Command.Tests/EventHandlers/HistoryEvents/StepChangedEventHandlerTests.cs | 6,164 | C# |
using System;
using System.Buffers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BencodeNET.Exceptions;
using BencodeNET.IO;
using BencodeNET.Objects;
namespace BencodeNET.Parsing
{
/// <summary>
/// A parser for bencoded byte strings.
/// </summary>
public class BStringParser : BObjectParser<BString>
{
/// <summary>
/// The minimum stream length in bytes for a valid string ('0:').
/// </summary>
protected const int MinimumLength = 2;
/// <summary>
/// Creates an instance using <see cref="System.Text.Encoding.UTF8"/> for parsing.
/// </summary>
public BStringParser()
: this(Encoding.UTF8)
{ }
/// <summary>
/// Creates an instance using the specified encoding for parsing.
/// </summary>
/// <param name="encoding"></param>
public BStringParser(Encoding encoding)
{
_encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
}
/// <summary>
/// The encoding used when creating the <see cref="BString"/> when parsing.
/// </summary>
public override Encoding Encoding => _encoding;
private Encoding _encoding;
/// <summary>
/// Changes the encoding used for parsing.
/// </summary>
/// <param name="encoding">The new encoding to use.</param>
public void ChangeEncoding(Encoding encoding)
{
_encoding = encoding;
}
/// <summary>
/// Parses the next <see cref="BString"/> from the reader.
/// </summary>
/// <param name="reader">The reader to parse from.</param>
/// <returns>The parsed <see cref="BString"/>.</returns>
/// <exception cref="InvalidBencodeException{BString}">Invalid bencode.</exception>
/// <exception cref="UnsupportedBencodeException{BString}">The bencode is unsupported by this library.</exception>
public override BString Parse(BencodeReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
// Minimum valid bencode string is '0:' meaning an empty string
if (reader.Length < MinimumLength)
throw InvalidBencodeException<BString>.BelowMinimumLength(MinimumLength, reader.Length.Value, reader.Position);
var startPosition = reader.Position;
var buffer = ArrayPool<char>.Shared.Rent(BString.LengthMaxDigits);
try
{
var lengthString = buffer.AsSpan();
var lengthStringCount = 0;
for (var c = reader.ReadChar(); c != default && c.IsDigit(); c = reader.ReadChar())
{
EnsureLengthStringBelowMaxLength(lengthStringCount, startPosition);
lengthString[lengthStringCount++] = c;
}
EnsurePreviousCharIsColon(reader.PreviousChar, reader.Position);
var stringLength = ParseStringLength(lengthString, lengthStringCount, startPosition);
var bytes = new byte[stringLength];
var bytesRead = reader.Read(bytes);
EnsureExpectedBytesRead(bytesRead, stringLength, startPosition);
return new BString(bytes, Encoding);
}
finally
{
ArrayPool<char>.Shared.Return(buffer);
}
}
/// <summary>
/// Parses the next <see cref="BString"/> from the reader.
/// </summary>
/// <param name="reader">The reader to parse from.</param>
/// <param name="cancellationToken"></param>
/// <returns>The parsed <see cref="BString"/>.</returns>
/// <exception cref="InvalidBencodeException{BString}">Invalid bencode.</exception>
/// <exception cref="UnsupportedBencodeException{BString}">The bencode is unsupported by this library.</exception>
public override async ValueTask<BString> ParseAsync(PipeBencodeReader reader, CancellationToken cancellationToken = default)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
var startPosition = reader.Position;
using (var memoryOwner = MemoryPool<char>.Shared.Rent(BString.LengthMaxDigits))
{
var lengthString = memoryOwner.Memory;
var lengthStringCount = 0;
for (var c = await reader.ReadCharAsync(cancellationToken).ConfigureAwait(false);
c != default && c.IsDigit();
c = await reader.ReadCharAsync(cancellationToken).ConfigureAwait(false))
{
EnsureLengthStringBelowMaxLength(lengthStringCount, startPosition);
lengthString.Span[lengthStringCount++] = c;
}
EnsurePreviousCharIsColon(reader.PreviousChar, reader.Position);
var stringLength = ParseStringLength(lengthString.Span, lengthStringCount, startPosition);
var bytes = new byte[stringLength];
var bytesRead = await reader.ReadAsync(bytes, cancellationToken).ConfigureAwait(false);
EnsureExpectedBytesRead(bytesRead, stringLength, startPosition);
return new BString(bytes, Encoding);
}
}
/// <summary>
/// Ensures that the length (number of digits) of the string-length part is not above <see cref="BString.LengthMaxDigits"/>
/// as that would equal 10 GB of data, which we cannot handle.
/// </summary>
private void EnsureLengthStringBelowMaxLength(int lengthStringCount, long startPosition)
{
// Because of memory limitations (~1-2 GB) we know for certain we cannot handle more than 10 digits (10GB)
if (lengthStringCount >= BString.LengthMaxDigits)
{
throw UnsupportedException(
$"Length of string is more than {BString.LengthMaxDigits} digits (>10GB) and is not supported (max is ~1-2GB).",
startPosition);
}
}
/// <summary>
/// Ensure that the previously read char is a colon (:),
/// separating the string-length part and the actual string value.
/// </summary>
private void EnsurePreviousCharIsColon(char previousChar, long position)
{
if (previousChar != ':') throw InvalidBencodeException<BString>.UnexpectedChar(':', previousChar, position - 1);
}
/// <summary>
/// Parses the string-length <see cref="string"/> into a <see cref="long"/>.
/// </summary>
private long ParseStringLength(Span<char> lengthString, int lengthStringCount, long startPosition)
{
lengthString = lengthString.Slice(0, lengthStringCount);
if (!ParseUtil.TryParseLongFast(lengthString, out var stringLength))
throw InvalidException($"Invalid length '{lengthString.AsString()}' of string.", startPosition);
// Int32.MaxValue is ~2GB and is the absolute maximum that can be handled in memory
if (stringLength > int.MaxValue)
{
throw UnsupportedException(
$"Length of string is {stringLength:N0} but maximum supported length is {int.MaxValue:N0}.",
startPosition);
}
return stringLength;
}
/// <summary>
/// Ensures that number of bytes read matches the expected number parsed from the string-length part.
/// </summary>
private void EnsureExpectedBytesRead(long bytesRead, long stringLength, long startPosition)
{
// If the two don't match we've reached the end of the stream before reading the expected number of chars
if (bytesRead == stringLength) return;
throw InvalidException(
$"Expected string to be {stringLength:N0} bytes long but could only read {bytesRead:N0} bytes.",
startPosition);
}
private static InvalidBencodeException<BString> InvalidException(string message, long startPosition)
{
return new InvalidBencodeException<BString>(
$"{message} The string starts at position {startPosition}.",
startPosition);
}
private static UnsupportedBencodeException<BString> UnsupportedException(string message, long startPosition)
{
return new UnsupportedBencodeException<BString>(
$"{message} The string starts at position {startPosition}.",
startPosition);
}
}
}
| 41.677725 | 132 | 0.603935 | [
"Unlicense"
] | djon2003/BencodeNET | BencodeNET/Parsing/BStringParser.cs | 8,794 | C# |
using System.Linq;
using JudgeSystem.Data.Models;
using JudgeSystem.Web.Controllers;
using JudgeSystem.Web.InputModels.Feedback;
using JudgeSystem.Common;
using MyTested.AspNetCore.Mvc;
using Xunit;
using Shouldly;
namespace JudgeSystem.Web.Tests.Controllers
{
public class FeedbackControllerTests
{
[Fact]
public void FeedbackControllerActions_ShouldBeAllowedOnlyForAuthorizedUser() =>
MyController<FeedbackController>
.Instance()
.ShouldHave()
.Attributes(attributes => attributes.RestrictingForAuthorizedRequests());
[Fact]
public void Send_ShouldReturnView() =>
MyController<FeedbackController>
.Instance()
.Calling(c => c.Send())
.ShouldReturn()
.View();
[Fact]
public void Send_ShouldHaveAttribtesForPostRequestAndAntiForgeryToken() =>
MyController<FeedbackController>
.Instance()
.Calling(c => c.Send(With.Default<FeedbackCreateInputModel>()))
.ShouldHave()
.ActionAttributes(attributes => attributes
.RestrictingForHttpMethod(HttpMethod.Post)
.ValidatingAntiForgeryToken());
[Theory]
[InlineData(ModelConstants.FeedbackContentMaxLength + 1)]
[InlineData(ModelConstants.FeedbackContentMinLength - 1)]
public void Send_WithInvalidModelStateShouldReturnViewWithTheSameViewModel(int contentLength)
{
string content = new string('a', contentLength);
MyController<FeedbackController>
.Instance()
.Calling(c => c.Send(new FeedbackCreateInputModel { Content = content }))
.ShouldHave()
.ModelState(modekState => modekState.For<FeedbackCreateInputModel>().ContainingErrorFor(m => m.Content))
.AndAlso()
.ShouldReturn()
.View(result => result
.WithModelOfType<FeedbackCreateInputModel>()
.Passing(model => model.Content == content));
}
[Theory]
[InlineData("Judge System works fine")]
public void Send_WithValidFeedback_ShouldReturnRedirectAndShoudAddFeedback(string content) =>
MyController<FeedbackController>
.Instance()
.WithUser(user => user.WithUsername("nasko"))
.Calling(c => c.Send(new FeedbackCreateInputModel { Content = content }))
.ShouldHave()
.Data(data => data
.WithSet<Feedback>(set =>
{
set.ShouldNotBeNull();
set.FirstOrDefault(f => f.Content == content).ShouldNotBeNull();
}))
.AndAlso()
.ShouldReturn()
.Redirect(result => result.To<HomeController>(c => c.Index()));
}
}
| 36.316456 | 115 | 0.606832 | [
"MIT"
] | NaskoVasilev/JudgeSystem | Tests/JudgeSystem.Web.Tests/Controllers/FeedbackControllerTests.cs | 2,871 | C# |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using DocuSign.eSign.Api;
using DocuSign.eSign.Model;
using DocuSign.eSign.Client;
using System.Reflection;
namespace DocuSign.eSign.Test
{
/// <summary>
/// Class for testing ServerTemplate
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class ServerTemplateTests
{
// TODO uncomment below to declare an instance variable for ServerTemplate
//private ServerTemplate instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of ServerTemplate
//instance = new ServerTemplate();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of ServerTemplate
/// </summary>
[Test]
public void ServerTemplateInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" ServerTemplate
//Assert.IsInstanceOfType<ServerTemplate> (instance, "variable 'instance' is a ServerTemplate");
}
/// <summary>
/// Test the property 'Sequence'
/// </summary>
[Test]
public void SequenceTest()
{
// TODO unit test for the property 'Sequence'
}
/// <summary>
/// Test the property 'TemplateId'
/// </summary>
[Test]
public void TemplateIdTest()
{
// TODO unit test for the property 'TemplateId'
}
}
}
| 25.298851 | 125 | 0.590186 | [
"MIT"
] | CameronLoewen/docusign-csharp-client | sdk/src/DocuSign.eSign.Test/Model/ServerTemplateTests.cs | 2,201 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Engine.Commands;
using Engine.Components;
using Engine.Events;
using PlayGen.ITAlert.Simulation.Components.Common;
using PlayGen.ITAlert.Simulation.Components.EntityTypes;
using PlayGen.ITAlert.Simulation.Components.Items;
using PlayGen.ITAlert.Simulation.Events;
namespace PlayGen.ITAlert.Simulation.Commands
{
[Deduplicate(DeduplicationPolicy.Replace)]
public class SwapSubsystemItemCommand : ICommand
{
public int PlayerId { get; set; }
public int SubsystemId { get; set; }
public int FromItemId { get; set; }
public int? ToItemId { get; set; }
public int FromContainerIndex { get; set; }
public int ToContainerIndex { get; set; }
}
public class SwapSubsystemItemCommandHandler : CommandHandler<SwapSubsystemItemCommand>
{
private readonly ComponentMatcherGroup<Player, ItemStorage, CurrentLocation> _playerMatcherGroup;
private readonly ComponentMatcherGroup<Item, Owner, CurrentLocation, IItemType> _itemMatcherGroup;
private readonly ComponentMatcherGroup<Subsystem, ItemStorage> _subsystemMatcherGroup;
private readonly EventSystem _eventSystem;
#region Overrides of CommandHandler<SwapSubsystemItemCommand>
public override IEqualityComparer<ICommand> Deduplicator => new SwapSubsystemItemCommandEqualityComparer();
#endregion
public SwapSubsystemItemCommandHandler(IMatcherProvider matcherProvider, EventSystem eventSystem)
{
_playerMatcherGroup = matcherProvider.CreateMatcherGroup<Player, ItemStorage, CurrentLocation>();
_itemMatcherGroup = matcherProvider.CreateMatcherGroup<Item, Owner, CurrentLocation, IItemType>();
_subsystemMatcherGroup = matcherProvider.CreateMatcherGroup<Subsystem, ItemStorage>();
_eventSystem = eventSystem;
}
protected override bool TryHandleCommand(SwapSubsystemItemCommand command, int currentTick, bool handlerEnabled)
{
ComponentEntityTuple<Item, Owner, CurrentLocation, IItemType> toItemTuple = null;
if (_playerMatcherGroup.TryGetMatchingEntity(command.PlayerId,
out var playerTuple)
&& _itemMatcherGroup.TryGetMatchingEntity(command.FromItemId,
out var fromItemTuple)
&& (!command.ToItemId.HasValue
|| _itemMatcherGroup.TryGetMatchingEntity(command.ToItemId.Value,
out toItemTuple))
// Player must be on a subsystem
&& playerTuple.Component3.Value.HasValue
&& _subsystemMatcherGroup.TryGetMatchingEntity(playerTuple.Component3.Value.Value,
out var subsystemTuple)
// Must be same subsystem as when command was issued
&& subsystemTuple.Entity.Id == command.SubsystemId)
{
var @event = new SwapSubsystemItemCommandEvent()
{
FromItemId = fromItemTuple.Entity.Id,
FromItemType = fromItemTuple.Component4.GetType().Name,
ToItemId = toItemTuple?.Entity.Id ?? -1,
ToItemType = toItemTuple?.Component4.GetType().Name,
PlayerEntityId = command.PlayerId,
SubsystemEntityId = fromItemTuple.Component3.Value ?? -1
};
// No one must own either item
if (handlerEnabled && fromItemTuple.Component2.Value == null && toItemTuple?.Component2.Value == null)
{
var toContainer = subsystemTuple.Component2.Items[command.ToContainerIndex];
var fromContainer = subsystemTuple.Component2.Items[command.FromContainerIndex];
@event.FromContainerType = fromContainer.GetType().Name;
@event.ToContainerType = toContainer.GetType().Name;
// Items must still be in same locations as when the command was issued
if (fromContainer.Item == command.FromItemId
&& toContainer.Item == command.ToItemId
// Must be enabled
&& fromContainer.Enabled
&& toContainer.Enabled
// Must be able to release items
&& (fromContainer.CanRelease || fromContainer.Item == null)
&& (toContainer.CanRelease || toContainer.Item == null)
// Containers must be able to accept items
&& toContainer.CanContain(command.FromItemId)
&& (!command.ToItemId.HasValue || fromContainer.CanContain(command.ToItemId.Value)))
{
toContainer.Item = command.FromItemId;
fromContainer.Item = command.ToItemId;
@event.Result = SwapSubsystemItemCommandEvent.ActivationResult.Success;
_eventSystem.Publish(@event);
return true;
}
else
{
if (toContainer.CanContain(command.FromItemId)
&& (!command.ToItemId.HasValue || fromContainer.CanContain(command.ToItemId.Value)))
{
@event.Result = SwapSubsystemItemCommandEvent.ActivationResult.Error;
_eventSystem.Publish(@event);
}
else
{
@event.Result = SwapSubsystemItemCommandEvent.ActivationResult.Failure_DestinationCannotCapture;
_eventSystem.Publish(@event);
}
}
}
else
{
if (handlerEnabled)
{
@event.Result = SwapSubsystemItemCommandEvent.ActivationResult.Failure_ItemAlreadyActive;
_eventSystem.Publish(@event);
}
else
{
@event.Result = SwapSubsystemItemCommandEvent.ActivationResult.Failure_CommandDisabled;
_eventSystem.Publish(@event);
}
}
}
return false;
}
}
public class SwapSubsystemItemCommandEqualityComparer : CommandEqualityComparer<SwapSubsystemItemCommand>
{
#region Overrides of CommandEqualityComparer<SwapSubsystemItemCommand>
protected override bool IsDuplicate(SwapSubsystemItemCommand a, SwapSubsystemItemCommand b)
{
return a.PlayerId == b.PlayerId
&& (a.ToItemId == b.ToItemId
|| a.ToItemId == b.FromItemId
|| a.FromItemId == b.ToItemId
|| a.FromItemId == b.FromItemId);
}
#endregion
}
public class SwapSubsystemItemCommandEvent : Event, IPlayerEvent, ISubsystemEvent
{
public enum ActivationResult
{
Error = 0,
Success,
Failure_ItemAlreadyActive,
Failure_DestinationCannotCapture,
Failure_CommandDisabled,
}
public ActivationResult Result { get; set; }
public int FromItemId { get; set; }
public string FromItemType { get; set; }
public string FromContainerType { get; set; }
public int ToItemId { get; set; }
public string ToItemType { get; set; }
public string ToContainerType { get; set; }
public int PlayerEntityId { get; set; }
public int SubsystemEntityId { get; set; }
}
}
| 34.091398 | 114 | 0.739316 | [
"Apache-2.0"
] | playgen/it-alert | Simulation/PlayGen.ITAlert.Simulation/Commands/SwapSubsystemItemCommand.cs | 6,343 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesis-2013-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Kinesis.Model
{
/// <summary>
/// Container for the parameters to the AddTagsToStream operation.
/// Adds or updates tags for the specified Amazon Kinesis stream. Each stream can have
/// up to 10 tags.
///
///
/// <para>
/// If tags have already been assigned to the stream, <code>AddTagsToStream</code> overwrites
/// any existing tags that correspond to the specified tag keys.
/// </para>
/// </summary>
public partial class AddTagsToStreamRequest : AmazonKinesisRequest
{
private string _streamName;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property StreamName.
/// <para>
/// The name of the stream.
/// </para>
/// </summary>
public string StreamName
{
get { return this._streamName; }
set { this._streamName = value; }
}
// Check to see if StreamName property is set
internal bool IsSetStreamName()
{
return this._streamName != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The set of key-value pairs to use to create the tags.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 30.578313 | 105 | 0.616627 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/Kinesis/Generated/Model/AddTagsToStreamRequest.cs | 2,538 | C# |
namespace DesignPatternsInCSharp.Behavioral.Chain.Conceptual;
public enum ChainLogLevel
{
DEBUG,
INFO,
WARNING
}
| 15.625 | 61 | 0.76 | [
"MIT"
] | adamradocz/DesignPatternsInCSharp | DesignPatternsInCSharp/Behavioral/Chain/Conceptual/ChainLogLevel.cs | 125 | C# |
using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditor.Experimental.SceneManagement;
using CommonMaxTools.Attributes;
namespace CommonMaxTools.Editor.Utils
{
public static class ExtendedEditorGUI
{
/// <summary>
/// Handles and show button in Inspector that invokes and performs specified method
/// </summary>
public static void ButtonHandle(UnityEngine.Object target, MethodInfo method)
{
if(!method.GetParameters().All(p => p.IsOptional))
{
Debug.LogError($"Failed to invoke method {method.Name} from gameobject {target.name}. It has a non optional parameters.");
return;
}
var buttonAttribute = method.GetCustomAttribute(typeof(ButtonMethodAttribute), true) as ButtonMethodAttribute;
if(buttonAttribute == null)
{
Debug.LogError($"Failed to get attribute by type {typeof(ButtonMethodAttribute)} from method");
return;
}
string buttonText = String.IsNullOrWhiteSpace(buttonAttribute.Text) ?
ObjectNames.NicifyVariableName(method.Name) : buttonAttribute.Text;
bool buttonEnabled = true;
if(method.ReturnType == typeof(IEnumerator))
{
buttonEnabled &= Application.isPlaying ? true : false;
}
EditorGUI.BeginDisabledGroup(!buttonEnabled);
if (GUILayout.Button(buttonText))
{
object[] defaultParams = method.GetParameters().Select(p => p.DefaultValue).ToArray();
IEnumerator methodResult = method.Invoke(target, defaultParams) as IEnumerator;
if (!Application.isPlaying)
{
// Set target object and scene dirty to serialize changes to disk
EditorUtility.SetDirty(target);
PrefabStage stage = PrefabStageUtility.GetCurrentPrefabStage();
if (stage != null)
{
// Prefab mode
EditorSceneManager.MarkSceneDirty(stage.scene);
}
else
{
// Normal scene
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
}
else if (methodResult != null && target is MonoBehaviour behaviour)
{
behaviour.StartCoroutine(methodResult);
}
}
EditorGUI.EndDisabledGroup();
}
/// <summary>
/// Draw colored box in Inspector
/// </summary>
public static void DrawColorBox(Rect position, Color bgColor, string label = "")
{
var defaultBGColor = GUI.backgroundColor;
GUI.backgroundColor = bgColor;
GUI.Box(position, label);
GUI.backgroundColor = defaultBGColor;
}
}
}
| 35.595506 | 138 | 0.565972 | [
"MIT"
] | Markmax2304/CommonMaxTools | Editor/Utils/ExtendedEditorGUI.cs | 3,170 | C# |
namespace MediaLibrary
{
partial class PersonControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.personName = new System.Windows.Forms.Label();
this.deleteButton = new System.Windows.Forms.PictureBox();
this.personPicture = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.deleteButton)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.personPicture)).BeginInit();
this.SuspendLayout();
//
// personName
//
this.personName.AutoSize = true;
this.personName.Dock = System.Windows.Forms.DockStyle.Fill;
this.personName.ForeColor = System.Drawing.SystemColors.InfoText;
this.personName.Location = new System.Drawing.Point(20, 0);
this.personName.Margin = new System.Windows.Forms.Padding(3, 0, 23, 0);
this.personName.Name = "personName";
this.personName.Size = new System.Drawing.Size(13, 13);
this.personName.TabIndex = 1;
this.personName.Text = "?";
this.personName.Click += new System.EventHandler(this.Person_Click);
this.personName.DoubleClick += new System.EventHandler(this.Person_DoubleClick);
this.personName.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Person_MouseClick);
this.personName.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Person_MouseDoubleClick);
//
// deleteButton
//
this.deleteButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.deleteButton.Dock = System.Windows.Forms.DockStyle.Right;
this.deleteButton.Image = global::MediaLibrary.Properties.Resources.remove_circle;
this.deleteButton.Location = new System.Drawing.Point(33, 0);
this.deleteButton.Margin = new System.Windows.Forms.Padding(0);
this.deleteButton.Name = "deleteButton";
this.deleteButton.Size = new System.Drawing.Size(20, 13);
this.deleteButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.deleteButton.TabIndex = 2;
this.deleteButton.TabStop = false;
this.deleteButton.Click += new System.EventHandler(this.DeleteButton_Click);
//
// personPicture
//
this.personPicture.Dock = System.Windows.Forms.DockStyle.Left;
this.personPicture.Image = global::MediaLibrary.Properties.Resources.single_neutral;
this.personPicture.Location = new System.Drawing.Point(0, 0);
this.personPicture.Name = "personPicture";
this.personPicture.Size = new System.Drawing.Size(20, 13);
this.personPicture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.personPicture.TabIndex = 0;
this.personPicture.TabStop = false;
this.personPicture.Click += new System.EventHandler(this.Person_Click);
this.personPicture.DoubleClick += new System.EventHandler(this.Person_DoubleClick);
this.personPicture.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Person_MouseClick);
this.personPicture.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Person_MouseDoubleClick);
//
// PersonControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.SystemColors.Info;
this.Controls.Add(this.personName);
this.Controls.Add(this.deleteButton);
this.Controls.Add(this.personPicture);
this.Name = "PersonControl";
this.Size = new System.Drawing.Size(53, 13);
((System.ComponentModel.ISupportInitialize)(this.deleteButton)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.personPicture)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox personPicture;
private System.Windows.Forms.Label personName;
private System.Windows.Forms.PictureBox deleteButton;
}
}
| 48.990826 | 124 | 0.631461 | [
"MIT"
] | GoddessArtemis/MediaLibrary | MediaLibrary/PersonControl.Designer.cs | 5,342 | C# |
namespace System.Runtime.CompilerServices
{
#if NET20
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
internal sealed class ExtensionAttribute : Attribute { }
#endif
} | 31.857143 | 98 | 0.793722 | [
"MIT"
] | SamKuppusamy/CsvReader | code/LumenWorks.Framework.IO/System/AttributeExtensions.cs | 225 | C# |
using System;
using System.Collections.Generic;
using Smooth.Algebraics;
namespace Smooth.Collections {
/// <summary>
/// Extension methods for IDictionary<>s.
/// </summary>
public static class IDictionaryExtensions {
/// <summary>
/// Analog to IDictionary<K, V>.TryGetValue(K, out V) that returns an option instead of using an out parameter.
/// </summary>
public static Option<V> TryGet<K, V>(this IDictionary<K, V> dictionary, K key) {
V value;
return dictionary.TryGetValue(key, out value) ? new Option<V>(value) : new Option<V>();
}
}
}
| 27.380952 | 119 | 0.693913 | [
"Apache-2.0"
] | AndroFARsh/BoidsExperiment | Assets/Plugins/Smooth/Foundations/Collections/IDictionaryExtensions.cs | 577 | C# |
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved.
/*
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.Transform)]
[Tooltip("Moves a Game Object's Rigid Body to a new position. To leave any axis unchanged, set variable to 'None'.")]
public class MovePosition : FsmStateAction
{
[RequiredField]
[CheckForComponent(typeof(Rigidbody))]
public FsmOwnerDefault gameObject;
[UIHint(UIHint.Variable)]
public FsmVector3 vector;
public FsmFloat x;
public FsmFloat y;
public FsmFloat z;
public Space space;
public bool everyFrame;
public override void Reset()
{
gameObject = null;
vector = null;
// default axis to variable dropdown with None selected.
x = new FsmFloat { UseVariable = true };
y = new FsmFloat { UseVariable = true };
z = new FsmFloat { UseVariable = true };
space = Space.Self;
everyFrame = false;
}
/* Transform scale doesn't stick in OnEnter
* TODO: figure out why...
public override void OnEnter()
{
DoSetPosition();
if (!everyFrame)
Finish();
}
public override void OnUpdate()
{
DoMovePosition();
if (!everyFrame)
Finish();
}
void DoMovePosition()
{
GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);
if (go == null) return;
if (go.rigidbody == null) return;
// init position
Vector3 position;
if (vector.IsNone)
{
if (space == Space.World)
position = go.rigidbody.position;
else
position = go.transform.TransformPoint(go.rigidbody.position);
}
else
{
position = vector.Value;
}
// override any axis
if (!x.IsNone) position.x = x.Value;
if (!y.IsNone) position.y = y.Value;
if (!z.IsNone) position.z = z.Value;
// apply
if (space == Space.World)
go.rigidbody.MovePosition(position);
else
go.rigidbody.MovePosition(go.transform.InverseTransformPoint(position))
}
}
}
*/ | 21.326087 | 118 | 0.66208 | [
"MIT"
] | 517752548/UnityFramework | GameFrameWork/ThirdParty/PlayMaker/Actions/Transform/MovePosition.cs | 1,962 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Analogy.DataProviders.Extensions
{
public interface IAnalogyComponentImages
{
Image GetLargeImage(Guid analogyComponentId);
Image GetSmallImage(Guid analogyComponentId);
Image GetOnlineConnectedLargeImage(Guid analogyComponentId);
Image GetOnlineConnectedSmallImage(Guid analogyComponentId);
Image GetOnlineDisconnectedLargeImage(Guid analogyComponentId);
Image GetOnlineDisconnectedSmallImage(Guid analogyComponentId);
}
}
| 31.7 | 71 | 0.782334 | [
"MIT"
] | Analogy-LogViewer/Analogy.DataProviders.Extensions | Analogy.DataProviders.Extensions/IAnalogyComponentImages.cs | 636 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.AvoidMultipleEnumerations.FlowAnalysis
{
/// <summary>
/// Represents a symbol with the deferred type that might come from many sources.
/// </summary>
internal class DeferredTypeEntitySet : CacheBasedEquatable<DeferredTypeEntitySet>, IDeferredTypeEntity
{
public ImmutableHashSet<AbstractLocation> DeferredTypeLocations { get; }
public DeferredTypeEntitySet(ImmutableHashSet<AbstractLocation> deferredTypeEntities)
=> DeferredTypeLocations = deferredTypeEntities;
protected override void ComputeHashCodeParts(ref RoslynHashCode hashCode)
=> hashCode.Add(HashUtilities.Combine(DeferredTypeLocations));
protected override bool ComputeEqualsByHashCodeParts(CacheBasedEquatable<DeferredTypeEntitySet> obj)
{
var other = (DeferredTypeEntitySet)obj;
return HashUtilities.Combine(other.DeferredTypeLocations) == HashUtilities.Combine(DeferredTypeLocations);
}
}
}
| 44.931034 | 145 | 0.760553 | [
"Apache-2.0"
] | komsa-ag/roslyn-analyzers | src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidMultipleEnumerations/FlowAnalysis/DeferredTypeEntitySet.cs | 1,305 | C# |
//-----------------------------------------------------------------------
// <copyright file="NSwagSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using NJsonSchema.Infrastructure;
using NSwag.Commands.CodeGeneration;
using NSwag.Commands.Generation;
namespace NSwag.Commands
{
/// <summary>The NSwagDocument base class.</summary>
/// <seealso cref="System.ComponentModel.INotifyPropertyChanged" />
public abstract class NSwagDocumentBase : INotifyPropertyChanged
{
private string _path;
private string _latestData;
private IOutputCommand _selectedSwaggerGenerator;
/// <summary>Initializes a new instance of the <see cref="NSwagDocumentBase"/> class.</summary>
protected NSwagDocumentBase()
{
SwaggerGenerators.FromDocumentCommand = new FromDocumentCommand();
SwaggerGenerators.JsonSchemaToOpenApiCommand = new JsonSchemaToOpenApiCommand();
SelectedSwaggerGenerator = SwaggerGenerators.FromDocumentCommand;
}
/// <summary>Converts a path to an absolute path.</summary>
/// <param name="pathToConvert">The path to convert.</param>
/// <returns>The absolute path.</returns>
protected abstract string ConvertToAbsolutePath(string pathToConvert);
/// <summary>Converts a path to an relative path.</summary>
/// <param name="pathToConvert">The path to convert.</param>
/// <returns>The relative path.</returns>
protected abstract string ConvertToRelativePath(string pathToConvert);
/// <summary>Executes the current document.</summary>
/// <returns>The result.</returns>
public abstract Task<OpenApiDocumentExecutionResult> ExecuteAsync();
/// <summary>Gets or sets the runtime where the document should be processed.</summary>
public Runtime Runtime { get; set; } = Runtime.NetCore21;
/// <summary>Gets or sets the default variables.</summary>
public string DefaultVariables { get; set; }
/// <summary>Gets or sets the selected swagger generator JSON.</summary>
[JsonProperty("DocumentGenerator")]
internal JObject SelectedSwaggerGeneratorRaw
{
get
{
var key = SelectedSwaggerGenerator.GetType().Name
.Replace("CommandBase", string.Empty)
.Replace("Command", string.Empty);
return JObject.FromObject(new Dictionary<string, IOutputCommand>
{
{
key[0].ToString().ToLowerInvariant() + key.Substring(1),
SelectedSwaggerGenerator
}
}, JsonSerializer.Create(GetSerializerSettings()));
}
set
{
var generatorProperty = value.Properties().First();
var key = generatorProperty.Name + "Command";
var collectionProperty = SwaggerGenerators.GetType().GetRuntimeProperty(key[0].ToString().ToUpperInvariant() + key.Substring(1));
var generator = collectionProperty.GetValue(SwaggerGenerators);
var newGenerator = (IOutputCommand)JsonConvert.DeserializeObject(generatorProperty.Value.ToString(), generator.GetType(), GetSerializerSettings());
collectionProperty.SetValue(SwaggerGenerators, newGenerator);
SelectedSwaggerGenerator = newGenerator;
}
}
/// <summary>Gets the swagger generators.</summary>
[JsonIgnore]
public OpenApiGeneratorCollection SwaggerGenerators { get; } = new OpenApiGeneratorCollection();
/// <summary>Gets the code generators.</summary>
[JsonProperty("CodeGenerators")]
public CodeGeneratorCollection CodeGenerators { get; } = new CodeGeneratorCollection();
/// <summary>Gets or sets the path.</summary>
[JsonIgnore]
public string Path
{
get { return _path; }
set
{
_path = value;
OnPropertyChanged();
OnPropertyChanged(nameof(Name));
}
}
/// <summary>Gets the name of the document.</summary>
[JsonIgnore]
public string Name
{
get
{
var name = System.IO.Path.GetFileName(Path);
if (!name.Equals("nswag.json", StringComparison.OrdinalIgnoreCase))
{
return name;
}
var segments = Path.Replace("\\", "/").Split('/');
return segments.Length >= 2 ? string.Join("/", segments.Skip(segments.Length - 2)) : name;
}
}
/// <summary>Gets a value indicating whether the document is dirty (has any changes).</summary>
[JsonIgnore]
public bool IsDirty => _latestData != JsonConvert.SerializeObject(this, Formatting.Indented, GetSerializerSettings());
/// <summary>Gets the selected Swagger generator.</summary>
[JsonIgnore]
public IOutputCommand SelectedSwaggerGenerator
{
get { return _selectedSwaggerGenerator; }
set
{
_selectedSwaggerGenerator = value;
OnPropertyChanged();
}
}
/// <summary>Creates a new NSwagDocument.</summary>
/// <typeparam name="TDocument">The type.</typeparam>
/// <returns>The document.</returns>
protected static TDocument Create<TDocument>()
where TDocument : NSwagDocumentBase, new()
{
var document = new TDocument();
document.Path = "Untitled";
document._latestData = JsonConvert.SerializeObject(document, Formatting.Indented, GetSerializerSettings());
return document;
}
/// <summary>Loads an existing NSwagDocument.</summary>
/// <typeparam name="TDocument">The type.</typeparam>
/// <param name="filePath">The file path.</param>
/// <param name="variables">The variables.</param>
/// <param name="applyTransformations">Specifies whether to expand environment variables and convert variables.</param>
/// <param name="mappings">The mappings.</param>
/// <returns>The document.</returns>
protected static async Task<TDocument> LoadAsync<TDocument>(
string filePath,
string variables,
bool applyTransformations,
IDictionary<Type, Type> mappings)
where TDocument : NSwagDocumentBase, new()
{
var data = DynamicApis.FileReadAllText(filePath);
data = TransformLegacyDocument(data, out var requiredLegacyTransformations);
if (requiredLegacyTransformations)
{
// Save now to avoid transformations
var document = LoadDocument<TDocument>(filePath, mappings, data);
await document.SaveAsync();
}
if (applyTransformations)
{
data = Regex.Replace(data, "%[A-Za-z0-9_]*?%", p => EscapeJsonString(Environment.ExpandEnvironmentVariables(p.Value)));
foreach (var p in ConvertVariables(variables))
{
data = data.Replace("$(" + p.Key + ")", EscapeJsonString(p.Value));
}
var obj = JObject.Parse(data);
if (obj["defaultVariables"] != null)
{
var defaultVariables = obj["defaultVariables"].Value<string>();
foreach (var p in ConvertVariables(defaultVariables))
{
data = data.Replace("$(" + p.Key + ")", EscapeJsonString(p.Value));
}
}
}
return LoadDocument<TDocument>(filePath, mappings, data);
}
private static TDocument LoadDocument<TDocument>(string filePath, IDictionary<Type, Type> mappings, string data)
where TDocument : NSwagDocumentBase, new()
{
var settings = GetSerializerSettings();
settings.ContractResolver = new BaseTypeMappingContractResolver(mappings);
var document = FromJson<TDocument>(filePath, data);
return document;
}
/// <summary>Converts the document to JSON.</summary>
/// <typeparam name="TDocument">The document type.</typeparam>
/// <param name="filePath">The file path.</param>
/// <param name="data">The JSON data.</param>
/// <returns>The document.</returns>
public static TDocument FromJson<TDocument>(string filePath, string data)
where TDocument : NSwagDocumentBase, new()
{
var settings = GetSerializerSettings();
var document = JsonConvert.DeserializeObject<TDocument>(data, settings);
if (filePath != null)
{
document.Path = filePath;
document.ConvertToAbsolutePaths();
}
document._latestData = JsonConvert.SerializeObject(document, Formatting.Indented, GetSerializerSettings());
return document;
}
/// <summary>Saves the document.</summary>
/// <returns>The task.</returns>
public Task SaveAsync()
{
DynamicApis.FileWriteAllText(Path, ToJsonWithRelativePaths());
_latestData = JsonConvert.SerializeObject(this, Formatting.Indented, GetSerializerSettings());
return Task.CompletedTask;
}
/// <summary>Converts the document to JSON with relative paths.</summary>
/// <returns>The JSON data.</returns>
public string ToJsonWithRelativePaths()
{
ConvertToRelativePaths();
try
{
return ToJson();
}
finally
{
ConvertToAbsolutePaths();
}
}
/// <summary>Converts the document to JSON.</summary>
/// <returns>The JSON data.</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented, GetSerializerSettings());
}
/// <summary>Generates the <see cref="OpenApiDocument"/> with the currently selected generator.</summary>
/// <returns>The document.</returns>
protected async Task<OpenApiDocument> GenerateSwaggerDocumentAsync()
{
return (OpenApiDocument) await SelectedSwaggerGenerator.RunAsync(null, null);
}
private static string EscapeJsonString(string value)
{
if (!string.IsNullOrEmpty(value))
{
value = JsonConvert.ToString(value);
return value.Substring(1, value.Length - 2);
}
return string.Empty;
}
private static Dictionary<string, string> ConvertVariables(string variables)
{
try
{
return (variables ?? "")
.Split(',').Where(p => !string.IsNullOrEmpty(p))
.ToDictionary(p => p.Split('=')[0], p => p.Split('=')[1]);
}
catch (Exception exception)
{
throw new InvalidOperationException("Could not parse variables, ensure that they are " +
"in the form 'key1=value1,key2=value2', variables: " + variables, exception);
}
}
private static JsonSerializerSettings GetSerializerSettings()
{
return new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Include,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
{
new StringEnumConverter()
}
};
}
private void ConvertToAbsolutePaths()
{
if (SwaggerGenerators.FromDocumentCommand != null)
{
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://"))
{
SwaggerGenerators.FromDocumentCommand.Url = ConvertToAbsolutePath(SwaggerGenerators.FromDocumentCommand.Url);
}
}
if (SwaggerGenerators.WebApiToOpenApiCommand != null)
{
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyPaths.Select(ConvertToAbsolutePath).ToArray();
SwaggerGenerators.WebApiToOpenApiCommand.ReferencePaths =
SwaggerGenerators.WebApiToOpenApiCommand.ReferencePaths.Select(ConvertToAbsolutePath).ToArray();
SwaggerGenerators.WebApiToOpenApiCommand.DocumentTemplate = ConvertToAbsolutePath(
SwaggerGenerators.WebApiToOpenApiCommand.DocumentTemplate);
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyConfig = ConvertToAbsolutePath(
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyConfig);
}
if (SwaggerGenerators.AspNetCoreToOpenApiCommand != null)
{
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyPaths.Select(ConvertToAbsolutePath).ToArray();
SwaggerGenerators.AspNetCoreToOpenApiCommand.ReferencePaths =
SwaggerGenerators.AspNetCoreToOpenApiCommand.ReferencePaths.Select(ConvertToAbsolutePath).ToArray();
SwaggerGenerators.AspNetCoreToOpenApiCommand.DocumentTemplate = ConvertToAbsolutePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.DocumentTemplate);
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyConfig = ConvertToAbsolutePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyConfig);
SwaggerGenerators.AspNetCoreToOpenApiCommand.Project = ConvertToAbsolutePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.Project);
SwaggerGenerators.AspNetCoreToOpenApiCommand.MSBuildProjectExtensionsPath = ConvertToAbsolutePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.MSBuildProjectExtensionsPath);
SwaggerGenerators.AspNetCoreToOpenApiCommand.WorkingDirectory = ConvertToAbsolutePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.WorkingDirectory);
}
if (SwaggerGenerators.TypesToOpenApiCommand != null)
{
SwaggerGenerators.TypesToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.TypesToOpenApiCommand.AssemblyPaths.Select(ConvertToAbsolutePath).ToArray();
SwaggerGenerators.TypesToOpenApiCommand.AssemblyConfig = ConvertToAbsolutePath(
SwaggerGenerators.TypesToOpenApiCommand.AssemblyConfig);
}
if (CodeGenerators.OpenApiToTypeScriptClientCommand != null)
{
CodeGenerators.OpenApiToTypeScriptClientCommand.ExtensionCode = ConvertToAbsolutePath(
CodeGenerators.OpenApiToTypeScriptClientCommand.ExtensionCode);
CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory = ConvertToAbsolutePath(
CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory);
if (CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory != null && !Directory.Exists(CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory))
{
throw new InvalidOperationException($"The template directory \"{CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory}\" does not exist");
}
}
if (CodeGenerators.OpenApiToCSharpClientCommand != null)
{
CodeGenerators.OpenApiToCSharpClientCommand.ContractsOutputFilePath = ConvertToAbsolutePath(
CodeGenerators.OpenApiToCSharpClientCommand.ContractsOutputFilePath);
CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory = ConvertToAbsolutePath(
CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory);
if (CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory != null && !Directory.Exists(CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory))
{
throw new InvalidOperationException($"The template directory \"{CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory}\" does not exist");
}
}
if (CodeGenerators.OpenApiToCSharpControllerCommand != null)
{
CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory = ConvertToAbsolutePath(
CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory);
if (CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory != null && !Directory.Exists(CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory))
{
throw new InvalidOperationException($"The template directory {CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory}\" does not exist");
}
}
foreach (var generator in CodeGenerators.Items.Concat(SwaggerGenerators.Items))
{
generator.OutputFilePath = ConvertToAbsolutePath(generator.OutputFilePath);
}
}
private void ConvertToRelativePaths()
{
if (SwaggerGenerators.FromDocumentCommand != null)
{
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://"))
{
SwaggerGenerators.FromDocumentCommand.Url = ConvertToRelativePath(SwaggerGenerators.FromDocumentCommand.Url);
}
}
if (SwaggerGenerators.WebApiToOpenApiCommand != null)
{
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyPaths.Select(ConvertToRelativePath).ToArray();
SwaggerGenerators.WebApiToOpenApiCommand.ReferencePaths =
SwaggerGenerators.WebApiToOpenApiCommand.ReferencePaths.Select(ConvertToRelativePath).ToArray();
SwaggerGenerators.WebApiToOpenApiCommand.DocumentTemplate = ConvertToRelativePath(
SwaggerGenerators.WebApiToOpenApiCommand.DocumentTemplate);
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyConfig = ConvertToRelativePath(
SwaggerGenerators.WebApiToOpenApiCommand.AssemblyConfig);
}
if (SwaggerGenerators.AspNetCoreToOpenApiCommand != null)
{
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyPaths.Select(ConvertToRelativePath).ToArray();
SwaggerGenerators.AspNetCoreToOpenApiCommand.ReferencePaths =
SwaggerGenerators.AspNetCoreToOpenApiCommand.ReferencePaths.Select(ConvertToRelativePath).ToArray();
SwaggerGenerators.AspNetCoreToOpenApiCommand.DocumentTemplate = ConvertToRelativePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.DocumentTemplate);
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyConfig = ConvertToRelativePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.AssemblyConfig);
SwaggerGenerators.AspNetCoreToOpenApiCommand.Project = ConvertToRelativePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.Project);
SwaggerGenerators.AspNetCoreToOpenApiCommand.MSBuildProjectExtensionsPath = ConvertToRelativePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.MSBuildProjectExtensionsPath);
SwaggerGenerators.AspNetCoreToOpenApiCommand.WorkingDirectory = ConvertToRelativePath(
SwaggerGenerators.AspNetCoreToOpenApiCommand.WorkingDirectory);
}
if (SwaggerGenerators.TypesToOpenApiCommand != null)
{
SwaggerGenerators.TypesToOpenApiCommand.AssemblyPaths =
SwaggerGenerators.TypesToOpenApiCommand.AssemblyPaths.Select(ConvertToRelativePath).ToArray();
SwaggerGenerators.TypesToOpenApiCommand.AssemblyConfig = ConvertToRelativePath(
SwaggerGenerators.TypesToOpenApiCommand.AssemblyConfig);
}
if (CodeGenerators.OpenApiToTypeScriptClientCommand != null)
{
CodeGenerators.OpenApiToTypeScriptClientCommand.ExtensionCode = ConvertToRelativePath(
CodeGenerators.OpenApiToTypeScriptClientCommand.ExtensionCode);
CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory = ConvertToRelativePath(
CodeGenerators.OpenApiToTypeScriptClientCommand.TemplateDirectory);
}
if (CodeGenerators.OpenApiToCSharpClientCommand != null)
{
CodeGenerators.OpenApiToCSharpClientCommand.ContractsOutputFilePath = ConvertToRelativePath(
CodeGenerators.OpenApiToCSharpClientCommand.ContractsOutputFilePath);
CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory = ConvertToRelativePath(
CodeGenerators.OpenApiToCSharpClientCommand.TemplateDirectory);
}
if (CodeGenerators.OpenApiToCSharpControllerCommand != null)
{
CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory = ConvertToRelativePath(
CodeGenerators.OpenApiToCSharpControllerCommand.TemplateDirectory);
}
foreach (var generator in CodeGenerators.Items.Where(i => i != null).Concat(SwaggerGenerators.Items))
{
generator.OutputFilePath = ConvertToRelativePath(generator.OutputFilePath);
}
}
/// <summary>Occurs when a property value changes.</summary>
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>Raises all properties changed.</summary>
public void RaiseAllPropertiesChanged()
{
OnPropertyChanged(null);
}
private static string TransformLegacyDocument(string data, out bool saveFile)
{
saveFile = false;
// Swagger to OpenApi rename
if (data.Contains("\"typeScriptVersion\":") && !data.ToLowerInvariant().Contains("ExceptionClass".ToLowerInvariant()))
{
data = data.Replace("\"typeScriptVersion\":", "\"exceptionClass\": \"SwaggerException\", \"typeScriptVersion\":");
saveFile = true;
}
if (data.Contains("\"swaggerGenerator\":"))
{
data = data.Replace("\"swaggerGenerator\":", "\"documentGenerator\":");
saveFile = true;
}
if (data.Contains("\"swaggerToTypeScriptClient\":"))
{
data = data.Replace("\"swaggerToTypeScriptClient\":", "\"openApiToTypeScriptClient\":");
saveFile = true;
}
if (data.Contains("\"swaggerToCSharpClient\":"))
{
data = data.Replace("\"swaggerToCSharpClient\":", "\"openApiToCSharpClient\":");
saveFile = true;
}
if (data.Contains("\"swaggerToCSharpController\":"))
{
data = data.Replace("\"swaggerToCSharpController\":", "\"openApiToCSharpController\":");
saveFile = true;
}
if (data.Contains("\"fromSwagger\":"))
{
data = data.Replace("\"fromSwagger\":", "\"fromDocument\":");
saveFile = true;
}
if (data.Contains("\"jsonSchemaToSwagger\":"))
{
data = data.Replace("\"jsonSchemaToSwagger\":", "\"jsonSchemaToOpenApi\":");
saveFile = true;
}
if (data.Contains("\"webApiToSwagger\":"))
{
data = data.Replace("\"webApiToSwagger\":", "\"webApiToOpenApi\":");
saveFile = true;
}
if (data.Contains("\"aspNetCoreToSwagger\":"))
{
data = data.Replace("\"aspNetCoreToSwagger\":", "\"aspNetCoreToOpenApi\":");
saveFile = true;
}
if (data.Contains("\"typesToSwagger\":"))
{
data = data.Replace("\"typesToSwagger\":", "\"typesToOpenApi\":");
saveFile = true;
}
// New file format
if (data.Contains("\"aspNetNamespace\": \"System.Web.Http\""))
{
data = data.Replace("\"aspNetNamespace\": \"System.Web.Http\"", "\"controllerTarget\": \"AspNet\"");
saveFile = true;
}
if (data.Contains("\"aspNetNamespace\": \"Microsoft.AspNetCore.Mvc\""))
{
data = data.Replace("\"aspNetNamespace\": \"Microsoft.AspNetCore.Mvc\"", "\"controllerTarget\": \"AspNetCore\"");
saveFile = true;
}
if (data.Contains("\"noBuild\":") && !data.ToLowerInvariant().Contains("UseDocumentProvider".ToLowerInvariant()))
{
data = data.Replace("\"noBuild\":", "\"useDocumentProvider\": false, \"noBuild\":");
saveFile = true;
}
if (data.Contains("\"noBuild\":") && !data.ToLowerInvariant().Contains("RequireParametersWithoutDefault".ToLowerInvariant()))
{
data = data.Replace("\"noBuild\":", "\"requireParametersWithoutDefault\": true, \"noBuild\":");
saveFile = true;
}
if (data.Contains("assemblyTypeToSwagger"))
{
data = data.Replace("assemblyTypeToSwagger", "typesToSwagger");
saveFile = true;
}
if (data.Contains("\"template\": \"Angular2\""))
{
data = data.Replace("\"template\": \"Angular2\"", "\"template\": \"Angular\"");
saveFile = true;
}
if (data.Contains("\"SelectedSwaggerGenerator\""))
{
var obj = JsonConvert.DeserializeObject<JObject>(data);
var selectedSwaggerGenerator = obj["SelectedSwaggerGenerator"].Value<int>();
if (selectedSwaggerGenerator == 0) // swagger url/data
{
obj["swaggerGenerator"] = new JObject
{
{
"fromSwagger", new JObject
{
{"url", obj["InputSwaggerUrl"]},
{"json", string.IsNullOrEmpty(obj["InputSwaggerUrl"].Value<string>()) ? obj["InputSwagger"] : null}
}
}
};
}
if (selectedSwaggerGenerator == 1) // web api
{
obj["swaggerGenerator"] = new JObject
{
{"webApiToSwagger", obj["WebApiToSwaggerCommand"]}
};
}
if (selectedSwaggerGenerator == 2) // json schema
{
obj["swaggerGenerator"] = new JObject
{
{
"jsonSchemaToSwagger", new JObject
{
{"schema", obj["InputJsonSchema"]},
}
}
};
}
if (selectedSwaggerGenerator == 3) // types
{
obj["swaggerGenerator"] = new JObject
{
{"assemblyTypeToSwagger", obj["AssemblyTypeToSwaggerCommand"]}
};
}
obj["codeGenerators"] = new JObject
{
{"swaggerToTypeScriptClient", obj["SwaggerToTypeScriptCommand"]},
{"swaggerToCSharpClient", obj["SwaggerToCSharpClientCommand"]},
{"swaggerToCSharpController", obj["SwaggerToCSharpControllerGenerator"]}
};
data = obj.ToString().Replace("\"OutputFilePath\"", "\"output\"");
saveFile = true;
}
// typeScriptVersion
if (data.Contains("generateReadOnlyKeywords") && !data.Contains("typeScriptVersion"))
{
data = data.Replace(@"""GenerateReadOnlyKeywords"": true", @"""typeScriptVersion"": 2.0");
data = data.Replace(@"""generateReadOnlyKeywords"": true", @"""typeScriptVersion"": 2.0");
data = data.Replace(@"""GenerateReadOnlyKeywords"": false", @"""typeScriptVersion"": 1.8");
data = data.Replace(@"""generateReadOnlyKeywords"": false", @"""typeScriptVersion"": 1.8");
saveFile = true;
}
// Full type names
if (data.Contains("\"dateType\": \"DateTime\""))
{
data = data.Replace("\"dateType\": \"DateTime\"", "\"dateType\": \"System.DateTime\"");
saveFile = true;
}
if (data.Contains("\"dateTimeType\": \"DateTime\""))
{
data = data.Replace("\"dateTimeType\": \"DateTime\"", "\"dateTimeType\": \"System.DateTime\"");
saveFile = true;
}
if (data.Contains("\"timeType\": \"TimeSpan\""))
{
data = data.Replace("\"timeType\": \"TimeSpan\"", "\"timeType\": \"System.TimeSpan\"");
saveFile = true;
}
if (data.Contains("\"timeSpanType\": \"TimeSpan\""))
{
data = data.Replace("\"timeSpanType\": \"TimeSpan\"", "\"timeSpanType\": \"System.TimeSpan\"");
saveFile = true;
}
if (data.Contains("\"arrayType\": \"ObservableCollection\""))
{
data = data.Replace("\"arrayType\": \"ObservableCollection\"", "\"arrayType\": \"System.Collections.ObjectModel.ObservableCollection\"");
saveFile = true;
}
if (data.Contains("\"dictionaryType\": \"Dictionary\""))
{
data = data.Replace("\"dictionaryType\": \"Dictionary\"", "\"dictionaryType\": \"System.Collections.Generic.Dictionary\"");
saveFile = true;
}
return data;
}
}
}
| 46.088112 | 183 | 0.573878 | [
"MIT"
] | FramingApp/NSwag | src/NSwag.Commands/NSwagDocumentBase.cs | 32,955 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Resources;
using Azure.Storage.Test;
namespace Azure.Storage.Blobs.Tests.ManagedDisk
{
/// <summary>
/// This fixture makes sure that managed disk snapshots are initialized and destroyed once per whole test suite.
///
/// Deleting snapshots at test class level was not viable as it led to race conditions related to access rights,
/// i.e. if one of the middle (or first) snapshots is deleted it seems that service revokes read access while it squashes data.
/// </summary>
public class ManagedDiskFixture : SetUpFixtureBase<BlobTestEnvironment>
{
public ManagedDiskFixture()
: base(/* RecordedTestMode.Live /* to hardocode the mode */)
{
}
public static ManagedDiskFixture Instance { get; private set; }
private ManagedDiskConfiguration _config;
private ResourceGroup _resourceGroup;
public Snapshot Snapshot1 { get; private set; }
public Snapshot Snapshot2 { get; private set; }
public Uri Snapshot1SASUri { get; private set; }
public Uri Snapshot2SASUri { get; private set; }
public override async Task SetUp()
{
if (Environment.Mode != RecordedTestMode.Playback)
{
_config = TestConfigurations.DefaultTargetManagedDisk;
TokenCredential tokenCredentials = new Identity.ClientSecretCredential(
_config.ActiveDirectoryTenantId, _config.ActiveDirectoryApplicationId, _config.ActiveDirectoryApplicationSecret);
ArmClient client = new ArmClient(tokenCredentials, _config.SubsriptionId);
Subscription subscription = await client.GetDefaultSubscriptionAsync();
_resourceGroup = await subscription.GetResourceGroups().GetAsync(_config.ResourceGroupName);
var disks = await _resourceGroup.GetDisks().GetAllAsync().ToListAsync();
var disk = disks.Where(d => d.Data.Name.Contains(_config.DiskNamePrefix)).First();
Snapshot1 = await CreateSnapshot(disk, _config.DiskNamePrefix + Guid.NewGuid().ToString().Replace("-", ""));
// The disk is attached to VM, wait some time to let OS background jobs write something to disk to create delta.
await Task.Delay(TimeSpan.FromSeconds(60));
Snapshot2 = await CreateSnapshot(disk, _config.DiskNamePrefix + Guid.NewGuid().ToString().Replace("-", ""));
Snapshot1SASUri = await GrantAccess(Snapshot1);
Snapshot2SASUri = await GrantAccess(Snapshot2);
}
Instance = this;
}
public override async Task TearDown()
{
if (Environment.Mode != RecordedTestMode.Playback)
{
await RevokeAccess(Snapshot1);
await RevokeAccess(Snapshot2);
await DeleteSnapshot(Snapshot1);
await DeleteSnapshot(Snapshot2);
}
}
private async Task<Snapshot> CreateSnapshot(Disk disk, string name)
{
var snapshotCreateOperation = await _resourceGroup.GetSnapshots().CreateOrUpdateAsync(WaitUntil.Completed, name,
new SnapshotData(_config.Location)
{
CreationData = new CreationData(DiskCreateOption.Copy)
{
SourceResourceId = disk.Id
},
Incremental = true,
});
return await snapshotCreateOperation.WaitForCompletionAsync();
}
private async Task DeleteSnapshot(Snapshot snapshot)
{
var snapshotDeleteOperation = await snapshot.DeleteAsync(WaitUntil.Completed);
await snapshotDeleteOperation.WaitForCompletionResponseAsync();
}
private async Task<Uri> GrantAccess(Snapshot snapshot)
{
var grantOperation = await snapshot.GrantAccessAsync(WaitUntil.Completed,
new GrantAccessData(AccessLevel.Read, 3600));
AccessUri accessUri = await grantOperation.WaitForCompletionAsync();
return new Uri(accessUri.AccessSAS);
}
private async Task RevokeAccess(Snapshot snapshot)
{
var revokeOperation = await snapshot.RevokeAccessAsync(WaitUntil.Completed);
await revokeOperation.WaitForCompletionResponseAsync();
}
}
}
| 41.267241 | 133 | 0.647587 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/storage/Azure.Storage.Blobs/tests/ManagedDiskFixture.cs | 4,789 | C# |
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using FamilyManagerWeb.Models;
namespace FamilyManagerWeb.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
}
| 39.45098 | 207 | 0.618787 | [
"MIT"
] | lyc-chengzi/fmServer | FamilyManagerWeb/Filters/InitializeSimpleMembershipAttribute.cs | 2,014 | C# |
using System.Collections.Generic;
using System.Collections;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using System.IO;
using System;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;
public class Tool_QuickStart : EditorWindow
{
//Version
string _Version = "V1.0.12";
//Navigation Tool
int _MenuID = 0; // QuickStart/Scripts/QuickUI
int _DimensionID = 0; // 2D/3D
int _Type2DID = 0; // Platformer/TopDown/VisualNovel
int _Type3DID = 0; // FPS/ThirdPerson/TopDown/Platformer
bool _SelectWindow = false;
//Navigation Tool Windows
int _WindowID = 0; // Default/UpdateLog/FileFinder/ScriptToString/MapEditor
string[] _WindowNames = new string[] {"Home","Update Log","FileFinder","ScriptToString","MapEditor" };
//Scripts
Tool_QuickStart_Script[] QuickStart_Scripts = new Tool_QuickStart_Script[] {
// NAME TAGS STATE CODE
new Tool_QuickStart_Script("AudioHandler", "Audio_Handler", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine.SceneManagement;\nusing UnityEngine;\nusing UnityEngine.Audio;\n\npublic class AudioHandler : MonoBehaviour\n{\n [Header(\"Settings\")]\n [Tooltip(\"Only used for testing disable it for the final build to improve performance\")]\n [SerializeField] private bool _RefreshSettingsOnUpdate = false;\n\n [Header(\"AudioMixer/Audio\")]\n [SerializeField] private AudioMixerGroup _AudioMixer = null;\n [SerializeField] private List<AudioHandler_Sound> _Sound = new List<AudioHandler_Sound>();\n\n private string _CurrentScene;\n\n //You can call AudioHandler.AUDIO from every script as long as you have the script in the scene.\n public static AudioHandler AUDIO;\n\n void Awake()\n {\n AUDIO = this;\n\n //PlayOnStart\n for (int i = 0; i < _Sound.Count; i++)\n {\n //AudioSource\n if (_Sound[i].Settings.CreateAudioSource)\n {\n _Sound[i].Settings.AudioSource = this.gameObject.AddComponent<AudioSource>();\n _Sound[i].Settings.AudioSource.outputAudioMixerGroup = _AudioMixer;\n\n //AudioGroup\n if (_Sound[i].Settings.AudioGroup != null)\n _Sound[i].Settings.AudioSource.outputAudioMixerGroup = _Sound[i].Settings.AudioGroup;\n }\n\n //AudioClip\n _Sound[i].Settings.AudioSource.clip = _Sound[i].Settings.AudioClip;\n\n //Settings\n if (_Sound[i].AudioSettings.PlayOnStart)\n {\n _Sound[i].Settings.AudioSource.playOnAwake = _Sound[i].AudioSettings.PlayOnStart;\n _Sound[i].Settings.AudioSource.Play();\n }\n if (_Sound[i].AudioEffects.FadeIn)\n {\n _Sound[i].Settings.AudioSource.volume = 1;\n _Sound[i].AudioEffects.FadeInSpeed = _Sound[i].AudioSettings.Volume / _Sound[i].AudioEffects.FadeInDuration;\n }\n if (_Sound[i].AudioEffects.FadeOut)\n {\n _Sound[i].AudioEffects.FadeOutSpeed = _Sound[i].AudioSettings.Volume / _Sound[i].AudioEffects.FadeOutDuration;\n }\n }\n\n RefreshSettings();\n }\n\n void Update()\n {\n CheckNewScene();\n\n if (_RefreshSettingsOnUpdate)\n RefreshSettings();\n\n for (int i = 0; i < _Sound.Count; i++)\n {\n if(!_Sound[i].AudioEffects.FadingIn && !_Sound[i].AudioEffects.FadingOut)\n {\n _Sound[i].Settings.AudioSource.volume = _Sound[i].AudioSettings.Volume;\n continue;\n }\n\n //FadeIn\n if (_Sound[i].AudioEffects.FadingIn)\n {\n if (_Sound[i].AudioEffects.FadeIn && !_Sound[i].AudioEffects.FadeInDone)\n {\n if (_Sound[i].Settings.AudioSource.volume < _Sound[i].AudioSettings.Volume)\n {\n _Sound[i].Settings.AudioSource.volume += _Sound[i].AudioEffects.FadeInSpeed * Time.deltaTime;\n }\n else\n {\n _Sound[i].AudioEffects.FadeInDone = true;\n _Sound[i].Settings.AudioSource.volume = _Sound[i].AudioSettings.Volume;\n }\n }\n }\n //FadeOut\n if (_Sound[i].AudioEffects.FadingOut)\n {\n if (_Sound[i].AudioEffects.FadeOutAfterTime > -0.1f)\n {\n _Sound[i].AudioEffects.FadeOutAfterTime -= 1 * Time.deltaTime;\n }\n else\n {\n if (_Sound[i].AudioEffects.FadeOut && !_Sound[i].AudioEffects.FadeOutDone)\n {\n if (_Sound[i].Settings.AudioSource.volume > 0)\n {\n _Sound[i].Settings.AudioSource.volume -= _Sound[i].AudioEffects.FadeOutSpeed * Time.deltaTime;\n }\n else\n {\n _Sound[i].AudioEffects.FadeOutDone = true;\n _Sound[i].Settings.AudioSource.volume = 0;\n _Sound[i].Settings.AudioSource.Stop();\n }\n }\n }\n }\n }\n }\n\n private void CheckNewScene()\n {\n if (_CurrentScene != SceneManager.GetActiveScene().name)\n {\n _CurrentScene = SceneManager.GetActiveScene().name;\n for (int i = 0; i < _Sound.Count; i++)\n {\n for (int o = 0; o < _Sound[i].AudioControl.StartAudioOnScene.Count; o++)\n {\n if (_Sound[i].AudioControl.StartAudioOnScene[o] == _CurrentScene)\n {\n //FadeIn\n if (_Sound[i].AudioEffects.FadeIn)\n {\n _Sound[i].AudioEffects.FadingOut = false;\n _Sound[i].AudioEffects.FadeInDone = false;\n _Sound[i].AudioEffects.FadingIn = true;\n }\n _Sound[i].Settings.AudioSource.Play();\n }\n }\n for (int o = 0; o < _Sound[i].AudioControl.StopAudioOnScene.Count; o++)\n {\n if (_Sound[i].AudioControl.StopAudioOnScene[o] == _CurrentScene)\n {\n //FadeOut\n if (_Sound[i].AudioEffects.FadeOut && !_Sound[i].AudioEffects.FadingOut)\n {\n _Sound[i].AudioEffects.FadingIn = false;\n _Sound[i].AudioEffects.FadeOutDone = false;\n _Sound[i].AudioEffects.FadingOut = true;\n }\n else\n _Sound[i].Settings.AudioSource.Stop();\n }\n }\n }\n }\n }\n private void AudioHandler_PlayTrack(int trackid)\n {\n _Sound[trackid].Settings.AudioSource.Play();\n }\n\n /// <summary>Plays the audiotrack.</summary>\n public void PlayTrack(string trackname)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n AudioHandler_PlayTrack(i);\n }\n }\n public void PlayTrack(int trackid)\n {\n AudioHandler_PlayTrack(trackid);\n }\n\n /// <summary>Plays the audiotrack if it's not playing yet.</summary>\n public void StartTrack(string trackname)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n if (!_Sound[i].Settings.AudioSource.isPlaying)\n AudioHandler_PlayTrack(i);\n }\n }\n public void StartTrack(int trackid)\n {\n if (!_Sound[trackid].Settings.AudioSource.isPlaying)\n AudioHandler_PlayTrack(trackid);\n }\n\n /// <summary>Stops the audiotrack.</summary>\n public void StopTrack(string trackname)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n _Sound[i].Settings.AudioSource.Stop();\n }\n }\n public void StopTrack(int trackid)\n {\n _Sound[trackid].Settings.AudioSource.Stop();\n }\n\n /// <summary>Returns audio file name.</summary>\n public string Get_Track_AudioFileName(string trackname)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n return _Sound[i].Settings.AudioClip.name;\n }\n return \"No AudioClip detected\";\n }\n public string Get_Track_AudioFileName(int trackid)\n {\n return _Sound[trackid].Settings.AudioClip.name;\n }\n\n /// <summary>Set audiosource.</summary>\n public void SetAudioSource(string trackname, AudioSource audiosource)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n _Sound[i].Settings.AudioSource = audiosource;\n }\n }\n public void SetAudioSource(int trackid, AudioSource audiosource)\n {\n _Sound[trackid].Settings.AudioSource = audiosource;\n }\n\n /// <summary>Set track volume.</summary>\n public void SetTrackVolume(string trackname, float volume, bool checkmaxvolume)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n {\n if (!checkmaxvolume)\n _Sound[i].AudioSettings.Volume = volume;\n else\n if (volume >= _Sound[i].AudioSettings.MaxVolume)\n _Sound[i].AudioSettings.Volume = _Sound[i].AudioSettings.MaxVolume;\n else\n _Sound[i].AudioSettings.Volume = volume;\n break;\n }\n }\n }\n public void SetTrackVolume(int trackid, float volume, bool checkmaxvolume)\n {\n if (!checkmaxvolume)\n _Sound[trackid].AudioSettings.Volume = volume;\n else if (volume >= _Sound[trackid].AudioSettings.MaxVolume)\n _Sound[trackid].AudioSettings.Volume = _Sound[trackid].AudioSettings.MaxVolume;\n else\n _Sound[trackid].AudioSettings.Volume = volume;\n }\n\n /// <summary>Returns track id.</summary>\n public int Get_Track_ID(string trackname)\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n if (_Sound[i].AudioTrackName == trackname)\n return i;\n }\n return 0;\n }\n\n /// <summary>Refresh settings.</summary>\n public void RefreshSettings()\n {\n for (int i = 0; i < _Sound.Count; i++)\n {\n //SetClip\n if (_Sound[i].Settings.AudioSource.clip != _Sound[i].Settings.AudioClip)\n _Sound[i].Settings.AudioSource.clip = _Sound[i].Settings.AudioClip;\n //SetEffects\n if (!_Sound[i].AudioEffects.FadeIn || _Sound[i].AudioEffects.FadeIn && _Sound[i].AudioEffects.FadeInDone)\n _Sound[i].Settings.AudioSource.volume = _Sound[i].AudioSettings.Volume;\n _Sound[i].Settings.AudioSource.loop = _Sound[i].AudioSettings.Loop;\n }\n }\n\n\n}\n\n[System.Serializable]\npublic class AudioHandler_Sound\n{\n public string AudioTrackName;\n public AudioHandler_Settings Settings;\n public AudioHandler_AudioSettings AudioSettings;\n public AudioHandler_Control AudioControl;\n public AudioHandler_Effects AudioEffects;\n}\n\n[System.Serializable]\npublic class AudioHandler_Settings\n{\n [Header(\"AudioClip/AudioMixerGroup\")]\n public AudioClip AudioClip;\n public AudioMixerGroup AudioGroup;\n\n [Header(\"AudioSource\")]\n public AudioSource AudioSource;\n public bool CreateAudioSource;\n}\n\n[System.Serializable]\npublic class AudioHandler_AudioSettings\n{\n [Header(\"AudioSettings\")]\n [Range(0, 1)] public float Volume;\n [Range(0, 1)] public float MaxVolume;\n public bool Loop;\n public bool PlayOnStart;\n}\n\n[System.Serializable]\npublic class AudioHandler_Control\n{\n [Header(\"Enable/Disable Song\")]\n public List<string> StartAudioOnScene = new List<string>();\n public List<string> StopAudioOnScene = new List<string>();\n public bool StopOnNextScene;\n [HideInInspector] public int SceneEnabled;\n}\n\n[System.Serializable]\npublic class AudioHandler_Effects\n{\n [Header(\"FadeIn\")]\n public bool FadeIn;\n public float FadeInDuration;\n [HideInInspector] public float FadeInSpeed;\n [HideInInspector] public bool FadeInDone;\n [HideInInspector] public bool FadingIn;\n [Header(\"FadeOut\")]\n public bool FadeOut;\n public float FadeOutAfterTime;\n public float FadeOutDuration;\n [HideInInspector] public float FadeOutSpeed;\n [HideInInspector] public bool FadeOutDone;\n [HideInInspector] public bool FadingOut;\n}\n"),
new Tool_QuickStart_Script("AudioZoneBox", "Audio_Zone_Handler", "stable", "using UnityEngine;\nusing UnityEditor;\nusing UnityEditor.IMGUI.Controls;\n\npublic class AudioZoneBox : MonoBehaviour\n{\n private enum Options { SetVolume, VolumeOnDistance };\n [Header(\"Type\")]\n [SerializeField] private Options _Option = Options.SetVolume;\n\n [Header(\"Target\")]\n [SerializeField] private Transform _ZoneEffector = null;\n\n [Header(\"Settings - Zone\")]\n [SerializeField] private string _AudioTrack = \"\";\n [SerializeField] private float _Volume = 1;\n\n [Tooltip(\"1 = volume from 0 to max based on how close the effector is to the center.\")]\n [SerializeField] private float _IncreaseMultiplier = 1;\n\n // Check effector leaving bounds\n private bool _EffectorInBounds;\n\n //Bounds\n public Bounds Bounds { get { return _Bounds; } set { _Bounds = value; } }\n [SerializeField] private Bounds _Bounds = new Bounds(Vector3.zero, new Vector3(5,5,5));\n\n // Optimization (This way the AudioHandler doesn't have too loop trough the available audiotracks)\n private int _AudioTrackID;\n\n // AudioHandler Ref\n private AudioHandler AudioHandler;\n\n // Max distance\n private float _MaxDistance;\n\n void Start()\n {\n AudioHandler = AudioHandler.AUDIO;\n\n if (_ZoneEffector == null)\n {\n try { _ZoneEffector = GameObject.Find(\"Player\").transform; }\n catch { Debug.Log(\"No Effector Assigned!\"); }\n }\n \n // Get TrackID\n _AudioTrackID = AudioHandler.AUDIO.Get_Track_ID(_AudioTrack);\n\n // Set max distance\n _MaxDistance = Vector3.Distance(Vector3.zero, _Bounds.size) *.25f;\n }\n\n void Update()\n {\n if (Bounds.Contains(_ZoneEffector.position))\n {\n switch(_Option)\n {\n case Options.SetVolume:\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, _Volume, true);\n break;\n case Options.VolumeOnDistance:\n float distance = Vector3.Distance(_Bounds.center, _ZoneEffector.position);\n float newvolume = (1 - (distance / _MaxDistance)) * _Volume * _IncreaseMultiplier;\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, newvolume, true);\n break;\n }\n\n // Check Effector OnExit\n if (!_EffectorInBounds)\n _EffectorInBounds = true;\n }\n else\n {\n // Effector OnExit\n if (_EffectorInBounds)\n {\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, 0, true);\n _EffectorInBounds = false;\n }\n }\n }\n\n private void OnDrawGizmos()\n {\n Gizmos.color = new Vector4(0, 1f, 0, 0.1f);\n Gizmos.DrawCube(transform.position, Bounds.size);\n }\n}\n\n//Editor Bounds\n[CustomEditor(typeof(AudioZoneBox)), CanEditMultipleObjects]\npublic class AudioZoneBoxEditor : Editor\n{\n private BoxBoundsHandle _BoundsHandle = new BoxBoundsHandle();\n\n protected virtual void OnSceneGUI()\n {\n AudioZoneBox audiozonebox = (AudioZoneBox)target;\n\n _BoundsHandle.center = audiozonebox.transform.position;\n _BoundsHandle.size = audiozonebox.Bounds.size;\n\n EditorGUI.BeginChangeCheck();\n _BoundsHandle.DrawHandle();\n if (EditorGUI.EndChangeCheck())\n {\n Undo.RecordObject(audiozonebox, \"Change Bounds\");\n\n Bounds newBounds = new Bounds();\n newBounds.center = audiozonebox.transform.position;\n newBounds.size = _BoundsHandle.size;\n audiozonebox.Bounds = newBounds;\n }\n }\n}\n"),
new Tool_QuickStart_Script("AudioZoneSphere", "Audio_Zone_Handler", "stable", "using UnityEngine;\nusing UnityEditor;\nusing UnityEditor.IMGUI.Controls;\n\npublic class AudioZoneSphere : MonoBehaviour\n{\n private enum Options { SetVolume, VolumeOnDistance };\n [Header(\"Type\")]\n [SerializeField] private Options _Option = Options.SetVolume;\n\n [Header(\"Target\")]\n [SerializeField] private Transform _ZoneEffector = null;\n\n [Header(\"Settings - Zone\")]\n [SerializeField] private string _AudioTrack = \"\";\n [SerializeField] private float _Volume = 1;\n [Tooltip(\"1 = volume from 0 to max based on how close the effector is to the center.\")]\n [SerializeField] private float _IncreaseMultiplier = 1;\n\n // Check effector leaving bounds\n private bool _EffectorInBounds;\n\n //Bounds\n public float BoundsRadius;\n public BoundingSphere Bounds { get { return _Bounds; } set { _Bounds = value; } }\n [SerializeField] private BoundingSphere _Bounds = new BoundingSphere(Vector3.zero, 5);\n\n // Optimization (This way the AudioHandler doesn't have too loop trough the available audiotracks)\n private int _AudioTrackID;\n\n // AudioHandler Ref\n private AudioHandler AudioHandler;\n\n // Max distance\n private float _MaxDistance;\n\n void Start()\n {\n _Bounds = new BoundingSphere(transform.position, BoundsRadius);\n\n AudioHandler = AudioHandler.AUDIO;\n\n if (_ZoneEffector == null)\n {\n try { _ZoneEffector = GameObject.Find(\"Player\").transform; }\n catch { Debug.Log(\"No Effector Assigned!\"); }\n }\n \n // Get TrackID\n _AudioTrackID = AudioHandler.AUDIO.Get_Track_ID(_AudioTrack);\n\n // Set max distance\n _MaxDistance = Bounds.radius;\n }\n\n void Update()\n {\n if (Vector3.Distance(transform.position,_ZoneEffector.position) <= _MaxDistance)\n {\n switch (_Option)\n {\n case Options.SetVolume:\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, _Volume, true);\n break;\n case Options.VolumeOnDistance:\n float distance = Vector3.Distance(Bounds.position, _ZoneEffector.position);\n float newvolume = (1 - (distance / _MaxDistance)) * _Volume * _IncreaseMultiplier;\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, newvolume, true);\n break;\n }\n\n // Check Effector OnExit\n if (!_EffectorInBounds)\n _EffectorInBounds = true;\n }\n else\n {\n // Effector OnExit\n if (_EffectorInBounds)\n {\n AudioHandler.AUDIO.SetTrackVolume(_AudioTrackID, 0, true);\n _EffectorInBounds = false;\n }\n }\n }\n\n private void OnDrawGizmos()\n {\n Gizmos.color = new Vector4(0, 1f, 0, 0.1f);\n Gizmos.DrawSphere(transform.position, Bounds.radius);\n }\n}\n\n//Editor Bounds\n[CustomEditor(typeof(AudioZoneSphere)), CanEditMultipleObjects]\npublic class AudioZoneSphereEditor : Editor\n{\n private SphereBoundsHandle _BoundsHandle = new SphereBoundsHandle();\n\n protected virtual void OnSceneGUI()\n {\n AudioZoneSphere audiozonesphere = (AudioZoneSphere)target;\n\n _BoundsHandle.center = audiozonesphere.transform.position;\n _BoundsHandle.radius = audiozonesphere.Bounds.radius;\n\n EditorGUI.BeginChangeCheck();\n _BoundsHandle.DrawHandle();\n if (EditorGUI.EndChangeCheck())\n {\n Undo.RecordObject(audiozonesphere, \"Change Bounds\");\n\n BoundingSphere newBounds = new BoundingSphere();\n newBounds.position = audiozonesphere.transform.position;\n newBounds.radius = _BoundsHandle.radius;\n audiozonesphere.Bounds = newBounds;\n\n audiozonesphere.BoundsRadius = _BoundsHandle.radius;\n audiozonesphere.Bounds = new BoundingSphere(Vector3.zero, audiozonesphere.BoundsRadius);\n }\n \n }\n}\n"),
new Tool_QuickStart_Script("BasicNavMeshAI", "AI_NavMesh", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.AI;\n\npublic class BasicNavMeshAI : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private Transform _Target = null;\n [SerializeField] private float _Speed = 2;\n\n private NavMeshAgent _Agent;\n\n private void Awake()\n {\n if (_Target == null)\n {\n try\n {\n _Target = GameObject.Find(\"Player\").transform;\n }\n catch\n {\n Debug.Log(\"No Target\");\n }\n }\n\n _Agent = GetComponent<NavMeshAgent>();\n _Agent.speed = _Speed;\n }\n\n private void Update()\n {\n if (_Target != null)\n {\n _Agent.SetDestination(_Target.position);\n }\n }\n}\n"),
new Tool_QuickStart_Script("Bullet", "Shooting_Bullet", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ExampleGame_TopDownShooter_Bullet : MonoBehaviour\n{\n [SerializeField] private float _Speed;\n [SerializeField] private float _Damage;\n\n [SerializeField] private GameObject _BulletObj;\n [SerializeField] private Disable _DisableScript;\n [SerializeField] private ParticleSystem _Particle;\n\n void FixedUpdate()\n {\n if (_BulletObj.activeSelf)\n transform.Translate(Vector3.forward * _Speed * Time.deltaTime);\n }\n\n void OnEnable()\n {\n _BulletObj.SetActive(true);\n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (_BulletObj.activeSelf)\n {\n if (other.tag == \"Wall\")\n {\n _Particle.Play();\n _DisableScript.DisableObject(5);\n _BulletObj.gameObject.SetActive(false);\n }\n if (other.tag == \"Enemy\")\n {\n _Particle.Play();\n other.gameObject.GetComponent<ExampleGame_TopDownShooter_Enemy>().DoDamage(_Damage);\n _DisableScript.DisableObject(5);\n _BulletObj.gameObject.SetActive(false);\n }\n }\n }\n}\n"),
new Tool_QuickStart_Script("CarArcade", "Car_Drive_Vehicle", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class CarArcade : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _ForwardAccel = 8;\n [SerializeField] private float _ReverseAccel = 4;\n [SerializeField] private float _TurnStrength = 180;\n [SerializeField] private float _GravityForce = 15;\n\n [Header(\"GroundCheck\")]\n [SerializeField] private LayerMask _GroundMask = ~0;\n [SerializeField] private float _GroundCheckLength = 0.5f;\n\n [Header(\"RigidBody\")]\n [SerializeField] private Rigidbody _RB = null;\n\n private float _SpeedInput;\n private float _TurnInput;\n private bool _Grounded;\n\n void Start() => _RB.transform.parent = null;\n\n void Update()\n {\n _SpeedInput = 0;\n if(Input.GetAxis(\"Vertical\") > 0)\n _SpeedInput = Input.GetAxis(\"Vertical\") * _ForwardAccel * 1000;\n else if(Input.GetAxis(\"Vertical\") < 0)\n _SpeedInput = Input.GetAxis(\"Vertical\") * _ReverseAccel * 1000;\n\n _TurnInput = Input.GetAxis(\"Horizontal\");\n\n if(_Grounded)\n transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles + new Vector3(0, _TurnInput * _TurnStrength * Time.deltaTime, 0));\n\n transform.position = _RB.transform.position;\n }\n\n private void FixedUpdate()\n {\n _Grounded = GroundCheck();\n\n if (_Grounded)\n {\n if (Mathf.Abs(_SpeedInput) > 0)\n _RB.AddForce(transform.forward * _SpeedInput);\n }\n else\n _RB.AddForce(Vector3.up * -_GravityForce * 100);\n }\n\n private bool GroundCheck()\n {\n _Grounded = false;\n RaycastHit hit;\n\n if(Physics.Raycast(transform.position, -transform.up, out hit, _GroundCheckLength, _GroundMask))\n {\n _Grounded = true;\n transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;\n }\n\n return _Grounded;\n }\n}\n"),
new Tool_QuickStart_Script("CarRealistic", "Car_Drive_Vehicle", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class CarRealistic : MonoBehaviour\n{\n [Header(\"Motor\")]\n [SerializeField] private List<AxleInfo> axleInfos = null;\n [SerializeField] private float maxMotorTorque = 1000;\n\n [Header(\"Steering\")]\n [SerializeField] private float maxSteeringAngle = 50;\n\n public void FixedUpdate()\n {\n float motor = maxMotorTorque * Input.GetAxis(\"Vertical\");\n float steering = maxSteeringAngle * Input.GetAxis(\"Horizontal\");\n\n foreach (AxleInfo axleInfo in axleInfos)\n {\n if (axleInfo.steering)\n {\n axleInfo.leftWheel.steerAngle = steering;\n axleInfo.rightWheel.steerAngle = steering;\n }\n if (axleInfo.motor)\n {\n axleInfo.leftWheel.motorTorque = motor;\n axleInfo.rightWheel.motorTorque = motor;\n }\n }\n }\n\n}\n\n[System.Serializable]\npublic class AxleInfo\n{\n public WheelCollider leftWheel;\n public WheelCollider rightWheel;\n public bool motor;\n public bool steering;\n}\n"),
new Tool_QuickStart_Script("DebugCommandBase", "Debug_Console", "stable", "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DebugCommandBase\n{\n private string _CommandID;\n private string _CommandDescription;\n private string _CommandFormat;\n\n public string CommandID { get { return _CommandID; } }\n public string CommandDescription { get { return _CommandDescription; } }\n public string CommandFormat { get { return _CommandFormat; } }\n\n public DebugCommandBase(string id, string description, string format)\n {\n _CommandID = id;\n _CommandDescription = description;\n _CommandFormat = format;\n }\n}\n\npublic class DebugCommand : DebugCommandBase\n{\n private Action command;\n\n public DebugCommand(string id, string description, string format, Action command) : base (id, description, format)\n {\n this.command = command;\n }\n\n public void Invoke()\n {\n command.Invoke();\n }\n}\n\npublic class DebugCommand<T1> : DebugCommandBase\n{\n private Action<T1> command;\n\n public DebugCommand(string id, string description, string format, Action<T1> command) : base (id, description, format)\n {\n this.command = command;\n }\n\n public void Invoke(T1 value)\n {\n command.Invoke(value);\n }\n}\n"),
new Tool_QuickStart_Script("DebugConsole", "Debug_Console", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DebugConsole : MonoBehaviour\n{\n private bool _ShowConsole;\n private bool _ShowHelp;\n private string _Input;\n private Vector2 _Scroll;\n\n public static DebugCommand TEST;\n public static DebugCommand HELP;\n public static DebugCommand HIDEHELP;\n public static DebugCommand<float> SETVALUE;\n\n public List<object> commandList;\n\n private void Awake()\n {\n HELP = new DebugCommand(\"help\", \"Shows a list of commands\", \"help\", () =>\n {\n _ShowHelp = !_ShowHelp;\n });\n\n HIDEHELP = new DebugCommand(\"hidehelp\", \"hide help info\", \"hidehelp\", () =>\n {\n _ShowHelp = false;\n });\n\n TEST = new DebugCommand(\"test\", \"example command\", \"test\", () =>\n {\n Debug.Log(\"test command triggered\");\n });\n\n SETVALUE = new DebugCommand<float>(\"setvalue\", \"example set value\", \"setvalue <value>\", (x) =>\n {\n Debug.Log(\"Value added: \" + x.ToString());\n });\n\n commandList = new List<object>\n { \n HELP,\n HIDEHELP,\n TEST,\n SETVALUE\n };\n }\n\n private void OnGUI()\n {\n //Check input\n if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.F1)\n {\n _ShowConsole = !_ShowConsole;\n }\n\n if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && _ShowConsole)\n {\n HandleInput();\n _Input = \"\";\n }\n\n //Console active\n if (!_ShowConsole) return;\n\n GUI.FocusControl(\"FOCUS\");\n \n float y = 0f;\n\n if(_ShowHelp)\n {\n GUI.Box(new Rect(0, y, Screen.width, 100), \"\");\n Rect viewport = new Rect(0, 0, Screen.width - 30, 20 * commandList.Count);\n _Scroll = GUI.BeginScrollView(new Rect(0, y + 5, Screen.width, 90), _Scroll, viewport);\n\n for (int i=0; i<commandList.Count; i++)\n {\n DebugCommandBase command = commandList[i] as DebugCommandBase;\n string label = $\"{command.CommandFormat} - {command.CommandDescription}\";\n Rect labelRect = new Rect(5, 20 * i, viewport.width - 100, 20);\n GUI.Label(labelRect, label);\n }\n\n GUI.EndScrollView();\n y += 100;\n }\n\n GUI.Box(new Rect(0, y, Screen.width, 30), \"\");\n\n GUI.backgroundColor = new Color(0,0,0,0);\n GUI.SetNextControlName(\"FOCUS\");\n _Input = GUI.TextField(new Rect(10, y + 5, Screen.width - 20, 20), _Input);\n }\n\n private void HandleInput()\n {\n string[] properties = _Input.Split(' ');\n\n for(int i=0; i < commandList.Count; i++)\n {\n DebugCommandBase commandBase = commandList[i] as DebugCommandBase;\n\n if (_Input.Contains(commandBase.CommandID))\n {\n if (commandList[i] as DebugCommand != null)\n (commandList[i] as DebugCommand).Invoke();\n else if (commandList[i] as DebugCommand<int> != null && properties.Length > 1)\n if (CheckInput(properties[1]))\n (commandList[i] as DebugCommand<int>).Invoke(int.Parse(properties[1]));\n }\n }\n }\n\n private bool CheckInput(string str)\n {\n foreach (char c in str)\n {\n if (c < '0' || c > '9')\n return false;\n }\n return true;\n }\n}\n"),
new Tool_QuickStart_Script("DialogSystem", "Dialog", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing TMPro;\nusing UnityEngine.Events;\n\npublic class DialogSystem : MonoBehaviour\n{\n public List<DialogSystem_DialogTree> Dialog = new List<DialogSystem_DialogTree>();\n\n public Vector2Int CurrentID = new Vector2Int(0,0);\n public TextMeshProUGUI DialogText;\n\n public List<TextMeshProUGUI> OptionsText = new List<TextMeshProUGUI>();\n public List<GameObject> OptionsButtons = new List<GameObject>();\n\n public Button NextButton;\n\n void Start()\n {\n \n }\n\n void Update()\n {\n DialogText.text = Dialog[CurrentID.x].DialogTree[CurrentID.y].Dialog;\n\n\n\n //OptionsActive\n for (int i = 0; i < OptionsButtons.Count; i++)\n {\n if (Dialog[CurrentID.x].DialogTree[CurrentID.y].Options.Count != 0)\n {\n if (i < Dialog[CurrentID.x].DialogTree[CurrentID.y].Options.Count)\n {\n OptionsButtons[i].SetActive(true);\n OptionsText[i].text = Dialog[CurrentID.x].DialogTree[CurrentID.y].Options[i].OptionInfo;\n }\n else\n {\n OptionsButtons[i].SetActive(false);\n }\n }\n else\n OptionsButtons[i].SetActive(false);\n }\n\n //NextButton\n if (Dialog[CurrentID.x].DialogTree[CurrentID.y].Options != null)\n {\n if (Dialog[CurrentID.x].DialogTree[CurrentID.y].Options.Count == 0)\n NextButton.enabled = true;\n else\n NextButton.enabled = false;\n }\n else\n NextButton.enabled = false;\n }\n\n public void ButtonInput(int id)\n {\n for (int i = 0; i < Dialog[CurrentID.x].DialogTree[CurrentID.y].Options[id].Options.Count; i++)\n {\n switch (Dialog[CurrentID.x].DialogTree[CurrentID.y].Options[id].Options[i].Option)\n {\n case DialogSystem_DialogOption.Options.GOTO:\n CurrentID = Dialog[CurrentID.x].DialogTree[CurrentID.y].Options[id].Options[i].NextID;\n break;\n case DialogSystem_DialogOption.Options.NEXT:\n CurrentID.y++;\n break;\n }\n break;\n }\n }\n\n public void Next()\n {\n CurrentID.y++;\n }\n}\n\n[System.Serializable]\npublic class DialogSystem_DialogTree\n{\n public string DialogTreeInfo = \"\";\n public List<DialogSystem_Dialog> DialogTree = new List<DialogSystem_Dialog>();\n}\n\n[System.Serializable]\npublic class DialogSystem_Dialog\n{\n public string Dialog = \"\";\n public List<DialogSystem_DialogOptions> Options = new List<DialogSystem_DialogOptions>();\n}\n\n[System.Serializable]\npublic class DialogSystem_DialogOptions\n{\n public string OptionInfo = \"\";\n public List<DialogSystem_DialogOption> Options = new List<DialogSystem_DialogOption>();\n\n [HideInInspector] public bool OptionToggle = false;\n}\n\n[System.Serializable]\npublic class DialogSystem_DialogOption\n{\n public enum Options {GOTO, NEXT};\n public Options Option;\n\n public Vector2Int NextID = new Vector2Int();\n}\n"),
new Tool_QuickStart_Script("DialogSystemEditor", "Dialog_Editor", "wip", "using UnityEngine;\nusing UnityEditor;\nusing System.Collections;\n\nclass DialogSystemEditor : EditorWindow\n{\n DialogSystem _Dialog;\n\n Vector2 _ScrollPos_TimeLine = new Vector2();\n Vector2 _ScrollPos_Editor = new Vector2();\n\n Vector2Int _Selected = new Vector2Int();\n\n [MenuItem(\"Tools/DialogSystem Editor\")]\n public static void ShowWindow()\n {\n EditorWindow.GetWindow(typeof(DialogSystemEditor));\n }\n\n void OnGUI()\n {\n GUILayout.Label(\"Dialog Editor\", EditorStyles.boldLabel);\n _Dialog = EditorGUILayout.ObjectField(_Dialog, typeof(DialogSystem), true) as DialogSystem;\n\n EditorGUILayout.BeginHorizontal(\"box\");\n if (_Dialog != null)\n {\n //Editor\n Editor();\n\n //TimeLine\n TimeLine();\n }\n EditorGUILayout.EndHorizontal();\n }\n\n void Editor()\n {\n EditorGUILayout.BeginVertical(\"box\");\n _ScrollPos_Editor = EditorGUILayout.BeginScrollView(_ScrollPos_Editor, GUILayout.Width(325));\n if (_Selected.x >= 0)\n {\n if (_Selected.x < _Dialog.Dialog.Count)\n {\n if (_Selected.y < _Dialog.Dialog[_Selected.x].DialogTree.Count)\n {\n //Dialog\n GUILayout.Label(\"Selected \" + \"ID:\" + _Selected.x.ToString() + \",\" + _Selected.y.ToString());\n _Dialog.Dialog[_Selected.x].DialogTreeInfo = EditorGUILayout.TextField(\"Row Info:\", _Dialog.Dialog[_Selected.x].DialogTreeInfo);\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Dialog = EditorGUILayout.TextArea(_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Dialog, GUILayout.Height(200), GUILayout.Width(300));\n\n //Dialog Options\n GUILayout.Label(\"Options\");\n EditorGUILayout.BeginVertical(\"box\");\n\n int optionscount = 0;\n for (int i = 0; i < _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options.Count; i++)\n {\n optionscount++;\n //Toggle\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionToggle = EditorGUILayout.Foldout(_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionToggle, \"(\" + optionscount.ToString() + \") \" + _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionInfo);\n \n //Options\n if (_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionToggle)\n {\n //Option Dialog\n GUILayout.Label(\"Option Dialog:\");\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionInfo = EditorGUILayout.TextArea(_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].OptionInfo, GUILayout.Height(100), GUILayout.Width(300));\n\n //Display options\n EditorGUILayout.BeginVertical(\"box\");\n for (int o = 0; o < _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options.Count; o++)\n {\n //Option dropdown/Remove Event\n EditorGUILayout.BeginHorizontal();\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options[o].Option = (DialogSystem_DialogOption.Options)EditorGUILayout.EnumPopup(_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options[o].Option);\n if (GUILayout.Button(\"-\", GUILayout.Width(20)))\n {\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options.RemoveAt(o);\n break;\n }\n EditorGUILayout.EndHorizontal();\n\n //Options\n switch (_Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options[o].Option)\n {\n case DialogSystem_DialogOption.Options.GOTO:\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options[o].NextID = EditorGUILayout.Vector2IntField(\"Next ID\", _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options[o].NextID);\n break;\n }\n\n }\n if (GUILayout.Button(\"Add Event\"))\n {\n DialogSystem_DialogOption newoption = new DialogSystem_DialogOption();\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options[i].Options.Add(newoption);\n }\n EditorGUILayout.EndVertical();\n }\n }\n if(GUILayout.Button(\"Add Option Dialog\"))\n {\n DialogSystem_DialogOptions newoption = new DialogSystem_DialogOptions();\n newoption.OptionInfo = \"new option\";\n _Dialog.Dialog[_Selected.x].DialogTree[_Selected.y].Options.Add(newoption);\n }\n EditorGUILayout.EndVertical();\n }\n else\n {\n GUILayout.Label(\"Selected\");\n GUILayout.Label(\"ID: --\");\n GUILayout.Label(\"Press a button on \nthe timeline to select!\");\n }\n }\n }\n else\n {\n GUILayout.Label(\"Selected\");\n GUILayout.Label(\"ID: --\");\n GUILayout.Label(\"Press a button on \nthe timeline to select!\");\n }\n EditorGUILayout.EndScrollView();\n EditorGUILayout.EndVertical();\n }\n\n void TimeLine()\n {\n EditorGUILayout.BeginVertical();\n _ScrollPos_TimeLine = EditorGUILayout.BeginScrollView(_ScrollPos_TimeLine);\n for (int i = 0; i < _Dialog.Dialog.Count; i++)\n {\n EditorGUILayout.BeginHorizontal(\"box\");\n\n //Row Options\n EditorGUILayout.BeginVertical();\n\n //ID/Remove\n EditorGUILayout.BeginHorizontal();\n //GUILayout.Label(_Dialog.Dialog[i].DialogTreeID.ToString(), GUILayout.Width(20));\n if (GUILayout.Button(\"-\", GUILayout.Width(20)))\n {\n _Dialog.Dialog.RemoveAt(i);\n if(_Selected.x > _Dialog.Dialog.Count-1)\n _Selected.x--;\n break;\n }\n EditorGUILayout.EndHorizontal();\n\n //ADD\n if (GUILayout.Button(\"+\", GUILayout.Width(20)))\n {\n DialogSystem_Dialog newdialog = new DialogSystem_Dialog();\n newdialog.Dialog = \"dialogtext\";\n _Dialog.Dialog[i].DialogTree.Add(newdialog);\n }\n\n EditorGUILayout.EndVertical();\n\n //TimeLineButtons\n for (int j = 0; j < 100; j++)\n {\n EditorGUILayout.BeginVertical();\n GUILayout.Label(j.ToString());\n\n if (j < _Dialog.Dialog[i].DialogTree.Count)\n {\n //if (GUILayout.Button(\"(\" + _Dialog.Dialog[i].DialogTree[j].Options.Count.ToString() + \") \" + _Dialog.Dialog[i].DialogTree[j].Dialog, GUILayout.Width(100), GUILayout.Height(30)))\n if (GUILayout.Button(j.ToString() + \" (\" + _Dialog.Dialog[i].DialogTree[j].Options.Count.ToString() + \") \", GUILayout.Width(100), GUILayout.Height(30)))\n {\n _Selected = new Vector2Int(i, j);\n }\n }\n\n EditorGUILayout.EndVertical();\n }\n EditorGUILayout.EndHorizontal();\n }\n\n if (GUILayout.Button(\"Add Dialog Tree\", GUILayout.Width(100), GUILayout.Height(50)))\n {\n DialogSystem_DialogTree newdialogtree = new DialogSystem_DialogTree();\n DialogSystem_Dialog newdialog = new DialogSystem_Dialog();\n newdialog.Dialog = \"dialogtext\";\n newdialogtree.DialogTree.Add(newdialog);\n _Dialog.Dialog.Add(newdialogtree);\n }\n\n EditorGUILayout.EndScrollView();\n EditorGUILayout.EndVertical();\n }\n}\n"),
new Tool_QuickStart_Script("Disable", "Practical_Disable", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Disable : MonoBehaviour {\n\n [SerializeField] private GameObject _Object;\n\n public void DisableObject(float seconds) {\n StartCoroutine(StartDisable(seconds));\n }\n\n private IEnumerator StartDisable(float seconds)\n {\n yield return new WaitForSeconds(seconds);\n _Object.SetActive(false);\n }\n}\n"),
new Tool_QuickStart_Script("DoEvent", "Practical_Event_UnityEvent", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine.Events;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class DoEvent : MonoBehaviour\n{\n [SerializeField] private UnityEvent _Event = null;\n [SerializeField] private bool _OnStart = false;\n [SerializeField] private bool _OnUpdate = false;\n [SerializeField] private bool _OnButtonPressed = false;\n\n void Start()\n {\n if (_OnStart)\n DoEvents();\n }\n\n void Update()\n {\n if (_OnUpdate)\n DoEvents();\n\n if (_OnButtonPressed)\n if (Input.anyKey)\n DoEvents();\n }\n\n private void DoEvents()\n {\n _Event.Invoke();\n }\n\n public void SetGameobject_InActive(GameObject targetobject)\n {\n targetobject.SetActive(false);\n }\n\n public void SetGameobject_Active(GameObject targetobject)\n {\n targetobject.SetActive(true);\n }\n\n public void SetGameObject_Negative(GameObject targetobject)\n {\n if (targetobject.activeSelf)\n targetobject.SetActive(false);\n else\n targetobject.SetActive(true);\n }\n\n public void LoadScene(int sceneid)\n {\n SceneManager.LoadScene(sceneid);\n }\n public void LoadScene(string scenename)\n {\n SceneManager.LoadScene(scenename);\n }\n public void Quit()\n {\n Application.Quit();\n }\n}\n"),
new Tool_QuickStart_Script("DontDestroy", "Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class DontDestroy : MonoBehaviour\n{\n void Start()\n {\n DontDestroyOnLoad(this.gameObject);\n }\n}\n"),
new Tool_QuickStart_Script("EditorWindowExample", "Editor_Window", "stable", "using UnityEngine;\nusing UnityEditor;\nusing System.Collections;\n\nclass EditorWindowExample : EditorWindow\n{\n string examplestring = \"example\";\n bool examplebool = false;\n\n [MenuItem(\"Tools/EditorWindowExample\")]\n public static void ShowWindow()\n {\n EditorWindow.GetWindow(typeof(EditorWindowExample));\n }\n\n void OnGUI()\n {\n GUILayout.Label(\"Example Title\", EditorStyles.boldLabel);\n examplestring = EditorGUILayout.TextField(\"Example string field\", examplestring);\n examplebool = EditorGUILayout.Toggle(\"Example bool field\", examplebool);\n }\n}\n"),
new Tool_QuickStart_Script("EnemySpawnHandler", "Enemy_Spawn_Handler", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class EnemySpawnHandler : MonoBehaviour\n{\n private enum Options {Endless, Waves}\n\n [Header(\"Settings\")]\n [SerializeField] private Options _Option = Options.Endless;\n [SerializeField] private int _Seed = 0;\n [SerializeField] private bool _SetRandomSeed = true;\n\n [Header(\"Object Pool\")]\n [SerializeField] private ObjectPool _ObjectPool = null;\n\n [Header(\"Enemies\")]\n [SerializeField] private EnemySpawnHandler_Enemy[] _Enemies = null;\n\n [Header(\"SpawnLocations\")]\n [SerializeField] private Transform[] _SpawnLocations = null;\n\n [Header(\"Settings - Endless\")]\n [SerializeField] private float _SpawnRate = 5; // Seconds between spawning\n [SerializeField] private float _SpawnRateEncrease = 0.05f; // Decrease time between spawning per sec\n [SerializeField] private bool _RandomEnemy = true;\n [SerializeField] private bool _RandomSpawn = true;\n\n [Header(\"Settings - Waves\")]\n [SerializeField] private EnemySpawnHandler_WaveSettings _Waves = null;\n [SerializeField] private bool _WaitForAllEnemiesKilled = true;\n\n private float _Timer = 0;\n private int _CurrentWave = 0;\n private int _CheckWave = 999;\n private float _TimerBetweenWaves = 0;\n private float _SpawnSpeed = 0;\n\n private int _EnemiesAlive = 0;\n\n private void Start()\n {\n if (_SetRandomSeed)\n Random.InitState(Random.Range(0, 10000));\n else\n Random.InitState(_Seed);\n\n if (_Waves.WaveOption == EnemySpawnHandler_WaveSettings.WaveOptions.Generate)\n GenerateWaves();\n if (_Waves.WaveOption == EnemySpawnHandler_WaveSettings.WaveOptions.Endless)\n {\n _Waves.WaveAmount = 1;\n GenerateWaves();\n GenerateWaves(1);\n }\n }\n\n void Update()\n {\n _Timer += 1 * Time.deltaTime;\n\n switch (_Option)\n {\n case Options.Endless:\n Update_Endless();\n break;\n case Options.Waves:\n Update_Waves();\n break;\n }\n }\n\n //Update\n private void Update_Endless()\n {\n if (_Timer >= _SpawnRate)\n {\n int randomenemyid = 0;\n int randomspawnid = 0;\n if (_RandomEnemy)\n randomenemyid = Random.Range(0, _Enemies.Length);\n if (_RandomSpawn)\n randomspawnid = Random.Range(0, _SpawnLocations.Length);\n Spawn(randomenemyid, randomspawnid);\n _Timer = 0;\n }\n _SpawnRate -= _SpawnRateEncrease * Time.deltaTime;\n }\n private void Update_Waves()\n {\n if (_CurrentWave < _Waves.Waves.Count)\n {\n if (_CheckWave != _CurrentWave)\n {\n if (_WaitForAllEnemiesKilled)\n {\n EnemiesAlive();\n\n if (_EnemiesAlive == 0)\n _TimerBetweenWaves += 1 * Time.deltaTime;\n }\n else\n _TimerBetweenWaves += 1 * Time.deltaTime;\n\n if (_TimerBetweenWaves >= _Waves.TimeBetweenWaves)\n {\n _TimerBetweenWaves = 0;\n _CheckWave = _CurrentWave;\n _SpawnSpeed = _Waves.Waves[_CurrentWave].SpawnDuration / _Waves.Waves[_CurrentWave].TotalEnemies;\n if (_Waves.WaveOption == EnemySpawnHandler_WaveSettings.WaveOptions.Endless)\n GenerateWaves(_CurrentWave+2);\n }\n }\n else\n {\n //Spawn\n if (_Waves.Waves[_CurrentWave].TotalEnemies > 0)\n {\n if (_Timer > _SpawnSpeed)\n {\n bool spawncheck = false;\n while (!spawncheck)\n {\n int spawnid = Random.Range(0, _Enemies.Length);\n if (_Waves.Waves[_CurrentWave].EnemyID[spawnid] > 0)\n {\n Spawn(spawnid, Random.Range(0, _SpawnLocations.Length));\n _Waves.Waves[_CheckWave].EnemyID[spawnid]--;\n _Waves.Waves[_CurrentWave].TotalEnemies--;\n spawncheck = true;\n }\n }\n _Timer = 0;\n }\n }\n else\n {\n _CurrentWave++;\n }\n }\n }\n }\n\n //Generate Waves\n private void GenerateWaves(int waveid = 0)\n {\n int enemytypes = _Enemies.Length;\n for (int i = 0; i < _Waves.WaveAmount; i++)\n {\n EnemySpawnHandler_Wave newwave = new EnemySpawnHandler_Wave();\n int enemyamount = 0;\n\n if (waveid == 0)\n enemyamount = Mathf.RoundToInt(_Waves.EnemyAmount * ((_Waves.EnemyIncreaseAmount * i) + 1));\n else\n enemyamount = Mathf.RoundToInt(_Waves.EnemyAmount * ((_Waves.EnemyIncreaseAmount * waveid) + 1));\n\n //Set enemy amount\n newwave.EnemyID = new int[enemytypes];\n int checkenemyamount = 0;\n newwave.TotalEnemies = enemyamount;\n\n while (checkenemyamount < enemyamount)\n {\n for (int j = 0; j < enemytypes; j++)\n {\n if (_Enemies[j].StartWave <= i)\n {\n int addamount = 0;\n if (enemyamount < 2)\n addamount = Random.Range(0, enemyamount);\n else\n addamount = Random.Range(0, Mathf.RoundToInt(enemyamount*0.5f));\n\n if (enemyamount > checkenemyamount + addamount)\n {\n newwave.EnemyID[j] += addamount;\n checkenemyamount += addamount;\n }\n else\n {\n newwave.EnemyID[j] += enemyamount - checkenemyamount;\n checkenemyamount = enemyamount;\n continue;\n }\n }\n }\n }\n _Waves.Waves.Add(newwave);\n }\n }\n\n public void Spawn(int enemyid, int spawnid)\n {\n GameObject obj = _ObjectPool.GetObjectPrefabName(_Enemies[enemyid].EnemyPrefab.name, false);\n obj.transform.position = _SpawnLocations[spawnid].position;\n obj.SetActive(true);\n }\n private void EnemiesAlive()\n {\n _EnemiesAlive = GameObject.FindGameObjectsWithTag(\"Enemy\").Length;\n }\n}\n\n[System.Serializable]\npublic class EnemySpawnHandler_Enemy\n{\n public string EnemyName;\n public GameObject EnemyPrefab;\n\n [Header(\"Settings\")]\n public int StartWave;\n}\n\n[System.Serializable]\npublic class EnemySpawnHandler_WaveSettings\n{\n public enum WaveOptions {Endless, Manually, Generate}\n public WaveOptions WaveOption;\n\n [Header(\"Endless\")]\n public float EnemyIncreaseAmount;\n\n [Header(\"Manual\")]\n public List<EnemySpawnHandler_Wave> Waves;\n\n [Header(\"Generate\")]\n public int WaveAmount;\n public int EnemyAmount;\n\n [Header(\"Other\")]\n public float TimeBetweenWaves;\n}\n\n[System.Serializable]\npublic class EnemySpawnHandler_Wave\n{\n public int[] EnemyID;\n public float SpawnDuration = 5;\n\n [HideInInspector] public int TotalEnemies;\n}\n"),
new Tool_QuickStart_Script("FadeInOut", "Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine.UI;\nusing UnityEngine;\n\npublic class FadeInOut : MonoBehaviour\n{\n private enum Fade { In, Out }\n [SerializeField] private Fade _FadeOption = Fade.In;\n [SerializeField] private float _Duration = 0;\n\n [SerializeField] private Image _Image = null;\n\n private float _ChangeSpeed;\n private Color _Color;\n\n void Start()\n {\n if (_Image == null)\n _Image = GetComponent<Image>();\n\n if (_FadeOption == Fade.In)\n _Color = new Color(_Image.color.r, _Image.color.g, _Image.color.b, 0);\n else\n _Color = new Color(_Image.color.r, _Image.color.g, _Image.color.b, 1);\n\n _ChangeSpeed = 1 / _Duration;\n }\n\n void Update()\n {\n if (_FadeOption == Fade.In && _Color.a < 1)\n {\n _Color.a += _ChangeSpeed * Time.deltaTime;\n }\n if (_FadeOption == Fade.Out && _Color.a > 0)\n {\n _Color.a -= _ChangeSpeed * Time.deltaTime;\n }\n\n _Image.color = _Color;\n }\n}\n"),
new Tool_QuickStart_Script("Health", "Health", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\n\npublic class Health : MonoBehaviour\n{\n [SerializeField] private float _MaxHealth = 100;\n\n [SerializeField] private UnityEvent _OnDeath;\n\n private float _CurrentHealth;\n\n private void OnEnable()\n {\n _CurrentHealth = _MaxHealth;\n }\n\n public void DoDamage(float damageamount)\n {\n _CurrentHealth -= damageamount;\n if(_CurrentHealth <= 0)\n {\n _CurrentHealth = 0;\n _OnDeath.Invoke();\n gameObject.SetActive(false);\n }\n }\n\n public float GetCurrentHealth()\n {\n return _CurrentHealth;\n }\n public float GetMaxHealth()\n {\n return GetMaxHealth();\n }\n}\n"),
new Tool_QuickStart_Script("Interactable", "Interaction", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\nusing UnityEngine.UI;\n\npublic class Interactable : MonoBehaviour\n{\n public enum InteractableType { Move, Door, SetLight, SetLightNegative, Lever, Button, Item, UIButton }\n public InteractableType _Type;\n\n private enum AxisOptions { x, y, z }\n [SerializeField] private AxisOptions _AxisOption = AxisOptions.x;\n\n [SerializeField] private bool _InvertMouse = false;\n\n [Header(\"Type - Light\")]\n [SerializeField] private GameObject _Light = null;\n [SerializeField] private bool _Light_StartOff = false;\n [Header(\"Type - Lever/Door\")]\n [SerializeField] private Transform _LeverRotationPoint = null;\n [SerializeField] private Vector2 _LeverMinMaxRotation = Vector2.zero;\n [SerializeField] private float _CompleteDeathZone = 0;\n [Header(\"Type - Button\")]\n [SerializeField] private float _ButtonPressDepth = 0;\n private bool _ButtonPressed;\n [Header(\"Type - Item\")]\n [SerializeField] private string _ItemInfo = \"\";\n [Header(\"Speed\")]\n [SerializeField] private float _Speed = 1;\n\n [Header(\"OnHigh\")]\n [SerializeField] private UnityEvent _OnHighEvent = null;\n [Header(\"OnLow\")]\n [SerializeField] private UnityEvent _OnLowEvent = null;\n [Header(\"OnNeutral\")]\n [SerializeField] private UnityEvent _OnNeutral = null;\n [Header(\"Trigger\")]\n [SerializeField] private UnityEvent _OnTrigger = null;\n\n\n private Vector3 velocity = Vector3.zero;\n private Rigidbody _RB;\n private Vector3 _DefaultLocalPosition;\n private Vector3 _DefaultPosition;\n private bool _MovingBack;\n\n private void Start()\n {\n _DefaultLocalPosition = transform.localPosition;\n _DefaultPosition = transform.position;\n _RB = GetComponent<Rigidbody>();\n if (_Type == InteractableType.SetLight || _Type == InteractableType.SetLightNegative)\n {\n if (_Light_StartOff)\n _Light.SetActive(false);\n else\n _Light.SetActive(true);\n }\n }\n\n private void Update()\n {\n if (_Type == InteractableType.Button)\n {\n UpdateButton();\n }\n\n if (_MovingBack)\n {\n transform.localPosition = Vector3.MoveTowards(transform.localPosition, _DefaultLocalPosition, 10 * Time.deltaTime);\n if (transform.localPosition == _DefaultLocalPosition)\n _MovingBack = false;\n }\n }\n\n public InteractableType Type()\n {\n return _Type;\n }\n\n public void GotoPickupPoint(Transform point)\n {\n _RB.velocity = Vector3.zero;\n transform.position = Vector3.SmoothDamp(transform.position, point.position, ref velocity, 0.2f);\n transform.rotation = Quaternion.RotateTowards(transform.rotation, point.rotation, 5f);\n }\n public void SetVelocity(Vector3 velocity)\n {\n _RB.velocity = velocity;\n }\n public void TrowObject(Transform transformtrow)\n {\n _RB.AddForce(transformtrow.forward * 5000);\n }\n public void OpenDoor()\n {\n float mouseY = Input.GetAxis(\"Mouse Y\");\n float angle = 0;\n switch (_AxisOption)\n {\n case AxisOptions.x:\n angle = _LeverRotationPoint.localEulerAngles.x;\n break;\n case AxisOptions.y:\n angle = _LeverRotationPoint.localEulerAngles.y;\n break;\n case AxisOptions.z:\n angle = _LeverRotationPoint.localEulerAngles.z;\n break;\n }\n angle = (angle > 180) ? angle - 360 : angle;\n\n HandleRotation(_LeverRotationPoint, new Vector2(0, mouseY), _LeverMinMaxRotation, 1.2f, angle);\n }\n public void MoveLever()\n {\n float mouseY = Input.GetAxis(\"Mouse Y\");\n float angle = 0;\n switch (_AxisOption)\n {\n case AxisOptions.x:\n angle = _LeverRotationPoint.localEulerAngles.x;\n break;\n case AxisOptions.y:\n angle = _LeverRotationPoint.localEulerAngles.y;\n break;\n case AxisOptions.z:\n angle = _LeverRotationPoint.localEulerAngles.z;\n break;\n }\n angle = (angle > 180) ? angle - 360 : angle;\n\n HandleRotation(_LeverRotationPoint, new Vector2(0, mouseY), _LeverMinMaxRotation, 1.2f, angle);\n\n //Check\n if (angle < _LeverMinMaxRotation.x + _CompleteDeathZone)\n {\n _OnLowEvent.Invoke();\n }\n if (angle > _LeverMinMaxRotation.y - _CompleteDeathZone)\n {\n _OnHighEvent.Invoke();\n }\n if (angle > _LeverMinMaxRotation.x + _CompleteDeathZone && angle < _LeverMinMaxRotation.y - _CompleteDeathZone)\n {\n _OnNeutral.Invoke();\n }\n }\n public void PressButton(bool option)\n {\n _ButtonPressed = true;\n }\n public void PressButtonNegative()\n {\n _ButtonPressed = !_ButtonPressed;\n }\n public void SetLight(bool option)\n {\n _Light.SetActive(option);\n }\n public void SetLightNegative()\n {\n if (_Light.activeSelf)\n _Light.SetActive(false);\n else\n _Light.SetActive(true);\n }\n public void ReturnToDefaultPos()\n {\n _MovingBack = true;\n }\n public string GetItemInfo()\n {\n return _ItemInfo;\n }\n public void PressUIButton()\n {\n _OnTrigger.Invoke();\n }\n private void HandleRotation(Transform effectedtransform, Vector2 mousemovement, Vector2 minmaxangle, float speed, float angle)\n {\n if (_InvertMouse)\n {\n mousemovement.x = mousemovement.x * -2;\n mousemovement.y = mousemovement.y * -2;\n }\n\n switch (_AxisOption)\n {\n case AxisOptions.x:\n effectedtransform.localEulerAngles += new Vector3((mousemovement.x + mousemovement.y) * speed, 0, 0);\n\n if (angle < minmaxangle.x)\n effectedtransform.localEulerAngles = new Vector3(minmaxangle.x + 0.5f, 0, 0);\n if (angle > minmaxangle.y)\n effectedtransform.localEulerAngles = new Vector3(minmaxangle.y - 0.5f, 0, 0);\n break;\n case AxisOptions.y:\n effectedtransform.localEulerAngles += new Vector3(0, (mousemovement.x + mousemovement.y) * speed, 0);\n\n if (angle < minmaxangle.x)\n effectedtransform.localEulerAngles = new Vector3(0, minmaxangle.x + 0.5f, 0);\n if (angle > minmaxangle.y)\n effectedtransform.localEulerAngles = new Vector3(0, minmaxangle.y - 0.5f, 0);\n break;\n case AxisOptions.z:\n effectedtransform.localEulerAngles += new Vector3(0, 0, (mousemovement.x + mousemovement.y) * speed);\n\n if (angle < minmaxangle.x)\n effectedtransform.localEulerAngles = new Vector3(0, 0, minmaxangle.x + 0.5f);\n if (angle > minmaxangle.y)\n effectedtransform.localEulerAngles = new Vector3(0, 0, minmaxangle.y - 0.5f);\n break;\n }\n }\n\n private void UpdateButton()\n {\n switch (_AxisOption)\n {\n case AxisOptions.x:\n if (_ButtonPressed)\n {\n if (transform.localPosition.x > _DefaultLocalPosition.x - _ButtonPressDepth)\n transform.localPosition -= new Vector3(_Speed, 0, 0) * Time.deltaTime;\n else\n {\n transform.localPosition = new Vector3(_DefaultLocalPosition.x - _ButtonPressDepth - 0.001f, transform.localPosition.y, transform.localPosition.z);\n _OnLowEvent.Invoke();\n }\n }\n else\n {\n if (transform.localPosition.x < _DefaultLocalPosition.x + _ButtonPressDepth)\n transform.localPosition += new Vector3(_Speed, 0, 0) * Time.deltaTime;\n else\n {\n transform.localPosition = new Vector3(_DefaultLocalPosition.x + _ButtonPressDepth, transform.localPosition.y, transform.localPosition.z);\n _OnHighEvent.Invoke();\n }\n\n }\n break;\n case AxisOptions.y:\n if (_ButtonPressed)\n {\n if (transform.localPosition.y > _DefaultLocalPosition.y - _ButtonPressDepth)\n transform.localPosition -= new Vector3(0, _Speed, 0) * Time.deltaTime;\n else\n {\n transform.localPosition = new Vector3(_DefaultLocalPosition.x, _DefaultLocalPosition.y - _ButtonPressDepth - 0.001f, _DefaultLocalPosition.z);\n _OnLowEvent.Invoke();\n }\n }\n else\n {\n if (transform.localPosition.y < _DefaultLocalPosition.y)\n transform.localPosition += new Vector3(0, _Speed, 0) * Time.deltaTime;\n else\n {\n transform.localPosition = _DefaultLocalPosition;\n _OnHighEvent.Invoke();\n }\n }\n break;\n case AxisOptions.z:\n if (_ButtonPressed)\n {\n if (transform.localPosition.z > _DefaultLocalPosition.z - _ButtonPressDepth)\n transform.localPosition -= new Vector3(0, 0, _Speed) * Time.deltaTime;\n else\n {\n transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, _DefaultLocalPosition.z - _ButtonPressDepth - 0.001f);\n _OnLowEvent.Invoke();\n }\n }\n else\n {\n if (transform.localPosition.z < _DefaultLocalPosition.z + _ButtonPressDepth)\n transform.localPosition += new Vector3(0, 0, _Speed) * Time.deltaTime;\n else\n {\n transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, _DefaultLocalPosition.z + _ButtonPressDepth);\n _OnHighEvent.Invoke();\n }\n }\n break;\n }\n }\n}\n"),
new Tool_QuickStart_Script("InteractionHandler", "Interaction_Handler", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\nusing TMPro;\n\npublic class InteractionHandler : MonoBehaviour\n{\n [SerializeField] private Image _Cursor = null;\n [SerializeField] private LayerMask _LayerMask = 0;\n [SerializeField] private Transform _Head = null;\n [Header(\"Pickup\")]\n [SerializeField] private GameObject _PickupPoint = null;\n [SerializeField] private Vector2 _PickupMinMaxRange = Vector2.zero;\n [SerializeField] private float _Range = 0;\n [Header(\"Item\")]\n [SerializeField] private Transform _ItemPreviewPoint = null;\n [SerializeField] private TextMeshProUGUI _ItemInfoText = null;\n\n private string _ItemInfo;\n\n private Vector3 _PickupPointPosition;\n private Vector3 _CalcVelocity;\n private Vector3 _PrevPosition;\n\n private GameObject _ActiveObject;\n private GameObject _CheckObject;\n private Interactable _Interactable;\n\n private bool _Interacting;\n private bool _Previewing;\n\n private Movement_CC_FirstPerson _CCS; //Script that handles rotation\n\n void Start()\n {\n _CCS = GetComponent<Movement_CC_FirstPerson>();\n _PickupPointPosition.z = _PickupMinMaxRange.x;\n }\n\n void Update()\n {\n if (!_Interacting)\n {\n RaycastHit hit;\n\n if (Physics.Raycast(_Head.position, _Head.TransformDirection(Vector3.forward), out hit, _Range, _LayerMask))\n {\n Debug.DrawRay(_Head.position, _Head.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);\n\n _ActiveObject = hit.transform.gameObject;\n\n _Cursor.color = Color.white;\n }\n else\n {\n Debug.DrawRay(_Head.position, _Head.TransformDirection(Vector3.forward) * _Range, Color.white);\n _Cursor.color = Color.red;\n\n _ActiveObject = null;\n _CheckObject = null;\n }\n\n if (_ActiveObject != _CheckObject)\n {\n _Interactable = _ActiveObject.GetComponent<Interactable>();\n _CheckObject = _ActiveObject;\n }\n }\n\n if(_ActiveObject != null)\n {\n if (_Interactable._Type != Interactable.InteractableType.Item)\n {\n //OnDown\n if (Input.GetMouseButtonDown(0))\n OnDown();\n\n if (_Interacting)\n {\n //OnUp\n if (Input.GetMouseButtonUp(0))\n OnUp();\n\n //OnActive\n OnActive();\n }\n }\n else\n {\n if (!_Previewing)\n {\n //Start Preview\n if (Input.GetKeyDown(KeyCode.E))\n {\n _ItemInfo = _Interactable.GetItemInfo();\n _CCS.LockRotation(true);\n _Previewing = true;\n }\n }\n else\n {\n _ActiveObject.transform.position = _ItemPreviewPoint.position;\n _Interactable.gameObject.transform.eulerAngles += new Vector3(-Input.GetAxis(\"Mouse Y\"), Input.GetAxis(\"Mouse X\"), 0);\n\n //Reset Preview\n if (Input.GetKeyDown(KeyCode.E))\n {\n _ItemInfo = \"\";\n _CCS.LockRotation(false);\n _Interactable.ReturnToDefaultPos();\n _Previewing = false;\n }\n }\n }\n }\n\n _ItemInfoText.text = _ItemInfo;\n }\n\n void FixedUpdate()\n {\n if (_Interacting)\n {\n OnActiveFixed();\n OnActiveFixed();\n }\n }\n\n private void OnUp()\n {\n _Interacting = false;\n switch (_Interactable._Type)\n {\n case Interactable.InteractableType.Lever:\n _CCS.LockRotation(false);\n break;\n case Interactable.InteractableType.Door:\n _CCS.LockRotation(false);\n break;\n case Interactable.InteractableType.Move:\n _Interactable.SetVelocity(_CalcVelocity);\n break;\n }\n }\n private void OnDown()\n {\n _Interacting = true;\n\n //OnClick\n switch (_Interactable._Type)\n {\n case Interactable.InteractableType.SetLight:\n _Interactable.SetLight(true);\n break;\n case Interactable.InteractableType.SetLightNegative:\n _Interactable.SetLightNegative();\n break;\n case Interactable.InteractableType.Move:\n _PickupPoint.transform.rotation = _ActiveObject.transform.rotation;\n _PickupPointPosition.z = Vector3.Distance(_Head.position, _ActiveObject.transform.position);\n break;\n case Interactable.InteractableType.Lever:\n _CCS.LockRotation(true);\n _PickupPointPosition.z = Vector3.Distance(_Head.position, _ActiveObject.transform.position);\n break;\n case Interactable.InteractableType.Door:\n _CCS.LockRotation(true);\n break;\n case Interactable.InteractableType.Button:\n _Interactable.PressButtonNegative();\n break;\n case Interactable.InteractableType.UIButton:\n _Interactable.PressUIButton();\n break;\n }\n }\n private void OnActive()\n {\n switch (_Interactable._Type)\n {\n case Interactable.InteractableType.Move:\n if (_PickupPointPosition.z < _PickupMinMaxRange.y && Input.mouseScrollDelta.y > 0)\n _PickupPointPosition.z += Input.mouseScrollDelta.y * 0.5f;\n if (_PickupPointPosition.z > _PickupMinMaxRange.x && Input.mouseScrollDelta.y < 0)\n _PickupPointPosition.z += Input.mouseScrollDelta.y * 0.5f;\n\n if(Input.GetMouseButtonDown(1))\n {\n _Interactable.TrowObject(_Head.transform);\n OnUp();\n }\n break;\n case Interactable.InteractableType.Door:\n _Interactable.OpenDoor();\n break;\n case Interactable.InteractableType.Lever:\n _Interactable.MoveLever();\n break;\n }\n\n if (Vector3.Distance(_Head.transform.position, _ActiveObject.transform.position) > _Range)\n {\n _Interacting = false;\n OnUp();\n }\n }\n\n private void OnActiveFixed()\n {\n switch (_Interactable._Type)\n {\n case Interactable.InteractableType.Move:\n _Interactable.GotoPickupPoint(_PickupPoint.transform);\n\n _PickupPoint.transform.localPosition = _PickupPointPosition;\n\n _CalcVelocity = (_ActiveObject.transform.position - _PrevPosition) / Time.deltaTime;\n _PrevPosition = _ActiveObject.transform.position;\n break;\n }\n }\n}\n"),
new Tool_QuickStart_Script("InteractWithPhysics", "Interact_Physics", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class InteractWithPhysics : MonoBehaviour\n{\n\n void OnControllerColliderHit(ControllerColliderHit hit)\n {\n Rigidbody body = hit.collider.attachedRigidbody;\n if (body != null && !body.isKinematic)\n body.velocity += hit.controller.velocity;\n }\n}\n"),
new Tool_QuickStart_Script("Inventory", "Inventory", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Inventory : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n"),
new Tool_QuickStart_Script("LightEffects", "Light_Effect", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class LightEffects : MonoBehaviour\n{\n public enum LightEffectOptions { Flickering, Off, On };\n\n [Header(\"Settings\")]\n [SerializeField] private LightEffectOptions _LightEffectOption = LightEffectOptions.Flickering;\n [SerializeField] private Vector2 _MinMaxIncrease = new Vector2(0.8f, 1.2f);\n [Range(0.01f, 100)] [SerializeField] private float _EffectStrength = 50;\n\n Queue<float> _LightFlickerQ;\n private float _LastSum = 0;\n private Light _Light;\n private float _LightIntensity = 0;\n\n public void Reset()\n {\n if (_LightEffectOption == LightEffectOptions.Flickering)\n {\n _LightFlickerQ.Clear();\n _LastSum = 0;\n }\n }\n\n void Start()\n {\n _Light = GetComponent<Light>();\n _LightIntensity = _Light.intensity;\n _LightFlickerQ = new Queue<float>(Mathf.RoundToInt(_EffectStrength));\n }\n\n void Update()\n {\n switch(_LightEffectOption)\n {\n case LightEffectOptions.Flickering:\n while (_LightFlickerQ.Count >= _EffectStrength)\n _LastSum -= _LightFlickerQ.Dequeue();\n\n float newVal = Random.Range(_LightIntensity * _MinMaxIncrease.x, _LightIntensity * _MinMaxIncrease.y);\n _LightFlickerQ.Enqueue(newVal);\n _LastSum += newVal;\n _Light.intensity = _LastSum / (float)_LightFlickerQ.Count;\n break;\n case LightEffectOptions.Off:\n _Light.intensity = 0;\n break;\n case LightEffectOptions.On:\n _Light.intensity = _LightIntensity = _MinMaxIncrease.x;\n break;\n }\n\n }\n\n public void SetEffect(LightEffectOptions options)\n {\n _LightEffectOption = options;\n }\n}\n"),
new Tool_QuickStart_Script("LoadScenes", "Load_Scenes", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class LoadScenes : MonoBehaviour\n{\n public void Action_LoadScene(int sceneid)\n {\n SceneManager.LoadScene(sceneid);\n }\n public void Action_LoadScene(string scenename)\n {\n SceneManager.LoadScene(scenename);\n }\n\n public void Action_ReloadScene()\n {\n SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);\n }\n\n public void Action_QuitApplication()\n {\n Application.Quit();\n }\n}\n"),
new Tool_QuickStart_Script("MenuHandler", "Menu_Handler", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class MenuHandler : MonoBehaviour\n{\n public void LoadScene(int sceneid)\n {\n SceneManager.LoadScene(sceneid);\n }\n\n public void LoadScene(string scenename)\n {\n SceneManager.LoadScene(scenename);\n }\n\n public int Get_CurrentSceneID()\n {\n return SceneManager.GetActiveScene().buildIndex;\n }\n\n public string Get_CurrentSceneName()\n {\n return SceneManager.GetActiveScene().name;\n }\n\n public void QuitGame()\n {\n Application.Quit();\n }\n}\n"),
new Tool_QuickStart_Script("Movement_2D_Platformer", "Movement_2D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(Rigidbody2D))]\npublic class Movement_2D_Platformer : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _NormalSpeed = 5;\n [SerializeField] private float _SprintSpeed = 8;\n [SerializeField] private float _JumpSpeed = 300;\n [SerializeField] private float _GroundCheck = 0.6f;\n [Header(\"Set ground layer\")]\n [SerializeField] private LayerMask _GroundMask = ~1;\n\n private float _Speed = 0;\n private Rigidbody2D _RB;\n\n void Start()\n {\n //Get Rigidbody / Lock z rotation\n _RB = GetComponent<Rigidbody2D>();\n _RB.constraints = RigidbodyConstraints2D.FreezeRotation;\n }\n\n void Update()\n {\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n _Speed = _SprintSpeed;\n else\n _Speed = _NormalSpeed;\n\n //Jumping\n if (Input.GetButtonDown(\"Jump\") && IsGrounded())\n _RB.AddForce(new Vector2(0, _JumpSpeed));\n\n //Apply Movement\n _RB.velocity = new Vector2(Input.GetAxis(\"Horizontal\") * _Speed, _RB.velocity.y);\n }\n\n bool IsGrounded()\n {\n RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, _GroundCheck, _GroundMask);\n if (hit.collider != null)\n {\n return true;\n }\n return false;\n }\n}\n"),
new Tool_QuickStart_Script("Movement_2D_TopDown", "Movement_2D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(Rigidbody2D))]\npublic class Movement_2D_TopDown : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _NormalSpeed = 5;\n [SerializeField] private float _SprintSpeed = 8;\n\n private float _Speed = 0;\n private Rigidbody2D _RB;\n\n void Start()\n {\n //Get Rigidbody / Lock z rotation\n _RB = GetComponent<Rigidbody2D>();\n _RB.constraints = RigidbodyConstraints2D.FreezeRotation;\n _RB.gravityScale = 0;\n }\n\n void Update()\n {\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n _Speed = _SprintSpeed;\n else\n _Speed = _NormalSpeed;\n\n //Apply Movement\n _RB.velocity = new Vector2(Input.GetAxis(\"Horizontal\") * _Speed, Input.GetAxis(\"Vertical\") * _Speed);\n }\n}\n"),
new Tool_QuickStart_Script("Movement_Camera", "Movement_3D_Camera", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Movement_Camera : MonoBehaviour\n{\n private enum CameraOptionsPos { None, Follow }\n private enum CameraOptionsRot { None, Follow }\n\n [Header(\"Options\")]\n [SerializeField] private CameraOptionsPos _CameraOptionPos = CameraOptionsPos.Follow;\n [SerializeField] private CameraOptionsRot _CameraOptionRot = CameraOptionsRot.Follow;\n\n [Header(\"Settings - Position\")]\n [SerializeField] private Vector3 _OffsetPosition = new Vector3(0,12,-4);\n\n [Header(\"Settings - Rotation\")]\n [SerializeField] private Vector3 _OffsetRotation = Vector3.zero;\n\n [Header(\"Settings\")]\n [SerializeField] private float _Speed = 1000;\n\n [Header(\"Other\")]\n [SerializeField] private Transform _Target = null;\n [SerializeField] private bool _LockAxis_X = false;\n [SerializeField] private bool _LockAxis_Y = false;\n [SerializeField] private bool _LockAxis_Z = false;\n\n private Vector3 _TargetPosition;\n private float _ScreenShakeDuration;\n private float _ScreenShakeIntensity;\n\n void Update()\n {\n if(Input.GetKeyDown(KeyCode.J))\n {\n Effect_ScreenShake(3, 0.5f);\n }\n\n //Update Target Location\n float x_axis = _Target.transform.position.x + _OffsetPosition.x;\n float y_axis = _Target.transform.position.y + _OffsetPosition.y;\n float z_axis = _Target.transform.position.z + _OffsetPosition.z;\n\n if (_LockAxis_X)\n x_axis = _OffsetPosition.x;\n if (_LockAxis_Y)\n y_axis = _OffsetPosition.y;\n if (_LockAxis_Z)\n z_axis = _OffsetPosition.z;\n\n _TargetPosition = new Vector3(x_axis, y_axis, z_axis);\n\n // Movement\n switch (_CameraOptionPos)\n {\n case CameraOptionsPos.Follow:\n transform.position = Vector3.MoveTowards(transform.position, _TargetPosition, _Speed * Time.deltaTime);\n break;\n }\n\n //ScreenShake\n if(_ScreenShakeDuration > 0)\n {\n transform.localPosition = new Vector3(_TargetPosition.x + Random.insideUnitSphere.x * _ScreenShakeIntensity, _TargetPosition.y + Random.insideUnitSphere.y * _ScreenShakeIntensity, _TargetPosition.z);\n _ScreenShakeDuration -= 1 * Time.deltaTime;\n }\n else\n {\n // Rotation\n switch (_CameraOptionRot)\n {\n case CameraOptionsRot.Follow:\n Vector3 rpos = _Target.position - transform.position;\n Quaternion lookrotation = Quaternion.LookRotation(rpos, Vector3.up);\n transform.eulerAngles = new Vector3(lookrotation.eulerAngles.x + _OffsetRotation.x, lookrotation.eulerAngles.y + _OffsetRotation.y, lookrotation.eulerAngles.z + _OffsetRotation.z);\n break;\n }\n }\n }\n\n //Effects\n public void Effect_ScreenShake(float duration, float intesity)\n {\n _ScreenShakeDuration = duration;\n _ScreenShakeIntensity = intesity;\n }\n\n //Set\n public void Set_CameraTarget(GameObject targetobj)\n {\n _Target = targetobj.transform;\n }\n public void Set_OffSet(Vector3 offset)\n {\n _OffsetPosition = offset;\n }\n}\n"),
new Tool_QuickStart_Script("Movement_CC_FirstPerson", "Movement_3D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(CharacterController))]\npublic class Movement_CC_FirstPerson : MonoBehaviour\n{\n //Movement\n [SerializeField] private float _NormalSpeed = 5, _SprintSpeed = 8;\n [SerializeField] private float _JumpSpeed = 5;\n [SerializeField] private float _Gravity = 20;\n private Vector3 _MoveDirection = Vector3.zero;\n //Look around\n public float _CameraSensitivity = 1;\n [SerializeField] private Transform _Head = null;\n private float _RotationX = 90.0f;\n private float _RotationY = 0.0f;\n private float _Speed;\n\n private CharacterController _CC;\n private bool _LockRotation;\n\n void Start()\n {\n Cursor.lockState = CursorLockMode.Locked;\n Cursor.visible = false;\n _CC = GetComponent<CharacterController>();\n if (_Head == null)\n _Head = transform.GetChild(0).transform;\n }\n\n void Update()\n {\n //Look around\n if (!_LockRotation)\n {\n _RotationX += Input.GetAxis(\"Mouse X\") * _CameraSensitivity;\n _RotationY += Input.GetAxis(\"Mouse Y\") * _CameraSensitivity;\n _RotationY = Mathf.Clamp(_RotationY, -90, 90);\n\n transform.localRotation = Quaternion.AngleAxis(_RotationX, Vector3.up);\n _Head.transform.localRotation = Quaternion.AngleAxis(_RotationY, Vector3.left);\n }\n\n //Movement\n if (_CC.isGrounded)\n {\n _MoveDirection = new Vector3(Input.GetAxis(\"Horizontal\"), 0, Input.GetAxis(\"Vertical\"));\n _MoveDirection = transform.TransformDirection(_MoveDirection);\n _MoveDirection *= _Speed;\n if (Input.GetButton(\"Jump\"))\n _MoveDirection.y = _JumpSpeed;\n }\n\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n _Speed = _SprintSpeed;\n else\n _Speed = _NormalSpeed;\n\n //Apply Movement\n _MoveDirection.y -= _Gravity * Time.deltaTime;\n _CC.Move(_MoveDirection * Time.deltaTime);\n }\n\n public void LockRotation(bool state)\n {\n _LockRotation = state;\n }\n}\n"),
new Tool_QuickStart_Script("Movement_CC_Platformer", "Movement_3D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(CharacterController))]\npublic class Movement_CC_Platformer : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _NormalSpeed = 5, _SprintSpeed = 8;\n [SerializeField] private float _JumpSpeed = 5;\n [SerializeField] private float _Gravity = 20;\n [SerializeField] private bool _ZMovementActive = false;\n \n private Vector3 _MoveDirection = Vector3.zero;\n private float _Speed;\n private CharacterController _CC;\n\n void Start()\n {\n _CC = GetComponent<CharacterController>();\n }\n\n void Update()\n {\n //Movement\n if (_CC.isGrounded)\n {\n float verticalmovement = 0;\n if (_ZMovementActive)\n verticalmovement = Input.GetAxis(\"Vertical\");\n\n _MoveDirection = new Vector3(Input.GetAxis(\"Horizontal\"), 0, verticalmovement);\n _MoveDirection = transform.TransformDirection(_MoveDirection);\n _MoveDirection *= _Speed;\n if (Input.GetButton(\"Jump\"))\n _MoveDirection.y = _JumpSpeed;\n }\n\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n _Speed = _SprintSpeed;\n else\n _Speed = _NormalSpeed;\n\n //Apply Movement\n _MoveDirection.y -= _Gravity * Time.deltaTime;\n _CC.Move(_MoveDirection * Time.deltaTime);\n }\n}\n"),
new Tool_QuickStart_Script("Movement_CC_TopDown", "Movement_3D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(CharacterController))]\npublic class Movement_CC_TopDown : MonoBehaviour\n{\n //Movement\n [Header(\"Settings Camera\")]\n [SerializeField] private Camera _Camera;\n [Header(\"Settings\")]\n [SerializeField] private float _NormalSpeed = 5;\n [SerializeField] private float _SprintSpeed = 8;\n [SerializeField] private float _JumpSpeed = 5;\n [SerializeField] private float _Gravity = 20;\n [SerializeField] private bool _MovementRelativeToRotation = false;\n\n private float _Speed = 0;\n private Vector3 _MoveDirection = Vector3.zero;\n private CharacterController _CC;\n\n void Start()\n {\n _CC = GetComponent<CharacterController>();\n }\n\n void Update()\n {\n //Movement\n if (_CC.isGrounded)\n {\n _MoveDirection = new Vector3(Input.GetAxis(\"Horizontal\"), 0, Input.GetAxis(\"Vertical\"));\n if (_MovementRelativeToRotation)\n _MoveDirection = transform.TransformDirection(_MoveDirection);\n _MoveDirection *= _Speed;\n if (Input.GetButton(\"Jump\"))\n _MoveDirection.y = _JumpSpeed;\n }\n\n _MoveDirection.y -= _Gravity * Time.deltaTime;\n _CC.Move(_MoveDirection * Time.deltaTime);\n\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n _Speed = _SprintSpeed;\n else\n _Speed = _NormalSpeed;\n\n Ray cameraRay = _Camera.ScreenPointToRay(Input.mousePosition);\n Plane groundPlane = new Plane(Vector3.up, Vector3.zero);\n float rayLength;\n if (groundPlane.Raycast(cameraRay, out rayLength))\n {\n Vector3 pointToLook = cameraRay.GetPoint(rayLength);\n transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));\n }\n }\n\n public void SetCamera(Camera cameraobj)\n {\n _Camera = cameraobj;\n }\n}\n"),
new Tool_QuickStart_Script("Movement_FreeCamera", "Movement_3D_Camera", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Movement_FreeCamera : MonoBehaviour\n{\n [SerializeField] private float _Speed = 5;\n [SerializeField] private float _SprintSpeed = 8;\n\n private float _CurrentSpeed;\n\n void Start()\n {\n Cursor.visible = false;\n Cursor.lockState = CursorLockMode.Locked;\n }\n\n void Update()\n {\n if (Input.GetKey(KeyCode.LeftShift))\n _CurrentSpeed = _SprintSpeed;\n else\n _CurrentSpeed = _Speed;\n\n float xas = Input.GetAxis(\"Horizontal\");\n float zas = Input.GetAxis(\"Vertical\");\n\n transform.Translate(new Vector3(xas,0, zas) * _CurrentSpeed * Time.deltaTime);\n\n float mousex = Input.GetAxis(\"Mouse X\");\n float mousey = Input.GetAxis(\"Mouse Y\");\n transform.eulerAngles += new Vector3(-mousey, mousex, 0);\n }\n}\n"),
new Tool_QuickStart_Script("Movement_RB_FirstPerson", "Movement_3D", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[RequireComponent(typeof(Rigidbody))]\npublic class Movement_RB_FirstPerson : MonoBehaviour\n{\n [Header(\"Set Refference\")]\n [SerializeField] private Transform _Head = null;\n\n [Header(\"Settings\")]\n [SerializeField] private float _MovementSpeed = 5;\n [SerializeField] private float _JumpSpeed = 5;\n [SerializeField] private float _CameraSensitivity = 1;\n\n private Vector2 _LookRot = new Vector2(90,0);\n private Rigidbody _RB;\n private bool _Grounded;\n\n void Start()\n {\n Cursor.lockState = CursorLockMode.Locked;\n Cursor.visible = false;\n\n _RB = GetComponent<Rigidbody>();\n }\n\n void Update()\n {\n //Check Grounded\n _Grounded = Physics.CheckSphere(new Vector3(transform.position.x, transform.position.y - 1, transform.position.z), 0.4f);\n\n //Movement\n float x = Input.GetAxisRaw(\"Horizontal\") * _MovementSpeed;\n float y = Input.GetAxisRaw(\"Vertical\") * _MovementSpeed;\n\n //Jump\n if (Input.GetKeyDown(KeyCode.Space) && _Grounded)\n _RB.velocity = new Vector3(_RB.velocity.x, _JumpSpeed, _RB.velocity.z);\n\n //Apply Movement\n Vector3 move = transform.right * x + transform.forward * y;\n _RB.velocity = new Vector3(move.x, _RB.velocity.y, move.z);\n\n //Look around\n _LookRot.x += Input.GetAxis(\"Mouse X\") * _CameraSensitivity;\n _LookRot.y += Input.GetAxis(\"Mouse Y\") * _CameraSensitivity;\n _LookRot.y = Mathf.Clamp(_LookRot.y, -90, 90);\n\n transform.localRotation = Quaternion.AngleAxis(_LookRot.x, Vector3.up);\n _Head.transform.localRotation = Quaternion.AngleAxis(_LookRot.y, Vector3.left);\n }\n}\n"),
new Tool_QuickStart_Script("MVD_Namespace", "", "wip", "using UnityEngine;\nusing System.Collections;\n\nnamespace MVD\n{\n public class mvd : MonoBehaviour\n {\n\n //Movement\n public static void Movement_2D_Platformer(float speed, float shiftspeed, Rigidbody rigidbody, float jumpspeed, float groundcheck, LayerMask groundlayer, Transform playertransform)\n {\n float currentspeed;\n\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n currentspeed = shiftspeed;\n else\n currentspeed = speed;\n\n //Jumping\n if (Input.GetButtonDown(\"Jump\") && IsGrounded(groundcheck, groundlayer, playertransform))\n rigidbody.AddForce(new Vector2(0, jumpspeed));\n\n //Apply Movement\n rigidbody.velocity = new Vector2(Input.GetAxis(\"Horizontal\") * currentspeed, rigidbody.velocity.y);\n }\n static bool IsGrounded(float groundcheck, LayerMask groundlayer, Transform playertransform)\n {\n RaycastHit2D hit = Physics2D.Raycast(playertransform.position, Vector2.down, groundcheck, groundlayer);\n if (hit.collider != null)\n {\n return true;\n }\n return false;\n }\n public static void Movement_2D_TopDown(float speed, float shiftspeed, Rigidbody rigidbody)\n {\n float currentspeed;\n\n //Sprint\n if (Input.GetKey(KeyCode.LeftShift))\n currentspeed = shiftspeed;\n else\n currentspeed = speed;\n\n //Apply Movement\n rigidbody.velocity = new Vector2(Input.GetAxis(\"Horizontal\") * currentspeed, Input.GetAxis(\"Vertical\") * currentspeed);\n\n }\n public static void Movement_FreeCamera(float speed, float shiftspeed, Transform cameraobj)\n {\n Cursor.visible = false;\n Cursor.lockState = CursorLockMode.Locked;\n\n float _CurrentSpeed;\n\n if (Input.GetKey(KeyCode.LeftShift))\n _CurrentSpeed = shiftspeed;\n else\n _CurrentSpeed = speed;\n\n float xas = Input.GetAxis(\"Horizontal\");\n float zas = Input.GetAxis(\"Vertical\");\n\n cameraobj.Translate(new Vector3(xas, 0, zas) * _CurrentSpeed * Time.deltaTime);\n\n float mousex = Input.GetAxis(\"Mouse X\");\n float mousey = Input.GetAxis(\"Mouse Y\");\n cameraobj.transform.eulerAngles += new Vector3(-mousey, mousex, 0);\n }\n\n\n \n }\n}\n"),
new Tool_QuickStart_Script("ObjectPool", "ObjectPool", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ObjectPool : MonoBehaviour\n{\n [SerializeField] private ObjectPool_Pool[] _ObjectPools = null;\n private List<Transform> _Parents = new List<Transform>();\n\n private void Awake()\n {\n GameObject emptyobject = GameObject.CreatePrimitive(PrimitiveType.Cube);\n Destroy(emptyobject.GetComponent<MeshRenderer>());\n Destroy(emptyobject.GetComponent<BoxCollider>());\n\n for (int i = 0; i < _ObjectPools.Length; i++)\n {\n //Create parent\n GameObject poolparent = Instantiate(emptyobject, transform.position, Quaternion.identity);\n Destroy(poolparent.GetComponent<MeshRenderer>());\n Destroy(poolparent.GetComponent<BoxCollider>());\n\n //Set parent\n poolparent.transform.parent = transform;\n poolparent.transform.name = \"Pool_\" + _ObjectPools[i]._Name;\n _Parents.Add(poolparent.transform);\n\n //Create objects\n for (int o = 0; o < _ObjectPools[i]._Amount; o++)\n {\n GameObject obj = (GameObject)Instantiate(_ObjectPools[i]._Prefab);\n obj.transform.parent = poolparent.transform;\n obj.transform.position = new Vector2(9999, 9999);\n obj.SetActive(false);\n _ObjectPools[i]._Objects.Add(obj);\n }\n }\n Destroy(emptyobject);\n }\n\n //GetObject\n public GameObject GetObject(string objname)\n {\n int id = FindObjectPoolID(objname, false);\n return GetObject(id, true);\n }\n public GameObject GetObject(GameObject obj)\n {\n int id = FindObjectPoolID(obj);\n return GetObject(id, true);\n }\n public GameObject GetObjectPrefabName(string prefabname)\n {\n int id = FindObjectPoolID(prefabname, true);\n return GetObject(id, true);\n }\n\n //GetObject/setactive\n public GameObject GetObject(string objname, bool setactive)\n {\n int id = FindObjectPoolID(objname, false);\n return GetObject(id, setactive);\n }\n public GameObject GetObject(GameObject obj, bool setactive)\n {\n int id = FindObjectPoolID(obj);\n return GetObject(id, setactive);\n }\n public GameObject GetObjectPrefabName(string prefabname, bool setactive)\n {\n int id = FindObjectPoolID(prefabname, true);\n return GetObject(id, setactive);\n }\n\n public GameObject GetObject(int id, bool setactive)\n {\n GameObject freeObject = null;\n bool checkfreeobj = false;\n\n for (int i = 0; i < _ObjectPools[id]._Objects.Count; i++)\n {\n if (!_ObjectPools[id]._Objects[i].activeInHierarchy)\n {\n _ObjectPools[id]._Objects[i].transform.position = new Vector3(999, 999, 999);\n _ObjectPools[id]._Objects[i].SetActive(setactive);\n freeObject = _ObjectPools[id]._Objects[i];\n return freeObject;\n }\n }\n\n if (!checkfreeobj)\n {\n _ObjectPools[id]._Objects.Clear();\n freeObject = (GameObject)Instantiate(_ObjectPools[id]._Prefab, new Vector3(999,999,999), Quaternion.identity);\n freeObject.transform.parent = _Parents[id];\n freeObject.SetActive(setactive);\n _ObjectPools[id]._Objects.Add(freeObject);\n return freeObject;\n }\n\n Debug.Log(\"No Object Found\");\n return null;\n }\n\n public List<GameObject> GetAllObjects(GameObject objtype)\n {\n int id = FindObjectPoolID(objtype);\n return _ObjectPools[id]._Objects;\n }\n\n private int FindObjectPoolID(GameObject obj)\n {\n int id = 0;\n for (int i = 0; i < _ObjectPools.Length; i++)\n {\n if (obj == _ObjectPools[i]._Prefab)\n {\n id = i;\n }\n }\n return id;\n }\n private int FindObjectPoolID(string objname, bool isprefab)\n {\n for (int i = 0; i < _ObjectPools.Length; i++)\n {\n if (isprefab)\n if (objname == _ObjectPools[i]._Prefab.name)\n {\n return i;\n }\n else\n if (objname == _ObjectPools[i]._Name)\n {\n return i;\n }\n }\n Debug.Log(objname + \" Not Found\");\n return 0;\n }\n}\n\n[System.Serializable]\npublic class ObjectPool_Pool\n{\n public string _Name;\n public GameObject _Prefab;\n public int _Amount;\n [HideInInspector] public List<GameObject> _Objects;\n}\n"),
new Tool_QuickStart_Script("ObjectPoolSimple", "ObjectPool", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ObjectPoolSimple : MonoBehaviour\n{\n public GameObject prefabGameObject;\n public int pooledAmount;\n\n [HideInInspector] public List<GameObject> objects;\n\n void Awake()\n {\n for (int i = 0; i < pooledAmount; i++)\n {\n GameObject obj = (GameObject)Instantiate(prefabGameObject);\n obj.transform.parent = gameObject.transform;\n obj.SetActive(false);\n objects.Add(obj);\n }\n }\n}\n\n\n/* Use Pool\n \n [SerializeField]private ObjectPoolSimple _ObjectPool;\n\n private void Spawn() {\n for (int i = 0; i < _ObjectPool.objects.Count; i++) {\n if (!_ObjectPool.objects[i].activeInHierarchy) {\n _ObjectPool.objects[i].transform.position = new Vector3(0,0,0);\n _ObjectPool.objects[i].transform.rotation = Quaternion.Euler(0, 0, 0);\n _ObjectPool.objects[i].SetActive(true);\n break;\n }\n }\n }\n*/\n"),
new Tool_QuickStart_Script("OnCollision", "Collision_Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\n\npublic class OnCollision : MonoBehaviour\n{\n private enum Options {OnTriggerEnter, OnTriggerExit, OnTriggerStay, OnCollisionEnter, OnCollisionExit, OnCollisionStay, OnAll};\n [SerializeField] private LayerMask _LayerMask = ~0;\n [SerializeField] private Options _Option = Options.OnAll;\n [SerializeField] private string _Tag = \"\";\n [SerializeField] private UnityEvent _Event = null;\n\n private bool _HasTag;\n\n private void Start()\n {\n if (_Tag != \"\" || _Tag != null)\n _HasTag = true;\n }\n\n private void Action(Collider other)\n {\n if (_HasTag)\n if (other.CompareTag(_Tag) && other.gameObject.layer == _LayerMask)\n _Event.Invoke();\n }\n private void Action(Collision other)\n {\n if (_HasTag)\n if (other.gameObject.CompareTag(_Tag) && other.gameObject.layer == _LayerMask)\n _Event.Invoke();\n }\n\n private void OnTriggerEnter(Collider other)\n {\n if (_Option == Options.OnTriggerEnter || _Option == Options.OnAll)\n Action(other);\n }\n private void OnTriggerExit(Collider other)\n {\n if (_Option == Options.OnTriggerExit || _Option == Options.OnAll)\n Action(other);\n }\n private void OnTriggerStay(Collider other)\n {\n if (_Option == Options.OnTriggerStay || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionEnter(Collision other)\n {\n if (_Option == Options.OnCollisionEnter || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionExit(Collision other)\n {\n if (_Option == Options.OnCollisionExit || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionStay(Collision other)\n {\n if (_Option == Options.OnCollisionStay || _Option == Options.OnAll)\n Action(other);\n }\n}\n"),
new Tool_QuickStart_Script("OnCollision2D", "Collision_2D_Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.Events;\n\npublic class OnCollision2D : MonoBehaviour\n{\n private enum Options {OnTriggerEnter, OnTriggerExit, OnTriggerStay, OnCollisionEnter, OnCollisionExit, OnCollisionStay, OnAll};\n [SerializeField] private LayerMask _LayerMask = ~0;\n [SerializeField] private Options _Option = Options.OnAll;\n [SerializeField] private string _Tag = \"\";\n [SerializeField] private UnityEvent _Event = null;\n\n private bool _HasTag;\n\n private void Start()\n {\n if (_Tag != \"\" || _Tag != null)\n _HasTag = true;\n }\n\n private void Action(Collider2D other)\n {\n if (_HasTag)\n if (other.CompareTag(_Tag) && other.gameObject.layer == _LayerMask)\n _Event.Invoke();\n }\n private void Action(Collision2D other)\n {\n if (_HasTag)\n if (other.gameObject.CompareTag(_Tag) && other.gameObject.layer == _LayerMask)\n _Event.Invoke();\n }\n\n private void OnTriggerEnter2D(Collider2D other)\n {\n if (_Option == Options.OnTriggerEnter || _Option == Options.OnAll)\n Action(other);\n }\n private void OnTriggerExit2D(Collider2D other)\n {\n if (_Option == Options.OnTriggerExit || _Option == Options.OnAll)\n Action(other);\n }\n private void OnTriggerStay2D(Collider2D other)\n {\n if (_Option == Options.OnTriggerStay || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionEnter2D(Collision2D other)\n {\n if (_Option == Options.OnCollisionEnter || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionExit2D(Collision2D other)\n {\n if (_Option == Options.OnCollisionExit || _Option == Options.OnAll)\n Action(other);\n }\n private void OnCollisionStay2D(Collision2D other)\n {\n if (_Option == Options.OnCollisionStay || _Option == Options.OnAll)\n Action(other);\n }\n}\n"),
new Tool_QuickStart_Script("PauseMenu", "Menu_Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.SceneManagement;\n\npublic class PauseMenu : MonoBehaviour\n{\n [SerializeField] private GameObject _PauseMenu;\n\n void Update()\n {\n if(Input.GetKeyDown(KeyCode.Escape))\n {\n _PauseMenu.SetActive(!_PauseMenu.activeSelf);\n\n if (_PauseMenu.activeSelf)\n Time.timeScale = 0;\n else\n Time.timeScale = 1;\n }\n }\n\n public void LoadScene(int sceneid)\n {\n SceneManager.LoadScene(sceneid);\n Time.timeScale = 1;\n }\n\n public void LoadScene(string scenename)\n {\n SceneManager.LoadScene(scenename);\n Time.timeScale = 1;\n }\n\n public void Resume()\n {\n _PauseMenu.SetActive(false);\n Time.timeScale = 1;\n }\n}\n"),
new Tool_QuickStart_Script("PosToPos", "Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PosToPos : MonoBehaviour\n{\n [SerializeField] private Transform _GotoPosition = null;\n [SerializeField] private float _Speed = 0;\n\n private bool _Activated;\n\n void Update()\n {\n if (_Activated)\n transform.position = Vector3.MoveTowards(transform.position, _GotoPosition.position, _Speed);\n }\n\n public void StartMoving()\n {\n _Activated = true;\n }\n}\n"),
new Tool_QuickStart_Script("Read_ExcelFile", "Read_Excel_File", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Read_ExcelFile : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n"),
new Tool_QuickStart_Script("ReadAudioFile", "Read_File_Audio", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class ReadAudioFile : MonoBehaviour\n{\n [Header(\"Settings\")]\n private AudioSource _AudioScource = null;\n private bool _PlayOnStart = true;\n\n [Header(\"Info\")]\n public float[] Samples = new float[512];\n public float[] FreqBand = new float[8];\n public float[] BandBuffer = new float[8];\n public float[] BufferDecrease = new float[8];\n\n void Start()\n {\n if (_AudioScource == null)\n _AudioScource = GetComponent<AudioSource>();\n\n if (_PlayOnStart)\n _AudioScource.Play();\n }\n\n void Update()\n {\n GetSpectrumAudioSource();\n MakeFrequencyBands();\n UpdateBandBuffer();\n }\n\n void GetSpectrumAudioSource()\n {\n _AudioScource.GetSpectrumData(Samples, 0, FFTWindow.Blackman);\n }\n\n void UpdateBandBuffer()\n {\n for (int i = 0; i < 8; i++)\n {\n if (FreqBand[i] > BandBuffer[i])\n {\n BandBuffer[i] = FreqBand[i];\n BufferDecrease[i] = 0.005f;\n }\n if (FreqBand[i] < BandBuffer[i])\n {\n BandBuffer[i] -= BufferDecrease[i];\n BufferDecrease[i] *= 1.2f;\n }\n }\n }\n\n void MakeFrequencyBands()\n {\n float average = 0;\n int count = 0;\n\n for (int i = 0; i < 8; i++)\n {\n int sampleCount = (int)Mathf.Pow(2, i) * 2;\n\n if (i == 7)\n sampleCount += 2;\n\n for (int j = 0; j < sampleCount; j++)\n {\n average += Samples[count] * (count + 1);\n count++;\n }\n\n average /= count;\n FreqBand[i] = average * 10;\n }\n }\n}\n"),
new Tool_QuickStart_Script("ReadTwitchChat", "Networking", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System;\nusing System.ComponentModel;\nusing System.Net.Sockets;\nusing System.IO;\n\npublic class ReadTwitchChat : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _RefreshConnectionTimer = 60;\n private float _Timer;\n\n [Header(\"Twitch\")]\n private TcpClient twitchClient;\n private StreamReader reader;\n private StreamWriter writer;\n\n [SerializeField] private string _Username = \"\"; //Twitch user name\n [SerializeField] private string _OauthToken = \"\"; //Get token from https://twitchapps.com/tmi\n [SerializeField] private string _Channelname = \"\"; //Twitch channel name\n\n void Start()\n {\n Connect();\n }\n\n void Update()\n {\n //Check connection\n if (!twitchClient.Connected)\n Connect();\n\n _Timer -= 1 * Time.deltaTime;\n if (_Timer <= 0)\n {\n Connect();\n _Timer = _RefreshConnectionTimer;\n }\n\n ReadChat();\n }\n\n private void Connect()\n {\n twitchClient = new TcpClient(\"irc.chat.twitch.tv\", 6667);\n reader = new StreamReader(twitchClient.GetStream());\n writer = new StreamWriter(twitchClient.GetStream());\n\n writer.WriteLine(\"PASS \" + _OauthToken);\n writer.WriteLine(\"NICK \" + _Username);\n writer.WriteLine(\"USER \" + _Username + \" 8 * :\" + _Username);\n writer.WriteLine(\"JOIN #\" + _Channelname);\n\n writer.Flush();\n }\n\n private void ReadChat()\n {\n if (twitchClient.Available > 0)\n {\n var message = reader.ReadLine();\n\n if (message.Contains(\"PRIVMSG\"))\n {\n //Split\n var splitPoint = message.IndexOf(\"!\", 1);\n var chatName = message.Substring(0, splitPoint);\n\n //Name\n chatName = chatName.Substring(1);\n\n //Message\n splitPoint = message.IndexOf(\":\", 1);\n message = message.Substring(splitPoint + 1);\n print(string.Format(\"{0}: {1}\", chatName, message));\n\n if (message.ToLower().Contains(\"example\"))\n {\n Debug.Log(\"<color=green>\" + chatName + \" has used the command example </color>\");\n }\n }\n }\n }\n\n}\n"),
new Tool_QuickStart_Script("ReadWrite_TextFile", "Read_Write_File", "stable", "using UnityEngine;\nusing System.IO;\n\npublic class ReadWrite_TextFile : MonoBehaviour\n{\n [SerializeField] private string _Path = \"\";\n [SerializeField] private string _FileName = \"ExampleTextFile\";\n\n [Header(\"Example\")]\n [SerializeField] private string _Message = \"Test Message\";\n\n void Start()\n {\n if (_Path == \"\")\n {\n _Path = \"Assets/\" + _FileName;\n }\n\n WriteTextFile();\n ReadTextFile();\n }\n\n public void ReadTextFile()\n {\n StreamReader reader = new StreamReader(_Path + \".txt\");\n Debug.Log(\"Read Result: \" + reader.ReadToEnd());\n reader.Close();\n }\n\n public void WriteTextFile()\n {\n StreamWriter writer = new StreamWriter(_Path + \".txt\", true);\n writer.WriteLine(_Message);\n writer.Close();\n Debug.Log(\"Write Complete\");\n }\n}\n"),
new Tool_QuickStart_Script("Rotation", "Practical", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Rotation : MonoBehaviour\n{\n [SerializeField] private Vector3 _RotationSpeed = Vector3.zero;\n\n void Update()\n {\n transform.Rotate(new Vector3(_RotationSpeed.x, _RotationSpeed.y, _RotationSpeed.z) * Time.deltaTime);\n }\n}\n"),
new Tool_QuickStart_Script("SaveLoad_JSON", "Json_Save_Load", "stable", "using System.Collections.Generic;\nusing System.IO;\nusing UnityEngine;\n\npublic class SaveLoad_JSON : MonoBehaviour\n{\n private Json_SaveData _SaveData = new Json_SaveData();\n\n void Start()\n {\n LoadData();\n }\n\n public void SaveData()\n {\n string jsonData = JsonUtility.ToJson(_SaveData, true);\n File.WriteAllText(Application.persistentDataPath + \"/SaveData.json\", jsonData);\n }\n public void LoadData()\n {\n try\n {\n string dataAsJson = File.ReadAllText(Application.persistentDataPath + \"/SaveData.json\");\n _SaveData = JsonUtility.FromJson<Json_SaveData>(dataAsJson);\n }\n catch\n {\n SaveData();\n }\n }\n public Json_SaveData GetSaveData()\n {\n return _SaveData;\n }\n public void CreateNewSave()\n {\n Json_ExampleData newsave = new Json_ExampleData();\n newsave.exampleValue = 10;\n _SaveData.saveData.Add(newsave);\n }\n}\n\n[System.Serializable]\npublic class Json_SaveData\n{\n public List <Json_ExampleData> saveData = new List<Json_ExampleData>();\n}\n[System.Serializable]\npublic class Json_ExampleData\n{\n public float exampleValue = 0;\n}\n"),
new Tool_QuickStart_Script("SaveLoad_XML", "XML_Save_Load", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Xml.Serialization;\nusing System.IO;\n\npublic class SaveLoad_XML : MonoBehaviour\n{\n private XML_SaveData _SaveData = new XML_SaveData();\n\n void Start()\n {\n LoadData();\n }\n\n public void SaveData()\n {\n XmlSerializer serializer = new XmlSerializer(typeof(XML_SaveData));\n\n using (FileStream stream = new FileStream(Application.persistentDataPath + \"/SaveData.xml\", FileMode.Create))\n {\n serializer.Serialize(stream, _SaveData);\n }\n }\n\n public void LoadData()\n {\n try\n {\n XmlSerializer serializer = new XmlSerializer(typeof(XML_SaveData));\n\n using (FileStream stream = new FileStream(Application.persistentDataPath + \"/SaveData.xml\", FileMode.Open))\n {\n _SaveData = serializer.Deserialize(stream) as XML_SaveData;\n }\n }\n catch\n {\n SaveData();\n }\n }\n\n public XML_SaveData GetSaveData()\n {\n return _SaveData;\n }\n public void CreateNewSave()\n {\n XML_ExampleData newsave = new XML_ExampleData();\n newsave.exampleValue = 10;\n _SaveData.saveData.Add(newsave);\n }\n}\n\n[System.Serializable]\npublic class XML_SaveData\n{\n public List<XML_ExampleData> saveData = new List<XML_ExampleData>();\n}\n[System.Serializable]\npublic class XML_ExampleData\n{\n public float exampleValue = 0;\n}\n"),
new Tool_QuickStart_Script("ScriptebleGameObject", "SO_ScriptebleGameObject", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\n[CreateAssetMenu(fileName = \"Example\", menuName = \"SO/ExampleSO\", order = 1)]\npublic class ScriptebleGameObject : ScriptableObject\n{\n public string examplestring;\n public int exampleint;\n}\n"),
new Tool_QuickStart_Script("SettingsHandler", "Settings_Handler", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing TMPro;\nusing UnityEngine.Audio;\nusing UnityEngine.UI;\nusing System;\n\npublic class SettingsHandler : MonoBehaviour\n{\n [SerializeField] private AudioMixer _AudioMixer = null;\n [SerializeField] private float _Current_Volume = 1;\n\n\n [SerializeField] private TMP_Dropdown _Dropdown_Resolution = null;\n [SerializeField] private TMP_Dropdown _Dropdown_Quality = null;\n [SerializeField] private TMP_Dropdown _Dropdown_Texture = null;\n [SerializeField] private TMP_Dropdown _Dropdown_AA = null;\n [SerializeField] private Slider _Slider_Volume = null;\n\n [SerializeField] private Resolution[] _Resolutions = null;\n\n private void Start()\n {\n _Resolutions = Screen.resolutions;\n _Dropdown_Resolution.ClearOptions();\n List<string> options = new List<string>();\n\n int currentresid = 0;\n for (int i = 0; i < _Resolutions.Length; i++)\n {\n string option = _Resolutions[i].width + \" x \" + _Resolutions[i].height;\n options.Add(option);\n\n if (_Resolutions[i].width == Screen.currentResolution.width && _Resolutions[i].height == Screen.currentResolution.height)\n currentresid = i;\n }\n\n _Dropdown_Resolution.AddOptions(options);\n _Dropdown_Resolution.value = currentresid;\n _Dropdown_Resolution.RefreshShownValue();\n }\n\n // [Display]\n //Resolution\n public void Set_Resolution(int resid)\n {\n Resolution resolution = _Resolutions[resid];\n Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);\n }\n\n //FullScreen\n public void Set_FullScreen(bool isFullscreen)\n {\n Screen.fullScreen = isFullscreen;\n }\n\n //Quiality\n public void Set_Quality(int qualityid)\n {\n if (qualityid != 6) // if the user is not using \n //any of the presets\n QualitySettings.SetQualityLevel(qualityid);\n switch (qualityid)\n {\n case 0: // quality level - very low\n _Dropdown_Texture.value = 3;\n _Dropdown_AA.value = 0;\n break;\n case 1: // quality level - low\n _Dropdown_Texture.value = 2;\n _Dropdown_AA.value = 0;\n break;\n case 2: // quality level - medium\n _Dropdown_Texture.value = 1;\n _Dropdown_AA.value = 0;\n break;\n case 3: // quality level - high\n _Dropdown_Texture.value = 0;\n _Dropdown_AA.value = 0;\n break;\n case 4: // quality level - very high\n _Dropdown_Texture.value = 0;\n _Dropdown_AA.value = 1;\n break;\n case 5: // quality level - ultra\n _Dropdown_Texture.value = 0;\n _Dropdown_AA.value = 2;\n break;\n }\n\n _Dropdown_Quality.value = qualityid;\n }\n\n //Vsync\n //MaxFOS\n //Gama\n\n // [Grapics]\n //Antialiasing\n public void SetAntiAliasing(int aaid)\n {\n QualitySettings.antiAliasing = aaid;\n _Dropdown_Quality.value = 6;\n }\n\n //Shadows\n //ViewDistance\n //TextureQuality\n public void Set_TextureQuality(int textureid)\n {\n QualitySettings.masterTextureLimit = textureid;\n _Dropdown_Quality.value = 6;\n }\n\n //ViolageDistance\n //ViolageDensity\n\n // [Gameplay]\n //SoundAll\n public void Set_Volume(float volume)\n {\n _AudioMixer.SetFloat(\"Volume\", volume);\n _Current_Volume = volume;\n }\n\n //SoundEffects\n //Music\n\n // Quit / Save / Load\n public void ExitGame()\n {\n Application.Quit();\n }\n public void SaveSettings()\n {\n PlayerPrefs.SetInt(\"QualitySettingPreference\",\n _Dropdown_Quality.value);\n PlayerPrefs.SetInt(\"ResolutionPreference\",\n _Dropdown_Resolution.value);\n PlayerPrefs.SetInt(\"TextureQualityPreference\",\n _Dropdown_Texture.value);\n PlayerPrefs.SetInt(\"AntiAliasingPreference\",\n _Dropdown_AA.value);\n PlayerPrefs.SetInt(\"FullscreenPreference\",\n Convert.ToInt32(Screen.fullScreen));\n PlayerPrefs.SetFloat(\"VolumePreference\",\n _Current_Volume);\n }\n public void LoadSettings(int currentResolutionIndex)\n {\n if (PlayerPrefs.HasKey(\"QualitySettingPreference\"))\n _Dropdown_Quality.value =\n PlayerPrefs.GetInt(\"QualitySettingPreference\");\n else\n _Dropdown_Quality.value = 3;\n if (PlayerPrefs.HasKey(\"ResolutionPreference\"))\n _Dropdown_Resolution.value =\n PlayerPrefs.GetInt(\"ResolutionPreference\");\n else\n _Dropdown_Resolution.value = currentResolutionIndex;\n if (PlayerPrefs.HasKey(\"TextureQualityPreference\"))\n _Dropdown_Texture.value =\n PlayerPrefs.GetInt(\"TextureQualityPreference\");\n else\n _Dropdown_Texture.value = 0;\n if (PlayerPrefs.HasKey(\"AntiAliasingPreference\"))\n _Dropdown_AA.value =\n PlayerPrefs.GetInt(\"AntiAliasingPreference\");\n else\n _Dropdown_AA.value = 1;\n if (PlayerPrefs.HasKey(\"FullscreenPreference\"))\n Screen.fullScreen =\n Convert.ToBoolean(PlayerPrefs.GetInt(\"FullscreenPreference\"));\n else\n Screen.fullScreen = true;\n if (PlayerPrefs.HasKey(\"VolumePreference\"))\n _Slider_Volume.value =\n PlayerPrefs.GetFloat(\"VolumePreference\");\n else\n _Slider_Volume.value =\n PlayerPrefs.GetFloat(\"VolumePreference\");\n }\n\n\n //Set\n public void SetDropDown_Resolution(TMP_Dropdown resolutions)\n {\n _Dropdown_Resolution = resolutions;\n }\n public void SetDropDown_Quality(TMP_Dropdown quality)\n {\n _Dropdown_Quality = quality;\n }\n public void SetDropDown_TextureQuality(TMP_Dropdown texturequality)\n {\n _Dropdown_Texture = texturequality;\n }\n public void SetDropDown_AA(TMP_Dropdown aa)\n {\n _Dropdown_AA = aa;\n }\n public void SetSlider_VolumeSlider(Slider volumeslider)\n {\n _Slider_Volume = volumeslider;\n }\n}\n"),
new Tool_QuickStart_Script("Shooting", "Shooting", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Shooting : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] ObjectPool _ObjectPool = null;\n [SerializeField] private GameObject _BulletPrefab = null;\n [SerializeField] private GameObject _ShootPoint = null;\n\n [Header(\"Semi\")]\n [SerializeField] private int _SemiAutomaticBulletAmount = 3;\n [SerializeField] private float _SemiShootSpeed = 0.2f;\n [Header(\"Automatic\")]\n [SerializeField] private float _SecondsBetweenShots = 0.5f;\n\n private enum ShootModes { SingleShot, SemiAutomatic, Automatic }\n [SerializeField] private ShootModes _ShootMode = ShootModes.SingleShot;\n\n private bool _CheckSingleShot;\n private float _Timer;\n private bool _LockShooting;\n\n void Update()\n {\n if (Input.GetMouseButton(0))\n {\n switch (_ShootMode)\n {\n case ShootModes.SingleShot:\n if (!_CheckSingleShot)\n Shoot();\n _CheckSingleShot = true;\n break;\n case ShootModes.SemiAutomatic:\n if (!_CheckSingleShot && !_LockShooting)\n StartCoroutine(SemiShot());\n _CheckSingleShot = true;\n break;\n case ShootModes.Automatic:\n _Timer += 1 * Time.deltaTime;\n if (_Timer >= _SecondsBetweenShots)\n {\n Shoot();\n _Timer = 0;\n }\n break;\n }\n }\n if (Input.GetMouseButtonUp(0))\n {\n _CheckSingleShot = false;\n }\n }\n\n IEnumerator SemiShot()\n {\n _LockShooting = true;\n for (int i = 0; i < _SemiAutomaticBulletAmount; i++)\n {\n Shoot();\n yield return new WaitForSeconds(_SemiShootSpeed);\n }\n _LockShooting = false;\n }\n\n void Shoot()\n {\n GameObject bullet = _ObjectPool.GetObject(_BulletPrefab, true);\n bullet.SetActive(true);\n bullet.transform.position = _ShootPoint.transform.position;\n bullet.transform.rotation = _ShootPoint.transform.rotation;\n }\n}\n"),
new Tool_QuickStart_Script("ShootingRayCast", "Shooting", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing System.Threading;\nusing UnityEngine;\n\npublic class ShootingRayCast : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private float _Damage = 20;\n [SerializeField] private float _ShootDistance = 50;\n [SerializeField] private string _EnemyTag = \"Enemy\";\n\n [Header(\"Semi\")]\n [SerializeField] private int _SemiAutomaticBulletAmount = 3;\n [SerializeField] private float _SemiShootSpeed = 0.2f;\n [Header(\"Automatic\")]\n [SerializeField] private float _SecondsBetweenShots = 0.5f;\n\n private enum ShootModes {SingleShot, SemiAutomatic, Automatic }\n [SerializeField] private ShootModes _ShootMode = ShootModes.SingleShot;\n\n private bool _CheckSingleShot;\n private float _Timer;\n private bool _LockShooting;\n\n void Update()\n {\n if (Input.GetMouseButton(0))\n {\n switch (_ShootMode)\n {\n case ShootModes.SingleShot:\n if (!_CheckSingleShot)\n Shoot();\n _CheckSingleShot = true;\n break;\n case ShootModes.SemiAutomatic:\n if (!_CheckSingleShot && !_LockShooting)\n StartCoroutine(SemiShot());\n _CheckSingleShot = true;\n break;\n case ShootModes.Automatic:\n _Timer += 1 * Time.deltaTime;\n if(_Timer >= _SecondsBetweenShots)\n {\n Shoot();\n _Timer = 0;\n }\n break;\n }\n }\n if(Input.GetMouseButtonUp(0))\n {\n _CheckSingleShot = false;\n }\n }\n\n IEnumerator SemiShot()\n {\n _LockShooting = true;\n for (int i = 0; i < _SemiAutomaticBulletAmount; i++)\n {\n Shoot();\n yield return new WaitForSeconds(_SemiShootSpeed);\n }\n _LockShooting = false;\n }\n\n void Shoot()\n {\n RaycastHit hit;\n if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, _ShootDistance))\n if (hit.transform.tag == _EnemyTag)\n {\n hit.transform.GetComponent<Health>().DoDamage(_Damage);\n }\n }\n}\n"),
new Tool_QuickStart_Script("SpaceShip", "Vehicle_Movement", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class SpaceShip : MonoBehaviour\n{\n // Start is called before the first frame update\n void Start()\n {\n \n }\n\n // Update is called once per frame\n void Update()\n {\n \n }\n}\n"),
new Tool_QuickStart_Script("StringFormats", "String_Format", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing TMPro;\n\npublic class StringFormats : MonoBehaviour\n{\n private enum FormatOptions {DigitalTime };\n [SerializeField] private FormatOptions _FormatOption = FormatOptions.DigitalTime;\n [SerializeField] private TextMeshProUGUI _ExampleText = null;\n\n private float _Timer;\n\n void Update()\n {\n _Timer += 1 * Time.deltaTime;\n\n switch (_FormatOption)\n {\n case FormatOptions.DigitalTime:\n _ExampleText.text = string.Format(\"{0:00}:{1:00}:{2:00}\", Mathf.Floor(_Timer / 3600), Mathf.Floor((_Timer / 60) % 60), _Timer % 60);\n break;\n }\n }\n}\n"),
new Tool_QuickStart_Script("Tool_Commands", "Tool_Commands", "wip", "using UnityEditor.SceneManagement;\nusing System.Collections.Generic;\nusing System.Collections;\nusing UnityEditor;\nusing UnityEngine;\nusing System.IO;\nusing UnityEngine.Events;\n\npublic class Tool_Commands : EditorWindow\n{\n //WIP\n\n //Commands\n private List<string> _ConsoleCommands = new List<string>();\n private List<string> _ConsoleCommandsResults = new List<string>();\n private Tool_CustomCommands _Commands = new Tool_CustomCommands(); \n\n //Search\n private string _Search = \"\";\n private string _InfoText = \"\";\n private string _CommandUsing = \"\";\n private int _ResultID = 0;\n private bool _Loaded = false;\n\n //Menu\n private string[] _MenuOptions = new string[] {\"Commands\", \"Create Command\", \"Menu\" };\n private int _MenuSelected = 0;\n\n private bool _EditMode;\n private int _CommandID;\n\n //Create Command\n private string[] _NewCommandTypes = new string[] {\"Search\", \"Load\", \"Create\" };\n private string[] _NewCommandType_Search = new string[] {\"Scene\", \"Folder\", \"Objects\" };\n private string[] _NewCommandType_Load = new string[] { \"Scene\", \"Folder\", \"Objects\" };\n private string[] _NewCommandType_Create = new string[] { \"Scene\", \"Object\" };\n private int _NewCommandTypesChosen = 0;\n private int _NewCommandTypeOptionChosen = 0;\n private string _NewCommandText = \"\";\n private int _Type;\n\n [MenuItem(\"Tools/Commands wip\")]\n static void Init()\n {\n Tool_Commands window = EditorWindow.GetWindow(typeof(Tool_Commands), false, \"Commands\") as Tool_Commands;\n window.minSize = new Vector2(550, 750);\n window.maxSize = new Vector2(550, 750);\n window.Show();\n window.minSize = new Vector2(50, 50);\n window.maxSize = new Vector2(9999999, 9999999);\n }\n\n //Window / Menu\n void OnGUI()\n { \n if (!_Loaded)\n {\n JsonLoad();\n _Loaded = true;\n }\n\n Menu();\n InfoBox();\n }\n private void Menu()\n {\n HandleInput();\n _MenuSelected = GUILayout.Toolbar(_MenuSelected, _MenuOptions);\n\n switch (_MenuSelected)\n {\n case 0:\n Search();\n ShowConsoleCommands();\n break;\n case 1:\n CreateCommands();\n break;\n case 2:\n MenuVieuw();\n break;\n }\n }\n\n //Input / Search\n private void HandleInput()\n {\n Event e = Event.current;\n switch (e.type)\n {\n case EventType.KeyDown:\n {\n if (Event.current.keyCode == (KeyCode.Return) || Event.current.keyCode == (KeyCode.KeypadEnter))\n {\n DoCommand();\n GUI.FocusControl(\"SearchField\");\n GUIUtility.ExitGUI();\n }\n if (Event.current.keyCode == (KeyCode.DownArrow))\n {\n if (_ResultID == _ConsoleCommandsResults.Count - 1)\n _ResultID = 0;\n else\n _ResultID++;\n }\n if (Event.current.keyCode == (KeyCode.UpArrow))\n {\n if (_ResultID == 0)\n _ResultID = _ConsoleCommandsResults.Count - 1;\n else\n _ResultID--;\n }\n }\n break;\n }\n if (Event.current.keyCode == (KeyCode.Escape))\n {\n this.Close();\n }\n Repaint();\n }\n private void Search()\n {\n //Input\n GUILayout.Label(\"Search: \");\n GUI.FocusControl(\"SearchField\");\n GUI.SetNextControlName(\"SearchField\");\n _Search = GUI.TextField(new Rect(5, 40, 500, 20), _Search.ToLower());\n GUILayout.Space(20);\n }\n\n //Search/Show Commands\n private void ShowConsoleCommands()\n {\n _CommandUsing = \"\";\n _ConsoleCommandsResults.Clear();\n GUILayout.BeginVertical(\"Box\");\n int resultamount = 0;\n string resultcommand = \"\";\n for (int i = 0; i < _ConsoleCommands.Count; i++)\n {\n if (_ConsoleCommands[i].Contains(_Search))\n {\n _ConsoleCommandsResults.Add(_ConsoleCommands[i]);\n resultamount++;\n resultcommand = _ConsoleCommands[i];\n }\n }\n\n if (resultamount > 1)\n {\n for (int i = 0; i < _ConsoleCommandsResults.Count; i++)\n {\n GUILayout.BeginHorizontal();\n if (_ConsoleCommandsResults[i] == _Search)\n {\n _ResultID = 0;\n GUILayout.Label(\">\" + _ConsoleCommandsResults[i]);\n _CommandUsing = _ConsoleCommandsResults[i];\n }\n else\n {\n if (i == _ResultID)\n {\n GUILayout.Label(\">\" + _ConsoleCommandsResults[i]);\n _CommandUsing = _ConsoleCommandsResults[i];\n }\n else\n {\n GUILayout.Label(_ConsoleCommandsResults[i]);\n }\n }\n //GUILayout.Label(_ConsoleCommandsInfoResults[i]);\n GUILayout.EndHorizontal();\n }\n }\n else\n {\n GUILayout.Label(\">\" + resultcommand);\n _CommandUsing = resultcommand;\n }\n if (_ResultID < 0)\n _ResultID = 0;\n if (_ResultID >= _ConsoleCommandsResults.Count - 1)\n _ResultID = _ConsoleCommandsResults.Count - 1;\n GUILayout.EndVertical();\n }\n private void DoCommand()\n {\n //GetCommand\n if (_NewCommandTypes[_Commands._ToolCommands[_ResultID]._Type] == \"Search\")\n DoCommand_Search();\n if (_NewCommandTypes[_Commands._ToolCommands[_ResultID]._Type] == \"Load\")\n DoCommand_Load();\n if (_NewCommandTypes[_Commands._ToolCommands[_ResultID]._Type] == \"Create\")\n DoCommand_Create();\n }\n private void DoCommand_Search()\n {\n if(_Commands._ToolCommands[_ResultID]._CommandData[0] == \"Objects\")\n {\n FindObjects(_Commands._ToolCommands[_ResultID]._CommandData[1]);\n }\n if (_Commands._ToolCommands[_ResultID]._CommandData[0] == \"Folder\")\n {\n //FindObjects(_Commands._ToolCommands[_ResultID]._CommandData[1]);\n string relativePath = _Commands._ToolCommands[_ResultID]._CommandData[1].Substring(_Commands._ToolCommands[_ResultID]._CommandData[1].IndexOf(\"Assets/\"));\n Selection.activeObject = AssetDatabase.LoadAssetAtPath(relativePath, typeof(Object));\n }\n }\n private void DoCommand_Load()\n {\n\n }\n private void DoCommand_Create()\n {\n\n }\n\n //Info Box\n private void InfoBox()\n {\n if (_InfoText != \"\")\n {\n GUILayout.BeginVertical(\"Box\");\n GUILayout.Label(_InfoText);\n GUILayout.EndVertical();\n }\n }\n\n //Create Commands\n private void CreateCommands()\n {\n GUILayout.BeginVertical(\"box\");\n _NewCommandText = EditorGUILayout.TextField(\"New Command: \",_NewCommandText);\n //GetType\n _NewCommandTypesChosen = GUILayout.Toolbar(_NewCommandTypesChosen, _NewCommandTypes);\n switch(_NewCommandTypesChosen)\n {\n case 0: //Seach\n _NewCommandTypeOptionChosen = GUILayout.Toolbar(_NewCommandTypeOptionChosen, _NewCommandType_Search);\n if(_NewCommandTypeOptionChosen >= _NewCommandType_Search.Length)\n _NewCommandTypeOptionChosen--;\n break;\n case 1: //Load\n _NewCommandTypeOptionChosen = GUILayout.Toolbar(_NewCommandTypeOptionChosen, _NewCommandType_Load);\n if (_NewCommandTypeOptionChosen >= _NewCommandType_Load.Length)\n _NewCommandTypeOptionChosen--;\n break;\n case 2: //Create\n _NewCommandTypeOptionChosen = GUILayout.Toolbar(_NewCommandTypeOptionChosen, _NewCommandType_Create);\n if (_NewCommandTypeOptionChosen >= _NewCommandType_Create.Length)\n _NewCommandTypeOptionChosen--;\n break;\n }\n\n if (GUILayout.Button(\"AddCommand\"))\n {\n //Create New Command\n Tool_Command newcommand = new Tool_Command();\n newcommand._TypeOption = _NewCommandTypeOptionChosen;\n\n switch (_NewCommandTypesChosen)\n {\n case 0: //Seach\n newcommand._CommandData.Add(_NewCommandType_Search[_NewCommandTypeOptionChosen]);\n newcommand._CommandData.Add(\"Object Name\");\n break;\n case 1: //Load\n newcommand._CommandData.Add(_NewCommandType_Load[_NewCommandTypeOptionChosen]);\n break;\n case 2: //Create\n newcommand._CommandData.Add(_NewCommandType_Create[_NewCommandTypeOptionChosen]);\n break;\n }\n\n newcommand._CommandName = _NewCommandText;\n newcommand._Type = _NewCommandTypesChosen;\n _Commands._ToolCommands.Add(newcommand);\n\n _NewCommandText = \"\";\n JsonUpdate();\n\n //Edit Command\n _EditMode = true;\n _CommandID = _Commands._ToolCommands.Count -1;\n EditCommand();\n }\n GUILayout.EndVertical();\n\n if (_EditMode)\n EditCommand();\n\n CommandEditList();\n }\n private void EditCommand()\n {\n GUILayout.BeginVertical(\"box\");\n GUILayout.Label(\"Editing Command: \" + _Commands._ToolCommands[_CommandID]._CommandName, EditorStyles.boldLabel);\n GUILayout.BeginVertical();\n if(_NewCommandTypes[_Commands._ToolCommands[_CommandID]._Type] == \"Search\")\n {\n if(_NewCommandType_Search[_Commands._ToolCommands[_CommandID]._TypeOption] == \"Objects\")\n {\n _Commands._ToolCommands[_CommandID]._CommandData[1] = EditorGUILayout.TextField(\"Name Gameobject:\",_Commands._ToolCommands[_CommandID]._CommandData[1]);\n }\n if (_NewCommandType_Search[_Commands._ToolCommands[_CommandID]._TypeOption] == \"Folder\")\n {\n if (GUILayout.Button(\"Get Path\"))\n _Commands._ToolCommands[_CommandID]._CommandData[1] = EditorUtility.OpenFilePanel(\"FolderPath: \", _Commands._ToolCommands[_CommandID]._CommandData[1], \"\");\n }\n }\n if (GUILayout.Button(\"Save\"))\n {\n JsonUpdate();\n _EditMode = false;\n }\n GUILayout.EndVertical();\n GUILayout.EndVertical();\n }\n private void CommandEditList()\n {\n GUILayout.BeginVertical(\"box\");\n GUILayout.BeginHorizontal(\"box\");\n\n GUILayout.BeginHorizontal(\"box\");\n GUILayout.Label(\"Command Name\");\n GUILayout.EndHorizontal();\n\n GUILayout.BeginHorizontal(\"box\");\n GUILayout.Label(\"Edit\");\n GUILayout.EndHorizontal();\n\n GUILayout.BeginHorizontal(\"box\");\n GUILayout.Label(\"Delete\");\n GUILayout.EndHorizontal();\n\n GUILayout.BeginHorizontal(\"box\");\n GUILayout.Label(\"Add to menu\");\n GUILayout.EndHorizontal();\n\n GUILayout.EndHorizontal();\n\n\n\n for (int i = 0; i < _Commands._ToolCommands.Count; i++)\n {\n GUILayout.BeginHorizontal(\"box\");\n GUILayout.Label(_Commands._ToolCommands[i]._CommandName);\n GUILayout.Label(\"Type: \" + _NewCommandTypes[_Commands._ToolCommands[i]._Type] + \" \" + _Commands._ToolCommands[i]._CommandData[0]);\n if (GUILayout.Button(\"Edit\"))\n {\n _CommandID = i;\n _EditMode = true;\n }\n if (GUILayout.Button(\"Delete\"))\n {\n _Commands._ToolCommands.Remove(_Commands._ToolCommands[i]);\n JsonUpdate();\n }\n if (_Commands._ToolCommands[i]._ToMenu)\n {\n if (GUILayout.Button(\"+\", GUILayout.Width(20)))\n {\n _Commands._ToolCommands[i]._ToMenu = !_Commands._ToolCommands[i]._ToMenu;\n JsonUpdate();\n }\n }\n else\n {\n if (GUILayout.Button(\"-\", GUILayout.Width(20)))\n {\n _Commands._ToolCommands[i]._ToMenu = !_Commands._ToolCommands[i]._ToMenu;\n JsonUpdate();\n }\n }\n GUILayout.EndHorizontal();\n }\n GUILayout.EndVertical();\n }\n\n //Menu\n private void MenuVieuw()\n {\n GUILayout.BeginVertical(\"box\");\n for (int i = 0; i < _Commands._ToolCommands.Count; i++)\n {\n if(_Commands._ToolCommands[i]._ToMenu)\n {\n if(GUILayout.Button(_Commands._ToolCommands[i]._CommandName))\n {\n _ResultID = i;\n DoCommand();\n }\n }\n }\n GUILayout.EndVertical();\n }\n\n //Save/Load\n private void JsonLoad()\n {\n try\n {\n _Commands._ToolCommands.Clear();\n _ConsoleCommands.Clear();\n string dataPath = \"Assets/Commands.CommandData\";\n string dataAsJson = File.ReadAllText(dataPath);\n _Commands = JsonUtility.FromJson<Tool_CustomCommands>(dataAsJson);\n\n for (int i = 0; i < _Commands._ToolCommands.Count; i++)\n {\n _ConsoleCommands.Add(_Commands._ToolCommands[i]._CommandName);\n }\n }\n catch\n {\n JsonSave();\n JsonLoad();\n }\n }\n private void JsonSave()\n {\n string json = JsonUtility.ToJson(_Commands);\n File.WriteAllText(\"Assets/Commands.CommandData\", json.ToString());\n }\n private void JsonUpdate()\n {\n JsonSave();\n JsonLoad();\n }\n\n //Find Objects\n private void FindObjects(string searchtext)\n {\n //GameObject[] objects = new GameObject[0];\n\n Selection.activeGameObject = GameObject.Find(searchtext);\n }\n\n}\n\n[System.Serializable]\npublic class Tool_CustomCommands\n{\n public List<Tool_Command> _ToolCommands = new List<Tool_Command>();\n}\n\n[System.Serializable]\npublic class Tool_Command\n{\n public string _CommandName = \"\";\n public int _Type = 0;\n public int _TypeOption = 0;\n public string _CommandInfo = \"\";\n public List<string> _CommandData = new List<string>();\n public bool _ToMenu = false;\n}\n"),
new Tool_QuickStart_Script("Tool_CreateHexagonMesh", "Tool_Editor", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\n\npublic class Tool_CreateHexagonMesh : EditorWindow\n{\n private GameObject _CenterObj;\n private List<GameObject> _ObjSaved = new List<GameObject>();\n private int _TotalObjects = 100;\n\n //Hex\n private int _HexLengthX = 10, _HexLengthZ = 10;\n private float _HexSize = 1;\n private float _DistanceBetween = 1;\n\n private bool _Center = true;\n private bool _Invert = false;\n\n [MenuItem(\"Tools/CreateHexagonGrid\")]\n static void Init()\n {\n Tool_CreateHexagonMesh window = (Tool_CreateHexagonMesh)EditorWindow.GetWindow(typeof(Tool_CreateHexagonMesh));\n window.Show();\n }\n\n void OnGUI()\n { \n GUILayout.BeginVertical(\"Box\");\n _CenterObj = (GameObject)EditorGUILayout.ObjectField(\"Center Object\", _CenterObj, typeof(GameObject), true);\n GUILayout.EndVertical();\n\n GUILayout.BeginVertical(\"Box\");\n _HexSize = EditorGUILayout.FloatField(\"Size: \", _HexSize);\n _HexLengthX = EditorGUILayout.IntField(\"Collom: \", _HexLengthX);\n _HexLengthZ = EditorGUILayout.IntField(\"Row: \", _HexLengthZ);\n\n GUILayout.BeginHorizontal(\"Box\");\n if (GUILayout.Button(\"Calculate Total Objects\"))\n _TotalObjects = _HexLengthX * _HexLengthZ;\n EditorGUILayout.LabelField(\"Total: \" + _TotalObjects.ToString());\n GUILayout.EndHorizontal();\n\n _Center = EditorGUILayout.Toggle(\"Center\", _Center);\n _Invert = EditorGUILayout.Toggle(\"Invert: \", _Invert);\n _DistanceBetween = EditorGUILayout.FloatField(\"Distance Between: \", _DistanceBetween);\n GUILayout.EndVertical();\n\n GUILayout.BeginVertical(\"Box\");\n if (GUILayout.Button(\"Create\"))\n {\n if (_CenterObj != null)\n {\n if (_ObjSaved.Count > 0)\n {\n for (int i = 0; i < _ObjSaved.Count; i++)\n {\n DestroyImmediate(_ObjSaved[i]);\n }\n _ObjSaved.Clear();\n }\n\n Vector3 objPos = _CenterObj.transform.position;\n CreateHexagon(new Vector3(_HexLengthX, 0, _HexLengthZ));\n SetParent();\n }\n else\n {\n Debug.Log(\"Center Object not selected!\");\n }\n }\n\n if (GUILayout.Button(\"Destroy\"))\n {\n if (_CenterObj != null)\n {\n for (int i = 0; i < _ObjSaved.Count; i++)\n {\n DestroyImmediate(_ObjSaved[i]);\n }\n _ObjSaved.Clear();\n\n\n int childs = _CenterObj.transform.childCount;\n for (int i = childs -1; i >= 0; i--)\n {\n DestroyImmediate(_CenterObj.transform.GetChild(i).gameObject);\n }\n }\n else\n {\n Debug.Log(\"Center Object not selected!\");\n }\n }\n\n if (GUILayout.Button(\"Confirm\"))\n {\n _ObjSaved.Clear();\n }\n GUILayout.EndVertical();\n }\n\n void CreateHexagon(Vector3 dimentsions)\n {\n Vector3 objPos = _CenterObj.transform.position;\n if (_Center && !_Invert)\n {\n objPos.x -= dimentsions.x * 0.5f * 1.7321f * _HexSize;\n objPos.z -= dimentsions.z * 0.5f * -1.5f * _HexSize;\n }\n if (_Center && _Invert)\n {\n objPos.x -= dimentsions.x * 0.5f * 1.7321f * _HexSize;\n objPos.z += dimentsions.z * 0.5f * -1.5f * _HexSize;\n }\n\n for (int xas = 0; xas < dimentsions.x; xas++)\n {\n CreateHax(new Vector3(objPos.x + 1.7321f * _HexSize * _DistanceBetween * xas, objPos.y, objPos.z));\n for (int zas = 1; zas < dimentsions.z; zas++)\n {\n float offset = 0;\n if (zas % 2 == 1)\n {\n offset = 0.86605f * _HexSize * _DistanceBetween;\n }\n else\n {\n offset = 0;\n }\n if (!_Invert)\n {\n CreateHax(new Vector3(objPos.x + 1.7321f * _HexSize * _DistanceBetween * xas - offset, objPos.y, objPos.z + -1.5f * _HexSize * _DistanceBetween * zas));\n }\n else\n {\n CreateHax(new Vector3(objPos.x + 1.7321f * _HexSize * _DistanceBetween * xas - offset, objPos.y, objPos.z + +1.5f * _HexSize * _DistanceBetween * zas));\n }\n }\n }\n }\n void CreateHax(Vector3 positions)\n {\n Vector3 objPos = _CenterObj.transform.position;\n\n GameObject gridObj = GameObject.CreatePrimitive(PrimitiveType.Cube);\n gridObj.transform.position = new Vector3(positions.x, positions.y, positions.z);\n\n DestroyImmediate(gridObj.GetComponent<BoxCollider>());\n\n float size = _HexSize;\n float width = Mathf.Sqrt(3) * size;\n float height = size * 2f;\n Mesh mesh = new Mesh();\n Vector3[] vertices = new Vector3[7];\n\n for (int i = 0; i < 6; i++)\n {\n float angle_deg = 60 * i - 30;\n float angle_rad = Mathf.Deg2Rad * angle_deg;\n\n vertices[i + 1] = new Vector3(size * Mathf.Cos(angle_rad), 0f, size * Mathf.Sin(angle_rad));\n }\n mesh.vertices = vertices;\n\n mesh.triangles = new int[]\n {\n 2,1,0,\n 3,2,0,\n 4,3,0,\n 5,4,0,\n 6,5,0,\n 1,6,0\n };\n\n Vector2[] uv = new Vector2[7];\n for (int i = 0; i < 7; i++)\n {\n uv[i] = new Vector2(\n (vertices[i].x + -width * .5f) * .5f / size,\n (vertices[i].z + -height * .5f) * .5f / size);\n }\n\n mesh.uv = uv;\n gridObj.GetComponent<MeshFilter>().sharedMesh = mesh;\n\n _ObjSaved.Add(gridObj);\n }\n\n void SetParent()\n {\n for (int i = 0; i < _ObjSaved.Count; i++)\n {\n _ObjSaved[i].transform.parent = _CenterObj.transform;\n }\n }\n}\n"),
new Tool_QuickStart_Script("Tool_FileFinder", "Tool_File_Finder", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEditor;\nusing UnityEngine;\n\npublic class Tool_FileFinder : EditorWindow\n{\n //Tool State / Scrollpos\n int _ToolState = 0;\n int _ToolStateCheck = 1;\n Vector2 _ScrollPos = new Vector2();\n\n //Project\n string _Project_Type = \"\";\n string _Project_Search = \"\";\n string _Project_SearchCheck = \"a\";\n bool _Project_ExcludeMeta = true;\n int _Project_Results = 0;\n int _Project_Total = 0;\n\n //Project > Results\n string[] _SearchResults = new string[0];\n string[] _SearchResultsChange = new string[0];\n\n //Scene\n string _Scene_Search = \"\";\n bool _Scene_InsceneInfo = true;\n\n //Scene > Results\n bool[] _Scene_Objects_Toggle = new bool[0];\n GameObject[] _Scene_Objects = new GameObject[0];\n\n //GetWindow\n [MenuItem(\"Tools/Tool_FileFinder\")]\n public static void ShowWindow()\n {\n EditorWindow.GetWindow(typeof(Tool_FileFinder));\n }\n\n //Menu/HomePage\n void OnGUI()\n {\n _ToolState = GUILayout.Toolbar(_ToolState, new string[] { \"Assets\", \"Scene\" });\n\n if (_ToolState == 0)\n {\n FileFinder_Search();\n FileFinder_SearchProject();\n }\n else\n {\n FileFinder_SceneSearch();\n _Scene_InsceneInfo = EditorGUILayout.Toggle(\"InScene Info\", _Scene_InsceneInfo);\n FileFinder_Scene();\n }\n\n //stop focus when switching\n if(_ToolStateCheck != _ToolState)\n {\n EditorGUI.FocusTextInControl(\"searchproject\");\n _ToolStateCheck = _ToolState;\n } \n }\n\n //Project\n void FileFinder_Search()\n {\n _Project_Search = EditorGUILayout.TextField(\"Search:\", _Project_Search);\n _Project_Type = EditorGUILayout.TextField(\"Type:\", _Project_Type);\n _Project_ExcludeMeta = EditorGUILayout.Toggle(\"Exlude Meta:\", _Project_ExcludeMeta);\n GUILayout.Label(\"(\" + _Project_Results + \"/\" + _Project_Total + \")\");\n\n _Project_Results = 0;\n _Project_Total = 0;\n\n if (_Project_Search != _Project_SearchCheck)\n {\n _SearchResults = System.IO.Directory.GetFiles(\"Assets/\", \"*\" + _Project_Type, System.IO.SearchOption.AllDirectories);\n _SearchResultsChange = _SearchResults;\n _Project_SearchCheck = _Project_Search;\n }\n }\n void FileFinder_SearchProject()\n {\n _ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);\n for (int i = 0; i < _SearchResults.Length; i++)\n {\n if (_SearchResults[i].ToLower().Contains(_Project_Search.ToLower()))\n {\n if(_Project_ExcludeMeta)\n {\n if (!_SearchResults[i].ToLower().Contains(\".meta\"))\n FileFinder_SearchProject_Results(i);\n }\n else\n FileFinder_SearchProject_Results(i);\n }\n _Project_Total++;\n }\n EditorGUILayout.EndScrollView();\n }\n void FileFinder_SearchProject_Results(int id)\n {\n GUILayout.BeginHorizontal(\"Box\");\n GUILayout.Label(_SearchResults[id], GUILayout.Width(Screen.width - 80));\n if (GUILayout.Button(\"Select\", GUILayout.Width(50)))\n {\n Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(_SearchResults[id]);\n }\n GUILayout.EndHorizontal();\n _Project_Results++;\n }\n\n //Scene\n void FileFinder_SceneSearch()\n {\n _Scene_Search = EditorGUILayout.TextField(\"Search:\", _Scene_Search);\n GUILayout.Label(\"(\" + _Project_Results + \"/\" + _Project_Total + \")\");\n\n if (GUILayout.Button(\"Refresh\"))\n {\n _Scene_Objects = new GameObject[0];\n }\n\n _Project_Results = 0;\n _Project_Total = 0;\n\n if (_Scene_Objects.Length == 0)\n {\n _Scene_Objects = FindObjectsOfType<GameObject>();\n _Scene_Objects_Toggle = new bool[_Scene_Objects.Length];\n }\n }\n void FileFinder_Scene()\n {\n _ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);\n try\n {\n for (int i = 0; i < _Scene_Objects.Length; i++)\n {\n if (_Scene_Objects[i].name.ToLower().Contains(_Scene_Search.ToLower()))\n {\n GUILayout.BeginHorizontal(\"Box\");\n _Scene_Objects_Toggle[i] = EditorGUILayout.Foldout(_Scene_Objects_Toggle[i], \"\");\n\n GUILayout.Label(_Scene_Objects[i].name, GUILayout.Width(Screen.width - 80));\n if (GUILayout.Button(\"Select\", GUILayout.Width(50)))\n {\n Selection.activeObject = _Scene_Objects[i];\n }\n\n if (_Scene_Objects_Toggle[i])\n {\n GUILayout.EndHorizontal();\n GUILayout.BeginVertical(\"box\");\n _Scene_Objects[i].name = EditorGUILayout.TextField(\"Name:\", _Scene_Objects[i].name);\n _Scene_Objects[i].transform.position = EditorGUILayout.Vector3Field(\"Position:\", _Scene_Objects[i].transform.position);\n _Scene_Objects[i].transform.eulerAngles = EditorGUILayout.Vector3Field(\"Rotation:\", _Scene_Objects[i].transform.eulerAngles);\n GUILayout.EndVertical();\n GUILayout.BeginHorizontal();\n }\n\n GUILayout.EndHorizontal();\n _Project_Results++;\n }\n _Project_Total++;\n }\n }\n catch\n {\n _Scene_Objects = new GameObject[0];\n }\n EditorGUILayout.EndScrollView();\n }\n\n //wip\n void FileFinder_NameChange()\n {\n _ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);\n for (int i = 0; i < _SearchResults.Length; i++)\n {\n if (_SearchResults[i].ToLower().Contains(_Project_Search.ToLower()))\n {\n GUILayout.BeginHorizontal(\"Box\");\n _SearchResultsChange[i] = EditorGUILayout.TextField(\"Object Name: \", _SearchResultsChange[i]);\n if (GUILayout.Button(\"Save\", GUILayout.Width(50)))\n {\n _SearchResults[i] = _SearchResultsChange[i];\n Debug.Log(_SearchResults[i] + \" to > \" + _SearchResultsChange[i]);\n }\n if (GUILayout.Button(\"Revert\", GUILayout.Width(50)))\n {\n _SearchResultsChange[i] = _SearchResults[i];\n Debug.Log(_SearchResultsChange[i] + \" to > \" + _SearchResults[i]);\n }\n if (GUILayout.Button(\"Select\", GUILayout.Width(50)))\n {\n Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(_SearchResults[i]);\n }\n GUILayout.EndHorizontal();\n _Project_Results++;\n }\n _Project_Total++;\n }\n EditorGUILayout.EndScrollView();\n }\n\n //Enable/Disable\n void OnEnable()\n {\n SceneView.duringSceneGui += this.OnSceneGUI;\n }\n void OnDisable()\n {\n SceneView.duringSceneGui -= this.OnSceneGUI;\n }\n\n //OnSceneGUI\n void OnSceneGUI(SceneView sceneView)\n {\n try\n {\n if (_Scene_InsceneInfo)\n {\n Handles.color = new Color(0, 1, 0, 0.1f);\n for (int i = 0; i < _Scene_Objects.Length; i++)\n {\n if (_Scene_Objects[i].name.ToLower().Contains(_Scene_Search.ToLower()))\n {\n Handles.SphereHandleCap(1, _Scene_Objects[i].transform.position, Quaternion.identity, 3f, EventType.Repaint);\n Handles.Label(_Scene_Objects[i].transform.position, _Scene_Objects[i].name);\n }\n }\n }\n }\n catch { }\n }\n}\n"),
new Tool_QuickStart_Script("Tool_MapEditor", "Tool_Map_Editor", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\nusing UnityEditorInternal;\nusing System.IO;\n\npublic class Tool_MapEditor : EditorWindow\n{\n #region Array Icons\n //Prefab Array\n private GameObject[] _Prefabs = new GameObject[0];\n private string[] _SearchResults = new string[0];\n\n //Array Options\n private string _SearchPrefab = \"\";\n private bool _HideNames = true;\n private float _ButtonSize = 1, _CollomLength = 4;\n\n //Array Selection\n private int _SelectedID = 99999999, _CheckSelectedID = 999999999;\n #endregion\n #region Options\n //Options\n private bool _HideOptions = true;\n private int _OptionsStates = 0, _PlacementStates = 0;\n\n //Placement Option\n private float _PaintSpeed = 1, _PaintTimer = 0;\n private bool _SnapPosActive = false;\n\n //Onscene Options\n private bool _ShowOptionsInScene;\n private int _InScene_SelectedID;\n #endregion\n #region Transform\n //Position\n private Vector3 _MousePos, _SnapPos, _ObjectPos;\n private Vector2 _GridSize = new Vector2(1, 1);\n\n //Rotation/Size\n private float _Rotation, _Size = 1;\n private bool _RandomRot = false;\n private Vector2 _PrevMousePos = new Vector3(0, 0, 0);\n #endregion\n #region Check\n //Check Buttons Event\n private bool _MouseDown, _ShiftDown, _CtrlDown, _ClickMenu;\n #endregion\n #region Other\n //Placement\n private GameObject _ParentObj, _ExampleObj;\n\n //Other\n private Vector2 _ScrollPos1, _ClickPos;\n private Texture2D[] _PrefabIcon = new Texture2D[0];\n #endregion\n\n //Start Window\n [MenuItem(\"Tools/Map Editor %m\")]\n static void Init()\n {\n Tool_MapEditor window = EditorWindow.GetWindow(typeof(Tool_MapEditor), false, \"Tool_MapEditor\") as Tool_MapEditor;\n window.Show();\n }\n\n //Load Objects\n private void Awake()\n {\n Load_Prefabs();\n Load_Prefabs();\n }\n\n //Enable/Disable\n void OnEnable()\n {\n SceneView.duringSceneGui += this.OnSceneGUI;\n SceneView.duringSceneGui += this.OnScene;\n }\n void OnDisable()\n {\n SceneView.duringSceneGui -= this.OnSceneGUI;\n SceneView.duringSceneGui -= this.OnScene;\n DestroyImmediate(_ExampleObj);\n }\n\n //OnGUI ObjectView\n void OnGUI()\n {\n GUILayout.BeginVertical(\"Box\");\n\n //Refresh/Info\n GUILayout.BeginHorizontal();\n if (GUILayout.Button(\"Refresh\", GUILayout.Width(80)))\n {\n FixPreview();\n Load_Prefabs();\n }\n GUILayout.Label(\"Loaded objects: \" + _SearchResults.Length);\n GUILayout.EndHorizontal();\n\n //Windows\n ObjectView_Header();\n ObjectView_Objects();\n ObjectView_Options();\n\n GUILayout.EndVertical();\n }\n private void ObjectView_Header()\n {\n GUILayout.BeginHorizontal();\n _OptionsStates = GUILayout.Toolbar(_OptionsStates, new string[] { \"Icon\", \"Text\" });\n _ButtonSize = EditorGUILayout.Slider(_ButtonSize, 0.25f, 2);\n if (!_HideNames)\n {\n if (GUILayout.Button(\"Hide Names\", GUILayout.Width(100)))\n _HideNames = true;\n }\n else\n {\n if (GUILayout.Button(\"Show Names\", GUILayout.Width(100)))\n _HideNames = false;\n }\n GUILayout.EndHorizontal();\n _SearchPrefab = EditorGUILayout.TextField(\"Search: \", _SearchPrefab);\n }\n private void ObjectView_Objects()\n {\n Color defaultColor = GUI.backgroundColor;\n GUILayout.BeginVertical(\"Box\");\n float calcWidth = 100 * _ButtonSize;\n _CollomLength = position.width / calcWidth;\n int x = 0;\n int y = 0;\n\n //Show/Hide Options\n if (_HideOptions)\n _ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 109));\n else\n {\n if (_PlacementStates == 0)\n _ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 235));\n else\n _ScrollPos1 = GUILayout.BeginScrollView(_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 253));\n }\n\n //Object Icons\n for (int i = 0; i < _SearchResults.Length; i++)\n {\n if (_Prefabs[i] != null && _Prefabs[i].name.ToLower().Contains(_SearchPrefab.ToLower()))\n {\n if (_OptionsStates == 0) //Icons\n {\n //Select Color\n if (_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = new Color(1, 0, 0); }\n\n //Create Button\n GUIContent content = new GUIContent();\n content.image = _PrefabIcon[i];\n GUI.skin.button.imagePosition = ImagePosition.ImageAbove;\n if (!_HideNames)\n content.text = _Prefabs[i].name;\n if (GUI.Button(new Rect(x * 100 * _ButtonSize, y * 100 * _ButtonSize, 100 * _ButtonSize, 100 * _ButtonSize), content))\n if (_SelectedID == i) { _SelectedID = 99999999; _CheckSelectedID = 99999999; DestroyImmediate(_ExampleObj); } else { _SelectedID = i; }\n\n //Reset Button Position\n x++;\n if (x >= _CollomLength - 1)\n {\n y++;\n x = 0;\n }\n GUI.backgroundColor = defaultColor;\n }\n else //Text Buttons\n {\n if (_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = defaultColor; }\n if (GUILayout.Button(_Prefabs[i].name))\n if (_SelectedID == i) { _SelectedID = 99999999; _CheckSelectedID = 99999999; DestroyImmediate(_ExampleObj); } else { _SelectedID = i; }\n GUI.backgroundColor = defaultColor;\n }\n }\n }\n if (_OptionsStates == 0)\n {\n GUILayout.Space(y * 100 * _ButtonSize + 100);\n }\n GUILayout.EndScrollView();\n GUILayout.EndVertical();\n }\n private void ObjectView_Options()\n {\n GUILayout.BeginVertical(\"Box\");\n if (!_HideOptions)\n {\n //Paint Options\n GUILayout.BeginVertical(\"Box\");\n _PlacementStates = GUILayout.Toolbar(_PlacementStates, new string[] { \"Click\", \"Paint\" });\n if (_PlacementStates == 1)\n _PaintSpeed = EditorGUILayout.FloatField(\"Paint Speed: \", _PaintSpeed);\n //Parent Options\n GUILayout.BeginHorizontal();\n _ParentObj = (GameObject)EditorGUILayout.ObjectField(\"Parent Object: \", _ParentObj, typeof(GameObject), true);\n if (_ParentObj != null)\n if (GUILayout.Button(\"Clean Parent\"))\n CleanParent();\n GUILayout.EndHorizontal();\n GUILayout.EndVertical();\n\n //Grid Options\n GUILayout.BeginVertical(\"Box\");\n _GridSize = EditorGUILayout.Vector2Field(\"Grid Size: \", _GridSize);\n _RandomRot = EditorGUILayout.Toggle(\"Random Rotation: \", _RandomRot);\n _SnapPosActive = EditorGUILayout.Toggle(\"Use Grid: \", _SnapPosActive);\n GUILayout.EndVertical();\n }\n //Hide/Show Options\n if (_HideOptions)\n {\n if (GUILayout.Button(\"Show Options\"))\n _HideOptions = false;\n }\n else\n {\n if (GUILayout.Button(\"Hide Options\"))\n _HideOptions = true;\n }\n GUILayout.EndVertical();\n }\n\n //OnSceneGUI\n void OnSceneGUI(SceneView sceneView)\n {\n Event e = Event.current;\n Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);\n RaycastHit hitInfo;\n\n if (Physics.Raycast(worldRay, out hitInfo))\n {\n //Check MousePosition\n _MousePos = hitInfo.point;\n\n //Create Example Object\n if (_SelectedID <= _Prefabs.Length)\n {\n if (_CheckSelectedID != _SelectedID)\n {\n DestroyImmediate(_ExampleObj);\n _ExampleObj = Instantiate(_Prefabs[_SelectedID], hitInfo.point, Quaternion.identity);\n _ExampleObj.layer = LayerMask.NameToLayer(\"Ignore Raycast\");\n for (int i = 0; i < _ExampleObj.transform.childCount; i++)\n {\n _ExampleObj.transform.GetChild(i).gameObject.layer = LayerMask.NameToLayer(\"Ignore Raycast\");\n for (int o = 0; o < _ExampleObj.transform.GetChild(i).childCount; o++)\n {\n _ExampleObj.transform.GetChild(i).GetChild(o).gameObject.layer = LayerMask.NameToLayer(\"Ignore Raycast\");\n }\n }\n _ExampleObj.name = \"Example Object\";\n _CheckSelectedID = _SelectedID;\n }\n }\n\n //Set Example Object Position + Rotation\n if (_ExampleObj != null)\n {\n _ExampleObj.transform.rotation = Quaternion.Euler(0, _Rotation, 0);\n _ExampleObj.transform.localScale = new Vector3(_Size, _Size, _Size);\n if (!e.shift && !e.control)\n {\n if (!_SnapPosActive)\n { _ExampleObj.transform.position = hitInfo.point; }\n else\n { _ExampleObj.transform.position = _SnapPos; }\n }\n }\n\n //Check Buttons Pressed\n if (!Event.current.alt && _SelectedID != 99999999)\n {\n if (Event.current.type == EventType.Layout)\n HandleUtility.AddDefaultControl(0);\n\n //Mouse Button 0 Pressed\n if (Event.current.type == EventType.MouseDown && Event.current.button == 0)\n {\n _MouseDown = true;\n _PaintTimer = _PaintSpeed;\n if (e.mousePosition.y <= 20)\n _ClickMenu = true;\n }\n\n //Mouse Button 0 Released\n if (Event.current.type == EventType.MouseUp && Event.current.button == 0)\n {\n _MouseDown = false;\n _ClickMenu = false;\n }\n\n //Check Shift\n if (e.shift)\n _ShiftDown = true;\n else\n _ShiftDown = false;\n\n //Check Ctrl\n if (e.control)\n _CtrlDown = true;\n else\n _CtrlDown = false;\n\n if (e.shift || e.control)\n {\n if (Event.current.type == EventType.MouseDown && Event.current.button == 0)\n _ClickPos = Event.current.mousePosition;\n }\n\n //Place Object\n if (!_ShiftDown && !_CtrlDown && !_ClickMenu)\n {\n if (_PlacementStates == 0)\n {\n if (Event.current.type == EventType.MouseDown && Event.current.button == 0)\n CreatePrefab(hitInfo.point);\n }\n else\n {\n float timer1Final = _PaintSpeed;\n if (_MouseDown)\n {\n _PaintTimer += 1 * Time.deltaTime;\n if (_PaintTimer >= timer1Final)\n {\n CreatePrefab(hitInfo.point);\n _PaintTimer = 0;\n }\n }\n }\n }\n }\n\n // Draw obj location\n if (_SelectedID != 99999999)\n {\n //Draw Red Cross + Sphere on object location\n Handles.color = new Color(1, 0, 0);\n Handles.DrawLine(new Vector3(hitInfo.point.x - 0.3f, hitInfo.point.y, hitInfo.point.z), new Vector3(hitInfo.point.x + 0.3f, hitInfo.point.y, hitInfo.point.z));\n Handles.DrawLine(new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z - 0.3f), new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z + 0.3f));\n if (_SnapPosActive)\n {\n Handles.SphereHandleCap(1, new Vector3(_SnapPos.x, hitInfo.point.y, _SnapPos.z), Quaternion.identity, 0.1f, EventType.Repaint);\n }\n else\n Handles.SphereHandleCap(1, new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z), Quaternion.identity, 0.1f, EventType.Repaint);\n\n //Check Snap Position\n if (_SnapPosActive)\n {\n Vector2 calc = new Vector2(_MousePos.x / _GridSize.x, _MousePos.z / _GridSize.y);\n Vector2 calc2 = new Vector2(Mathf.RoundToInt(calc.x) * _GridSize.x, Mathf.RoundToInt(calc.y) * _GridSize.y);\n\n _SnapPos = new Vector3(calc2.x, _MousePos.y, calc2.y);\n\n //Draw Grid\n Handles.color = new Color(0, 1, 0);\n float lineLength = 0;\n if (_GridSize.x > _GridSize.y)\n lineLength = _GridSize.x + 1;\n else\n lineLength = _GridSize.y + 1;\n\n for (int hor = 0; hor < 3; hor++)\n {\n Handles.DrawLine(new Vector3(calc2.x - lineLength, hitInfo.point.y, calc2.y - _GridSize.y + _GridSize.y * hor), new Vector3(calc2.x + lineLength, hitInfo.point.y, calc2.y - _GridSize.y + _GridSize.y * hor));\n }\n for (int ver = 0; ver < 3; ver++)\n {\n Handles.DrawLine(new Vector3(calc2.x - _GridSize.x + _GridSize.x * ver, hitInfo.point.y, calc2.y - lineLength), new Vector3(calc2.x - _GridSize.x + _GridSize.x * ver, hitInfo.point.y, calc2.y + lineLength));\n }\n }\n }\n }\n }\n\n //OnScene\n void OnScene(SceneView sceneView)\n {\n //InScene Option Bar\n Handles.BeginGUI();\n if (_ShowOptionsInScene)\n {\n //Option Bar\n GUI.Box(new Rect(0, 0, Screen.width, 22), GUIContent.none);\n _InScene_SelectedID = GUI.Toolbar(new Rect(22, 1, Screen.width / 2 - 30, 20), _InScene_SelectedID, new string[] { \"Settings\", \"Placement\", \"Transform\", \"Grid\" });\n switch (_InScene_SelectedID)\n {\n case 0: //Settings\n GUI.Label(new Rect(Screen.width / 2 - 5, 3, 50, 20), \"Parent: \");\n _ParentObj = (GameObject)EditorGUI.ObjectField(new Rect(Screen.width / 2 + 50, 1, 150, 20), _ParentObj, typeof(GameObject), true);\n if (GUI.Button(new Rect(Screen.width - 110, 1, 90, 20), \"Clean Parent\"))\n {\n CleanParent();\n }\n break;\n case 1: //Placement\n _PlacementStates = GUI.Toolbar(new Rect(Screen.width / 2 - 5, 1, 100, 20), _PlacementStates, new string[] { \"Click\", \"Paint\" });\n _PaintSpeed = EditorGUI.FloatField(new Rect(Screen.width / 2 + 185, 1, 50, 20), _PaintSpeed);\n GUI.Label(new Rect(Screen.width / 2 + 100, 3, 500, 20), \"Paint speed: \");\n break;\n case 2: //Transform\n _Size = EditorGUI.FloatField(new Rect(Screen.width / 2 + 125, 1, 100, 20), _Size);\n break;\n case 3: //Grid\n GUI.Label(new Rect(Screen.width / 2 + 80, 3, 100, 20), \"Grid Size: \");\n _GridSize.x = EditorGUI.FloatField(new Rect(Screen.width / 2 + 150, 1, 50, 20), _GridSize.x);\n _GridSize.y = EditorGUI.FloatField(new Rect(Screen.width / 2 + 200, 1, 50, 20), _GridSize.y);\n GUI.Label(new Rect(Screen.width / 2, 3, 100, 20), \"Enable: \");\n _SnapPosActive = EditorGUI.Toggle(new Rect(Screen.width / 2 + 50, 3, 20, 20), _SnapPosActive);\n break;\n }\n }\n\n //Hotkeys Resize / Rotate\n //Shift+MouseDown = Resize\n Vector2 prevmove = _PrevMousePos - Event.current.mousePosition;\n if (_ShiftDown && _MouseDown)\n {\n _Size = EditorGUI.Slider(new Rect(_ClickPos.x - 15, _ClickPos.y - 40, 50, 20), _Size, 0.01f, 1000000);\n _Size -= (prevmove.x + prevmove.y) * 0.05f;\n GUI.Label(new Rect(_ClickPos.x - 50, _ClickPos.y - 40, 500, 20), \"Size: \");\n }\n //Ctrl+MouseDown = Rotate\n if (_CtrlDown && _MouseDown)\n {\n _Rotation = EditorGUI.Slider(new Rect(_ClickPos.x - 15, _ClickPos.y - 40, 50, 20), _Rotation, -1000000, 1000000);\n _Rotation += prevmove.x + prevmove.y;\n GUI.Label(new Rect(_ClickPos.x - 80, _ClickPos.y - 40, 500, 20), \"Rotation: \");\n }\n _PrevMousePos = Event.current.mousePosition;\n\n //Inscene Show OptionButton\n GUI.color = new Color(1f, 1f, 1f, 1f);\n if (!_ShowOptionsInScene)\n {\n if (GUI.Button(new Rect(1, 1, 20, 20), \" +\"))\n _ShowOptionsInScene = true;\n }\n else\n {\n if (GUI.Button(new Rect(1, 1, 20, 20), \" -\"))\n _ShowOptionsInScene = false;\n }\n Handles.EndGUI();\n }\n\n //Load/Fix\n void Load_Prefabs()\n {\n _SearchResults = System.IO.Directory.GetFiles(\"Assets/\", \"*.prefab\", System.IO.SearchOption.AllDirectories);\n _Prefabs = new GameObject[_SearchResults.Length];\n _PrefabIcon = new Texture2D[_SearchResults.Length];\n\n for (int i = 0; i < _SearchResults.Length; i++)\n {\n Object prefab = null;\n prefab = AssetDatabase.LoadAssetAtPath(_SearchResults[i], typeof(GameObject));\n _Prefabs[i] = prefab as GameObject;\n _PrefabIcon[i] = AssetPreview.GetAssetPreview(_Prefabs[i]);\n }\n }\n void FixPreview()\n {\n Load_Prefabs();\n _SearchResults = System.IO.Directory.GetFiles(\"Assets/\", \"*.prefab\", System.IO.SearchOption.AllDirectories);\n\n for (int i = 0; i < _SearchResults.Length; i++)\n {\n if (_PrefabIcon[i] == null)\n AssetDatabase.ImportAsset(_SearchResults[i]);\n }\n Load_Prefabs();\n }\n\n //Create Prefab/Clean Parent\n void CreatePrefab(Vector3 createPos)\n {\n if (CheckPositionEmpty(true))\n {\n GameObject createdObj = PrefabUtility.InstantiatePrefab(_Prefabs[_SelectedID]) as GameObject;\n createdObj.transform.position = createPos;\n createdObj.transform.localScale = new Vector3(_Size, _Size, _Size);\n\n if (_ParentObj == null)\n {\n _ParentObj = new GameObject();\n _ParentObj.name = \"MapEditor_Parent\";\n }\n\n createdObj.transform.parent = _ParentObj.transform;\n if (_SnapPosActive)\n createdObj.transform.position = _SnapPos;\n else\n createdObj.transform.position = _MousePos;\n if (_RandomRot)\n createdObj.transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);\n else\n createdObj.transform.rotation = Quaternion.Euler(0, _Rotation, 0);\n }\n }\n void CleanParent()\n {\n int childAmount = _ParentObj.transform.childCount;\n int childCalc = childAmount - 1;\n for (int i = 0; i < childAmount; i++)\n {\n DestroyImmediate(_ParentObj.transform.GetChild(childCalc).gameObject);\n childCalc -= 1;\n }\n }\n bool CheckPositionEmpty(bool checky)\n {\n if (_ParentObj != null)\n {\n bool check = true;\n for (int i = 0; i < _ParentObj.transform.childCount; i++)\n {\n if (checky)\n {\n if (_ParentObj.transform.GetChild(i).position.x == _SnapPos.x && _ParentObj.transform.GetChild(i).position.z == _SnapPos.z)\n check = false;\n }\n else\n if (_ParentObj.transform.GetChild(i).position == _SnapPos)\n check = false;\n }\n return check;\n }\n else\n {\n return true;\n }\n }\n}\n"),
new Tool_QuickStart_Script("Tool_Math", "Tool_Math", "wip", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEditor;\n\npublic class Tool_Math : EditorWindow\n{\n string _Search = \"\";\n\n int _Selected = 0;\n int _CheckSelected = 1;\n string[] _Options = new string[]\n {\n \"sin\", \"cos\", \"tan\",\n };\n string[] _Results = new string[]\n {\n \"Mathf.Sin(float);\",\n \"Mathf.Cos(float);\",\n \"Mathf.Tan(float);\",\n };\n\n string _Result;\n private Vector2 _ScrollPos = new Vector2();\n\n [MenuItem(\"Tools/Tool_Math\")]\n public static void ShowWindow()\n {\n EditorWindow.GetWindow(typeof(Tool_Math));\n }\n\n void OnGUI()\n {\n //Result\n GUILayout.Label(\"Result:\");\n EditorGUILayout.TextField(\"\", _Result);\n\n //Check Selected\n if (_Selected != _CheckSelected)\n {\n _Result = _Results[_Selected];\n _CheckSelected = _Selected;\n }\n\n //Seach\n GUILayout.Space(20);\n GUILayout.Label(\"Search Formula:\");\n _Search = EditorGUILayout.TextField(\"\", _Search);\n\n //Search Results\n _ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);\n for (int i = 0; i < _Results.Length; i++)\n {\n if (_Options[i].Contains(_Search))\n if (GUILayout.Button(_Options[i]))\n _Selected = i;\n }\n EditorGUILayout.EndScrollView();\n }\n}\n"),
new Tool_QuickStart_Script("Tool_ScriptToString", "Tool_Editor", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.IO;\nusing UnityEditor;\nusing UnityEngine;\n\npublic class Tool_ScriptToString : EditorWindow\n{\n MonoScript _InputScript;\n string _ScriptOutput = \"\";\n\n private Vector2 _ScrollPos = new Vector2();\n\n [MenuItem(\"Tools/Convert Script to String\")]\n public static void ShowWindow()\n {\n EditorWindow.GetWindow(typeof(Tool_ScriptToString));\n }\n\n void OnGUI()\n {\n if (GUILayout.Button(\"Convert\", GUILayout.Height(30)))\n if(_InputScript != null)\n _ScriptOutput = ConvertScriptToString();\n\n _ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);\n Display_InputOutput();\n Display_StringExample();\n EditorGUILayout.EndScrollView();\n }\n\n private void Display_InputOutput()\n {\n GUILayout.Space(20);\n //Input\n GUILayout.Label(\"Input: \", EditorStyles.boldLabel);\n _InputScript = EditorGUILayout.ObjectField(_InputScript, typeof(MonoScript), false) as MonoScript;\n\n //Output\n GUILayout.Label(\"Output: \", EditorStyles.boldLabel);\n EditorGUILayout.TextField(\"\", _ScriptOutput);\n GUILayout.Space(20);\n }\n\n private void Display_StringExample()\n {\n //Preview\n List<string> output = new List<string>();\n List<string> output2 = new List<string>();\n\n for (int i = 0; i < _ScriptOutput.Length; i++)\n {\n output.Add(System.Convert.ToString(_ScriptOutput[i]));\n }\n\n int begincalc = 0;\n int endcalc = 0;\n\n for (int i = 0; i < output.Count; i++)\n {\n if (i + 1 < output.Count)\n {\n if (output[i] + output[i + 1] == \"\\n\")\n {\n endcalc = i;\n string addstring = \"\";\n for (int j = 0; j < endcalc - begincalc; j++)\n {\n addstring += output[begincalc + j];\n }\n addstring += output[endcalc] + output[endcalc + 1];\n\n output2.Add(addstring);\n endcalc = endcalc + 1;\n begincalc = endcalc + 1;\n }\n }\n }\n\n for (int i = 0; i < output2.Count; i++)\n {\n GUILayout.BeginHorizontal();\n if (output2[i].Contains(\"//\"))\n {\n EditorGUILayout.TextField(\"\", \"x\", GUILayout.MaxWidth(15));\n }\n else\n {\n EditorGUILayout.TextField(\"\", \"\", GUILayout.MaxWidth(15));\n }\n\n EditorGUILayout.TextField(\"\", output2[i]);\n GUILayout.EndHorizontal();\n }\n }\n\n private string ConvertScriptToString()\n {\n string newstring = \"\\\"\";\n string path = GetPath();\n string[] readText = File.ReadAllLines(path);\n\n for (int i = 0; i < readText.Length; i++)\n {\n string newline = \"\";\n for (int j = 0; j < readText[i].Length; j++)\n {\n if(System.Convert.ToString(readText[i][j]) == \"\\\"\")\n newline += \"\\\";\n newline += System.Convert.ToString(readText[i][j]);\n }\n readText[i] = newline + \"\\n\";\n newstring += readText[i];\n }\n\n newstring += \"\\\"\";\n\n return newstring;\n }\n\n private string GetPath()\n {\n string[] filepaths = System.IO.Directory.GetFiles(\"Assets/\", \"*.cs\", System.IO.SearchOption.AllDirectories);\n for (int i = 0; i < filepaths.Length; i++)\n {\n if (filepaths[i].Contains(_InputScript.name + \".cs\"))\n {\n return filepaths[i];\n }\n }\n return \"\";\n }\n}\n"),
new Tool_QuickStart_Script("Turret", "Turret_Shooting", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class Turret : MonoBehaviour\n{\n [Header(\"Settings\")]\n [SerializeField] private Vector2 _MinMaxRange = Vector2.zero;\n [SerializeField] private float _SecondsBetweenShots = 2;\n [SerializeField] private float _Damage = 25;\n [SerializeField] private GameObject _ShootPart = null;\n [SerializeField] private string _Tag = \"Enemy\";\n \n private float _Timer;\n private GameObject _Target;\n\n void Update()\n {\n if (_Target != null)\n {\n _ShootPart.transform.LookAt(_Target.transform.position);\n _Timer += 1 * Time.deltaTime;\n if (_Timer >= _SecondsBetweenShots)\n {\n _Target.GetComponent<Health>().DoDamage(_Damage);\n _Timer = 0;\n }\n }\n else\n {\n _ShootPart.transform.rotation = Quaternion.Euler(90, 0, 0);\n }\n\n _Target = FindEnemy();\n }\n\n public GameObject FindEnemy()\n {\n GameObject[] m_Targets = GameObject.FindGameObjectsWithTag(_Tag);\n GameObject closest = null;\n float distance = Mathf.Infinity;\n Vector3 position = transform.position;\n\n _MinMaxRange.x = _MinMaxRange.x * _MinMaxRange.x;\n _MinMaxRange.y = _MinMaxRange.y * _MinMaxRange.y;\n foreach (GameObject target in m_Targets)\n {\n Vector3 diff = target.transform.position - position;\n float curDistance = diff.sqrMagnitude;\n if (curDistance < distance && curDistance >= _MinMaxRange.x && curDistance <= _MinMaxRange.y)\n {\n closest = target;\n distance = curDistance;\n }\n }\n return closest;\n }\n}\n"),
new Tool_QuickStart_Script("UIEffects", "UI_Effect", "stable", "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.EventSystems;\n\npublic class UIEffects : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler\n{\n private enum UIEffectOptions { Grow, Shrink }\n [SerializeField] private UIEffectOptions _UIEffect = UIEffectOptions.Grow;\n [SerializeField] private Vector3 _MinDefaultMaxSize = new Vector3(0.9f,1f,1.1f);\n [SerializeField] private float _IncreaseSpeed = 1;\n\n private Vector3 _OriginalSize;\n private bool _MouseOver;\n\n void Start()\n {\n _OriginalSize = transform.localScale;\n }\n\n void Update()\n {\n switch (_UIEffect)\n {\n case UIEffectOptions.Grow:\n if (_MouseOver)\n {\n if (transform.localScale.y < _MinDefaultMaxSize.z)\n transform.localScale += new Vector3(_IncreaseSpeed, _IncreaseSpeed, _IncreaseSpeed) * Time.deltaTime;\n }\n else\n if (transform.localScale.y > _OriginalSize.y)\n transform.localScale -= new Vector3(_IncreaseSpeed, _IncreaseSpeed, _IncreaseSpeed) * Time.deltaTime;\n else\n transform.localScale = new Vector3(_OriginalSize.y, _OriginalSize.z, _OriginalSize.z);\n break;\n case UIEffectOptions.Shrink:\n if (_MouseOver)\n {\n if (transform.localScale.y > _MinDefaultMaxSize.x)\n transform.localScale -= new Vector3(_IncreaseSpeed, _IncreaseSpeed, _IncreaseSpeed) * Time.deltaTime;\n }\n else\n if (transform.localScale.y < _OriginalSize.x)\n transform.localScale += new Vector3(_IncreaseSpeed, _IncreaseSpeed, _IncreaseSpeed) * Time.deltaTime;\n else\n transform.localScale = new Vector3(_OriginalSize.x, _OriginalSize.y, _OriginalSize.z);\n break;\n }\n }\n\n public void OnPointerEnter(PointerEventData eventData)\n {\n _MouseOver = true;\n }\n\n public void OnPointerExit(PointerEventData eventData)\n {\n _MouseOver = false;\n }\n}\n")
};
bool[] _AddMultipleScripts = new bool[0];
bool _AddMultipleScriptsActive = false;
int _AddMultipleScripts_SelectAmount = 0;
//Settings
int _CreateSceneOptions = 0;
Vector2 _ScrollPos = new Vector2();
bool _StartUpSearch = false;
//Search
string _Search_Script = "";
string _Search_Tag = "";
string _Search_Window = "";
string[] _Project_Scripts = new string[0];
bool _Search_QuickStartScripts_Toggle = true;
bool _Searcg_ProjectScripts_Toggle = false;
int _Search_ProjectScripts_Results = 0;
int _Search_ProjectScripts_Total = 0;
int _Search_Results = 0;
int _Search_InProject_Results = 0;
//HUD Settings
bool _HUD_EnableLiveEdit = true;
//HUD Tabs
int _HUDTabID;
List<Tool_QuickStartUI_Tab> _HUDTab = new List<Tool_QuickStartUI_Tab>();
//HUD Profiles
enum HUDProfiles { BasicStartMenu, AdvanceStartMenu_wip };
HUDProfiles _HUD_Profiles;
//Other
GameObject _MainCanvas;
RectTransform _MainCanvasRect;
Vector2 _CheckMainCanvasRectSize;
//Tool Mode
int _ToolState = 0;
int _ToolStateCheck = 1;
//FileFinder (FF) ----------------------------------------------
#region FileFinder
string _FF_Type = "";
string _FF_TypeCheck = "";
string _FF_Search = "";
string _FF_SearchCheck = "a";
int _FF_Results = 0;
int _FF_Total = 0;
//Scene
string _FF_Scene_Search = "";
bool _FF_Scene_InsceneInfo = false;
GameObject[] _FF_Scene_Objects = new GameObject[0];
//Results
string[] _FF_SearchResults = new string[0];
#endregion
//Script To String (STS) ----------------------------------------------
#region Script To String
MonoScript _STS_InputScript = null;
string _STS_ScriptOutput = "";
#endregion
//Map Editor (ME) ----------------------------------------------
#region MapEditor
//Prefab Array
GameObject[] _ME_Prefabs = new GameObject[0];
string[] _ME_SearchResults = new string[0];
//Array Options
string _ME_SearchPrefab = "";
bool _ME_HideNames = true;
float _ME_ButtonSize = 1, _ME_CollomLength = 4;
//Array Selection
int _ME_SelectedID = 99999999, _ME_CheckSelectedID = 999999999;
//Options
bool _ME_HideOptions = true;
int _ME_OptionsStates = 0, _ME_PlacementStates = 0;
//Placement Option
float _ME_PaintSpeed = 1, _ME_PaintTimer = 0;
bool _ME_SnapPosActive = false;
//Onscene Options
bool _ME_ShowOptionsInScene;
int _ME_InScene_SelectedID;
//Position
Vector3 _ME_MousePos, _ME_SnapPos, _ME_ObjectPos;
Vector2 _ME_GridSize = new Vector2(1, 1);
//Rotation/Size
float _ME_Rotation, _ME_Size = 1;
bool _ME_RandomRot = false;
Vector2 _ME_PrevMousePos = new Vector3(0,0,0);
//Check Buttons Event
bool _ME_MouseDown, _ME_ShiftDown, _ME_CtrlDown, _ME_ClickMenu;
//Placement
GameObject _ME_ParentObj, _ME_ExampleObj;
Transform _ME_HitObject;
bool _ME_RotateWithObject = false;
//Other
Vector2 _ME_ScrollPos1, _ME_ClickPos;
Texture2D[] _ME_PrefabIcon = new Texture2D[0];
bool _ME_FirstLoad = true;
#endregion
[MenuItem("Tools/Tool_QuickStart %q")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(Tool_QuickStart));
}
//Menu
void OnGUI()
{
GUILayout.Label(_Version);
GUILayout.BeginHorizontal();
if (GUILayout.Button("=", GUILayout.Width(20)))
{
_WindowID = 0;
_SelectWindow = !_SelectWindow;
}
if (GUILayout.Button("?", GUILayout.Width(20)))
{
if (_WindowID == 1)
_WindowID = 0;
else
_WindowID = 1;
_SelectWindow = false;
}
if (_SelectWindow)
{
GUILayout.Label("Tool Navigation");
GUILayout.EndHorizontal();
_Search_Window = EditorGUILayout.TextField("Search: ", _Search_Window);
for (int i = 2; i < _WindowNames.Length; i++)
{
if (_Search_Window == "" || _WindowNames[i].ToLower().Contains(_Search_Window.ToLower()))
if (GUILayout.Button(_WindowNames[i], GUILayout.Height(30))) { _WindowID = i; _SelectWindow = false; _Search_Window = ""; ChangeTab(); }
}
}
else
{
switch (_WindowID)
{
case 0: //Default
//Menu Type
_MenuID = GUILayout.Toolbar(_MenuID, new string[] { "QuickStart", "Scripts", "QuickUI (wip)" });
GUILayout.EndHorizontal();
switch (_MenuID)
{
case 0: //QuickStart
Menu_QuickStart();
break;
case 1: //Scripts
Menu_Scripts();
break;
case 2: //QuickUI
Menu_QuickUI();
break;
}
break;
case 1: //UpdateLog
GUILayout.EndHorizontal();
UpdateLog();
break;
case 2: //FileFinder
GUILayout.EndHorizontal();
FileFinder();
break;
case 3: //ScriptToString
GUILayout.EndHorizontal();
ScriptToString_Menu();
break;
case 4: //MapEditor
GUILayout.EndHorizontal();
MapEditor_Menu();
break;
}
}
}
//Home > QuickStart : Menu
void Menu_QuickStart()
{
//FirstSearch
if(!_StartUpSearch)
{
SearchScripts();
_StartUpSearch = true;
}
//Dimension
_DimensionID = GUILayout.Toolbar(_DimensionID, new string[] { "2D", "3D" });
//Type 2D/3D
switch (_DimensionID)
{
case 0:
_Type2DID = GUILayout.Toolbar(_Type2DID, new string[] { "Platformer", "TopDown", "VisualNovel" });
break;
case 1:
_Type3DID = GUILayout.Toolbar(_Type3DID, new string[] { "FPS", "ThirdPerson", "TopDown", "Platformer" });
break;
}
//Info
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
if (_DimensionID == 0)
Menu_QuickStart2D();
else
Menu_QuickStart3D();
//Create/Refresh
GUI.backgroundColor = Color.white;
GUILayout.Label("Build Options", EditorStyles.boldLabel);
_CreateSceneOptions = GUILayout.Toolbar(_CreateSceneOptions, new string[] { "New scene", "This scene" });
EditorGUILayout.EndScrollView();
if (GUILayout.Button("Create"))
CreateTemplate();
if (GUILayout.Button("Refresh"))
SearchScripts();
}
void Menu_QuickStart2D()
{
switch (_Type2DID)
{
case 0: //Platformer
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_2D_Platformer");
ScriptStatus("Movement_Camera");
GUILayout.Label("Extra", EditorStyles.boldLabel);
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_2D_Platformer", "Movement_Camera" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "" });
EditorGUILayout.EndHorizontal();
break;
case 1: //TopDown
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_2D_TopDown");
ScriptStatus("Movement_Camera");
GUILayout.Label("Extra", EditorStyles.boldLabel);
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_2D_TopDown", "Movement_Camera" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "" });
EditorGUILayout.EndHorizontal();
break;
case 2: //VisualNovel
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("VisualNovelHandler");
GUILayout.Label("Extra", EditorStyles.boldLabel);
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "" });
EditorGUILayout.EndHorizontal();
break;
}
}
void Menu_QuickStart3D()
{
switch (_Type3DID)
{
case 0: //FPS
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_CC_FirstPerson");
GUILayout.Label("Extra", EditorStyles.boldLabel);
ScriptStatus("Health");
//
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_CC_FirstPerson"});
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "Movement_CC_FirstPerson", "Health" });
EditorGUILayout.EndHorizontal();
break;
case 1: //ThirdPerson
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_CC_FirstPerson");
GUILayout.Label("Extra", EditorStyles.boldLabel);
ScriptStatus("Health");
//
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_CC_FirstPerson" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "Movement_CC_FirstPerson", "Health" });
EditorGUILayout.EndHorizontal();
break;
case 2: //TopDown
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_CC_TopDown");
GUILayout.Label("Extra", EditorStyles.boldLabel);
ScriptStatus("Health");
//
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_CC_TopDown" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "Movement_CC_TopDown", "Health" });
EditorGUILayout.EndHorizontal();
break;
case 3: //Platformer
GUILayout.Label("Essential", EditorStyles.boldLabel);
ScriptStatus("Movement_CC_Platformer");
GUILayout.Label("Extra", EditorStyles.boldLabel);
ScriptStatus("Health");
//
GUI.backgroundColor = Color.white;
EditorGUILayout.BeginHorizontal("box");
GUILayout.Label("Add:", EditorStyles.boldLabel, GUILayout.Width(30));
if (GUILayout.Button("Essential"))
AddScriptsMultiple(new string[] { "Movement_CC_Platformer" });
if (GUILayout.Button("All"))
AddScriptsMultiple(new string[] { "Movement_CC_Platformer", "Health" });
EditorGUILayout.EndHorizontal();
break;
}
}
//Home > QuickStart : CreateScene
void CreateTemplate()
{
if (_CreateSceneOptions == 0)
{
Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
}
CreateObjects();
}
void CreateObjects()
{
//Check Scripts
SearchScripts();
//3D
if (_DimensionID == 1)
{
GameObject groundCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
groundCube.name = "Ground";
groundCube.transform.position = new Vector3(0, 0, 0);
GameObject player = GameObject.CreatePrimitive(PrimitiveType.Capsule);
player.name = "Player";
player.transform.position = new Vector3(0, 2, 0);
GameObject cameraObj = GameObject.Find("Main Camera");
switch (_Type3DID)
{
case 0: //FPS
CreateObjects_3D_FPS(player, groundCube, cameraObj);
break;
case 1: //ThirdPerson
CreateObjects_3D_ThirdPerson(player, groundCube, cameraObj);
break;
case 2: //TopDown
CreateObjects_3D_TopDown(player, groundCube, cameraObj);
break;
case 3: //Platformer
CreateObjects_3D_Platformer(player, groundCube, cameraObj);
break;
}
}
//2D
if (_DimensionID == 0)
{
GameObject groundCube = GameObject.CreatePrimitive(PrimitiveType.Quad);
DestroyImmediate(groundCube.GetComponent<MeshCollider>());
groundCube.AddComponent<BoxCollider2D>();
groundCube.name = "Ground";
groundCube.transform.position = new Vector3(0, 0, 0);
GameObject player = GameObject.CreatePrimitive(PrimitiveType.Quad);
DestroyImmediate(player.GetComponent<MeshCollider>());
player.AddComponent<BoxCollider2D>();
player.name = "Player";
player.transform.position = new Vector3(0, 2, 0);
GameObject cameraObj = GameObject.Find("Main Camera");
Camera cam = cameraObj.GetComponent<Camera>();
cam.orthographic = true;
switch(_Type2DID)
{
case 0: //Platformer
CreateObjects_2D_Platformer(player, groundCube, cameraObj);
break;
case 1: //TopDown
CreateObjects_2D_TopDown(player, groundCube, cameraObj);
break;
}
}
}
//Home > QuickStart : Create Objects 3D / Set scripts
void CreateObjects_3D_FPS(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
//Setup Level
groundobj.transform.localScale = new Vector3(25, 1, 25);
cameraobj.transform.parent = playerobj.transform;
cameraobj.transform.localPosition = new Vector3(0, 0.65f, 0);
GameObject objpool = new GameObject();
//Setup Scripts
if (ScriptExist("Health"))
{
string UniType = "Health";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("ObjectPool"))
{
string UniType = "ObjectPool";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
objpool.AddComponent(UnityType);
objpool.name = "ObjectPool";
}
if (ScriptExist("Movement_CC_FirstPerson"))
{
string UniType = "Movement_CC_FirstPerson";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
}
void CreateObjects_3D_ThirdPerson(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
//Setup Level
groundobj.transform.localScale = new Vector3(25, 1, 25);
GameObject rotationPoint = GameObject.CreatePrimitive(PrimitiveType.Cube);
rotationPoint.name = "rotationPoint";
rotationPoint.transform.position = new Vector3(0, 2, 0);
cameraobj.transform.parent = rotationPoint.transform;
cameraobj.transform.localPosition = new Vector3(1, 0.65f, -1.5f);
rotationPoint.transform.parent = playerobj.transform;
DestroyImmediate(rotationPoint.GetComponent<BoxCollider>());
rotationPoint.GetComponent<MeshRenderer>().enabled = false;
//Setup Scripts
if (ScriptExist("Health"))
{
string UniType = "Health";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_CC_FirstPerson"))
{
string UniType = "Movement_CC_FirstPerson";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
}
void CreateObjects_3D_TopDown(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
//Setup Level
groundobj.transform.localScale = new Vector3(25, 1, 25);
cameraobj.transform.position = new Vector3(0, 10, -1.5f);
cameraobj.transform.eulerAngles = new Vector3(80, 0, 0);
//Setup Scripts
if (ScriptExist("Health"))
{
string UniType = "Health";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_CC_TopDown"))
{
string UniType = "Movement_CC_TopDown";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
playerobj.GetComponent(UnityType).SendMessage("SetCamera", cameraobj.GetComponent<Camera>());
}
if (ScriptExist("Movement_Camera"))
{
string UniType = "Movement_Camera";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
cameraobj.AddComponent(UnityType);
cameraobj.GetComponent(UnityType).SendMessage("Set_CameraTarget", playerobj);
}
}
void CreateObjects_3D_Platformer(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
//Setup Level
groundobj.transform.localScale = new Vector3(25, 1, 1);
//Setup Scripts
if (ScriptExist("Health"))
{
string UniType = "Health";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_CC_Platformer"))
{
string UniType = "Movement_CC_Platformer";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_Camera"))
{
string UniType = "Movement_Camera";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
cameraobj.AddComponent(UnityType);
cameraobj.GetComponent(UnityType).SendMessage("Set_CameraTarget", playerobj);
cameraobj.GetComponent(UnityType).SendMessage("Set_OffSet", new Vector3(0, 5, -10));
}
}
//Home > QuickStart : Create Object 2D / Set scripts
void CreateObjects_2D_Platformer(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
groundobj.transform.localScale = new Vector3(25, 1, 1);
if (ScriptExist("Movement_2D_Platformer"))
{
string UniType = "Movement_2D_Platformer";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_Camera"))
{
string UniType = "Movement_Camera";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
cameraobj.AddComponent(UnityType);
cameraobj.GetComponent(UnityType).SendMessage("Set_CameraTarget", playerobj);
cameraobj.GetComponent(UnityType).SendMessage("Set_OffSet", new Vector3(0, 3, -10));
}
}
void CreateObjects_2D_TopDown(GameObject playerobj, GameObject groundobj, GameObject cameraobj)
{
DestroyImmediate(groundobj);
if (ScriptExist("Movement_2D_TopDown"))
{
string UniType = "Movement_2D_TopDown";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
playerobj.AddComponent(UnityType);
}
if (ScriptExist("Movement_Camera"))
{
string UniType = "Movement_Camera";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
cameraobj.AddComponent(UnityType);
cameraobj.GetComponent(UnityType).SendMessage("Set_CameraTarget", playerobj);
cameraobj.GetComponent(UnityType).SendMessage("Set_OffSet", new Vector3(0, 3, -10));
}
}
//Home > Scripts
void Menu_Scripts()
{
//Refresh
if (GUILayout.Button("Refresh"))
SearchScripts();
//MultiSelect
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Add Multiple: ", GUILayout.Width(75));
_AddMultipleScriptsActive = EditorGUILayout.Toggle(_AddMultipleScriptsActive, GUILayout.Width(70));
//MultiSelect Buttons
if (_AddMultipleScriptsActive)
{
//Add Selected
if (GUILayout.Button("Add Selected", GUILayout.Width(100)))
for (int i = 0; i < _AddMultipleScripts.Length; i++)
if (_AddMultipleScripts[i])
AddScript(i);
//DeSelect
if (GUILayout.Button("DeSelect (" + _AddMultipleScripts_SelectAmount.ToString() + ")", GUILayout.Width(100)))
for (int i = 0; i < _AddMultipleScripts.Length; i++)
_AddMultipleScripts[i] = false;
}
EditorGUILayout.EndHorizontal();
//Search Options
_Search_Script = EditorGUILayout.TextField("Search: ", _Search_Script);
_Search_Tag = EditorGUILayout.TextField("SearchTag: ", _Search_Tag);
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
//Quickstart Scripts
if (!_AddMultipleScriptsActive)
_Search_QuickStartScripts_Toggle = EditorGUILayout.Foldout(_Search_QuickStartScripts_Toggle, "QuickStart" + " || Results(" + _Search_Results.ToString() + "/" + QuickStart_Scripts.Length.ToString() + ") || In Project: " + _Search_InProject_Results.ToString());
else
_Search_QuickStartScripts_Toggle = EditorGUILayout.Foldout(_Search_QuickStartScripts_Toggle, "QuickStart" + " || Results(" + _Search_Results.ToString() + "/" + QuickStart_Scripts.Length.ToString() + ") || In Project: " + _Search_InProject_Results.ToString() + " || Selected: " + _AddMultipleScripts_SelectAmount.ToString());
if (_Search_QuickStartScripts_Toggle)
{
_Search_Results = 0;
_Search_InProject_Results = 0;
for (int i = 0; i < QuickStart_Scripts.Length; i++)
{
//Scripts
if (_Search_Script == "" || QuickStart_Scripts[i].ScriptName.ToLower().Contains(_Search_Script.ToLower()))
{
if (QuickStart_Scripts[i].ScriptTag.ToLower().Contains(_Search_Tag.ToLower()) || QuickStart_Scripts[i].ScriptTag == "" || QuickStart_Scripts[i].ScriptTag == null)
{
//Update results
_Search_Results++;
//Set color
if (QuickStart_Scripts[i].Exist)
{
GUI.backgroundColor = new Color(0, 1, 0);
_Search_InProject_Results++;
}
else
GUI.backgroundColor = new Color(1, 0, 0);
//Script
EditorGUILayout.BeginHorizontal("Box");
if (Screen.width <= 325)
{
if (_AddMultipleScriptsActive)
EditorGUILayout.LabelField(QuickStart_Scripts[i].ScriptName + ".cs", EditorStyles.boldLabel, GUILayout.Width(Screen.width - 150));
else
EditorGUILayout.LabelField(QuickStart_Scripts[i].ScriptName + ".cs", EditorStyles.boldLabel, GUILayout.Width(Screen.width - 135));
}
else
{
if (_AddMultipleScriptsActive)
EditorGUILayout.LabelField(QuickStart_Scripts[i].ScriptName + ".cs", EditorStyles.boldLabel, GUILayout.Width(Screen.width - 205));
else
EditorGUILayout.LabelField(QuickStart_Scripts[i].ScriptName + ".cs", EditorStyles.boldLabel, GUILayout.Width(Screen.width - 190));
}
if (Screen.width > 325)
EditorGUILayout.LabelField(QuickStart_Scripts[i].ScriptState, EditorStyles.miniLabel, GUILayout.Width(50));
//Select Script
if (!QuickStart_Scripts[i].Exist)
{
EditorGUI.BeginDisabledGroup(true);
if (GUILayout.Button("Select", GUILayout.Width(50)))
Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(QuickStart_Scripts[i].ScriptPath);
EditorGUI.EndDisabledGroup();
}
else
{
if (GUILayout.Button("Select", GUILayout.Width(50)))
Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(QuickStart_Scripts[i].ScriptPath);
}
//Add Script
EditorGUI.BeginDisabledGroup(QuickStart_Scripts[i].Exist);
if (GUILayout.Button("Add", GUILayout.Width(50)))
AddScript(i);
EditorGUI.EndDisabledGroup();
//Add Multiple
if (_AddMultipleScriptsActive)
_AddMultipleScripts[i] = EditorGUILayout.Toggle(_AddMultipleScripts[i]);
EditorGUILayout.EndHorizontal();
}
}
//SelectAmount
_AddMultipleScripts_SelectAmount = 0;
for (int j = 0; j < _AddMultipleScripts.Length; j++)
{
if (_AddMultipleScripts[j])
_AddMultipleScripts_SelectAmount++;
}
}
}
GUI.backgroundColor = Color.white;
//ProjectScripts
_Searcg_ProjectScripts_Toggle = EditorGUILayout.Foldout(_Searcg_ProjectScripts_Toggle, "Project" + " || Results(" + _Search_ProjectScripts_Results.ToString() + "/" + _Search_ProjectScripts_Total.ToString() + ")");
if (_Searcg_ProjectScripts_Toggle)
{
_Search_ProjectScripts_Results = 0;
_Search_ProjectScripts_Total = _Project_Scripts.Length;
for (int i = 0; i < _Project_Scripts.Length; i++)
{
if (_Search_Script == "" || _Project_Scripts[i].ToLower().Contains(_Search_Script.ToLower()))
{
//Update results
_Search_ProjectScripts_Results++;
//Script
EditorGUILayout.BeginHorizontal("Box");
EditorGUILayout.LabelField(_Project_Scripts[i], EditorStyles.boldLabel);
if (GUILayout.Button("Select", GUILayout.Width(50)))
Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(_Project_Scripts[i]);
EditorGUILayout.EndHorizontal();
}
}
}
EditorGUILayout.EndScrollView();
}
//Home > Scripts : Search
void ScriptStatus(string name)
{
int scriptid = 999;
for (int i = 0; i < QuickStart_Scripts.Length; i++)
{
if (name == QuickStart_Scripts[i].ScriptName)
{
scriptid = i;
continue;
}
}
if (scriptid != 999)
{
if (QuickStart_Scripts[scriptid].Exist)
{ GUI.backgroundColor = new Color(0, 1, 0); }
else
GUI.backgroundColor = new Color(1, 0, 0);
EditorGUILayout.BeginHorizontal("Box");
GUILayout.Label(name + ".cs");
EditorGUI.BeginDisabledGroup(QuickStart_Scripts[scriptid].Exist);
if (GUILayout.Button("Add", GUILayout.Width(50)))
{
AddScript(scriptid);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
}
else
{
GUI.backgroundColor = Color.black;
EditorGUILayout.BeginHorizontal("Box");
GUILayout.Label(name + ".cs");
EditorGUI.BeginDisabledGroup(true);
if (GUILayout.Button("Add", GUILayout.Width(50))) { }
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
}
}
void SearchScripts()
{
//QuickStart Scripts
bool[] checkexist = new bool[QuickStart_Scripts.Length];
for (int i = 0; i < QuickStart_Scripts.Length; i++)
{
string[] search_results = System.IO.Directory.GetFiles("Assets/", "*.cs", System.IO.SearchOption.AllDirectories);
for (int o = 0; o < search_results.Length; o++)
{
if (search_results[o].ToLower().Contains(QuickStart_Scripts[i].ScriptName.ToLower()))
{
checkexist[i] = true;
QuickStart_Scripts[i].ScriptPath = search_results[o];
}
}
}
for (int i = 0; i < QuickStart_Scripts.Length; i++)
{
QuickStart_Scripts[i].Exist = checkexist[i];
}
//Set
if (_AddMultipleScripts.Length == 0)
_AddMultipleScripts = new bool[QuickStart_Scripts.Length];
//Scripts Project
_Project_Scripts = System.IO.Directory.GetFiles("Assets/", "*.cs", System.IO.SearchOption.AllDirectories);
}
bool ScriptExist(string name)
{
int scriptid = 0;
for (int i = 0; i < QuickStart_Scripts.Length; i++)
{
if (name == QuickStart_Scripts[i].ScriptName)
{
scriptid = i;
continue;
}
}
return QuickStart_Scripts[scriptid].Exist;
}
//Home > Scripts : Add
void AddScriptsMultiple(string[] ids)
{
for (int i = 0; i < ids.Length; i++)
{
for (int o = 0; o < QuickStart_Scripts.Length; o++)
{
if (ids[i] == QuickStart_Scripts[o].ScriptName)
{
AddScript(o);
}
}
}
}
void AddScript(int id)
{
SearchScripts();
if (!QuickStart_Scripts[id].Exist)
{
using (StreamWriter sw = new StreamWriter(string.Format(Application.dataPath + "/" + QuickStart_Scripts[id].ScriptName + ".cs",
new object[] { QuickStart_Scripts[id].ScriptName.Replace(" ", "") })))
{
sw.Write(QuickStart_Scripts[id].ScriptCode);
}
}
AssetDatabase.Refresh();
SearchScripts();
}
//Home > QuickUI : Menu
void Menu_QuickUI()
{
GUILayout.BeginHorizontal();
_MainCanvas = (GameObject)EditorGUILayout.ObjectField("Canvas", _MainCanvas, typeof(GameObject), true);
if (_MainCanvas == null)
{
if (GUILayout.Button("Search"))
{
_MainCanvas = GameObject.FindObjectOfType<Canvas>().gameObject;
HUD_Add_Tab();
}
if (GUILayout.Button("Create"))
{
_MainCanvas = HUD_Create_Canvas();
HUD_Add_Tab();
}
}
else
{
if (GUILayout.Button("Delete"))
if (_MainCanvas != null)
{
DestroyImmediate(_MainCanvas);
_HUDTab.Clear();
_CheckMainCanvasRectSize = Vector2.zero;
_MainCanvasRect = null;
_MainCanvas = null;
}
}
GUILayout.EndHorizontal();
//LiveEditor
if (_MainCanvas != null)
HUD_Editor();
}
//Home > QuickUI : HUD Editor
void HUD_Editor()
{
HUD_Editor_Profile();
HUD_Editor_Tabs();
//HUD Settings
_HUD_EnableLiveEdit = EditorGUILayout.Toggle("Enable LiveUpdate",_HUD_EnableLiveEdit);
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
HUD_Editor_Obj();
HUD_Editor_CanvasOptions();
EditorGUILayout.EndScrollView();
}
void HUD_Editor_Tabs()
{
String[] tabs = new string[_HUDTab.Count];
for (int i = 0; i < _HUDTab.Count; i++)
{
tabs[i] = i.ToString();
}
GUILayout.BeginHorizontal();
_HUDTabID = GUILayout.Toolbar(_HUDTabID, tabs);
if (GUILayout.Button("Add", GUILayout.Width(50)))
{
HUD_Add_Tab();
}
GUILayout.EndHorizontal();
if (GUILayout.Button("ToggleActive"))
{
_HUDTab[_HUDTabID].HUD_TabParent.SetActive(!_HUDTab[_HUDTabID].HUD_TabParent.activeSelf);
}
}
void HUD_Editor_Profile()
{
GUILayout.BeginHorizontal();
_HUD_Profiles = (HUDProfiles)EditorGUILayout.EnumPopup("Load Profile:", _HUD_Profiles);
if (GUILayout.Button("Load", GUILayout.Width(50)))
{
HUD_ClearLoaded();
switch (_HUD_Profiles)
{
case HUDProfiles.BasicStartMenu:
HUD_LoadProfile_BasicStartMenu();
break;
case HUDProfiles.AdvanceStartMenu_wip:
HUD_LoadProfile_AdvancedMenu();
break;
}
}
GUILayout.EndHorizontal();
}
void HUD_Editor_Obj()
{
for (int i = 0; i < _HUDTab[_HUDTabID].HUD_TabOjects.Count; i++)
{
if (GUILayout.Button(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Name))
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_FoldOut = !_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_FoldOut;
if (_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_FoldOut)
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Name = EditorGUILayout.TextField("", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Name);
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Type = (Tool_QuickStartUI_Object.HUD_Types)EditorGUILayout.EnumPopup("", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Type);
if (_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Type != _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_CheckType)
{
if (GUILayout.Button("Update"))
{
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_RectTransform = null;
DestroyImmediate(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Object);
HUD_Change_Type(_HUDTab[_HUDTabID].HUD_TabOjects[i]);
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_CheckType = _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Type;
}
}
GUILayout.EndHorizontal();
//Type
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Location = (Tool_QuickStartUI_Object.HUD_Locations)EditorGUILayout.EnumPopup("Location:", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Location);
//Size
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Size = EditorGUILayout.Vector2Field("Size", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Size);
//Scale
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Scale = EditorGUILayout.Vector3Field("Scale", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Scale);
//Offset
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Offset = EditorGUILayout.Vector2Field("Offset", _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Offset);
if (GUILayout.Button("Remove"))
{
DestroyImmediate(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Object);
_HUDTab[_HUDTabID].HUD_TabOjects.Remove(_HUDTab[_HUDTabID].HUD_TabOjects[i]);
}
GUILayout.EndVertical();
}
}
}
void HUD_Editor_CanvasOptions()
{
if (_MainCanvas != null)
{
//LiveEdit
if (_HUD_EnableLiveEdit)
{
if (GUILayout.Button("Create", GUILayout.Height(30)))
{
Tool_QuickStartUI_Object newuiobj = new Tool_QuickStartUI_Object();
newuiobj.HUD_Object = HUD_Create_Text();
newuiobj.HUD_RectTransform = newuiobj.HUD_Object.GetComponent<RectTransform>();
newuiobj.HUD_CheckType = Tool_QuickStartUI_Object.HUD_Types.Text;
newuiobj.HUD_Object.name = "New Text";
newuiobj.HUD_Name = "New Text";
newuiobj.HUD_Size = new Vector2(200, 60);
newuiobj.HUD_Object.transform.SetParent(_HUDTab[_HUDTabID].HUD_TabParent.transform);
_HUDTab[_HUDTabID].HUD_TabOjects.Add(newuiobj);
}
LiveHUDEditorUpdate();
}
else
{
if (GUILayout.Button("Add"))
{
Tool_QuickStartUI_Object newuiobj = new Tool_QuickStartUI_Object();
_HUDTab[_HUDTabID].HUD_TabOjects.Add(newuiobj);
}
if (GUILayout.Button("Update"))
{
LiveHUDEditorUpdate();
}
}
}
else
GUILayout.Label("Add or assign canvas to create/add");
}
//Home > QuickUI : HUD Updator
void LiveHUDEditorUpdate()
{
for (int i = 0; i < _HUDTab[_HUDTabID].HUD_TabOjects.Count; i++)
{
if(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Object != null)
{
//Update HUD
HUD_Change_Position(_HUDTab[_HUDTabID].HUD_TabOjects[i]);
HUD_Set_Size(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Size);
HUD_Set_Scale(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Scale);
HUD_Set_SetOffSet(_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Offset);
_HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Object.name = _HUDTab[_HUDTabID].HUD_TabOjects[i].HUD_Name;
HUD_TextSize(_HUDTab[_HUDTabID].HUD_TabOjects[i]);
//Update canvas size / tab size
if(_MainCanvasRect == null)
_MainCanvasRect = _MainCanvas.GetComponent<RectTransform>();
if (_CheckMainCanvasRectSize != _MainCanvasRect.sizeDelta)
{
for (int j = 0; j < _HUDTab.Count; j++)
{
_HUDTab[j].HUD_TabParent.GetComponent<RectTransform>().sizeDelta = _MainCanvasRect.sizeDelta;
}
_CheckMainCanvasRectSize = _MainCanvasRect.sizeDelta;
}
//Update text size
for (int j = 0; j < _HUDTab[_HUDTabID].HUD_TabOjects.Count; j++)
{
if(_HUDTab[_HUDTabID].HUD_TabOjects[j].HUD_Type == Tool_QuickStartUI_Object.HUD_Types.Button)
{
for (int o = 0; o < _HUDTab[_HUDTabID].HUD_TabOjects[j].HUD_Text.Count; o++)
{
_HUDTab[_HUDTabID].HUD_TabOjects[j].HUD_Text[o].rectTransform.sizeDelta = _HUDTab[_HUDTabID].HUD_TabOjects[j].HUD_Size;
}
}
}
}
}
}
void HUDEditorRefresh()
{
for (int o = 0; o < _HUDTab.Count; o++)
{
for (int i = 0; i < _HUDTab[o].HUD_TabOjects.Count; i++)
{
if (_HUDTab[o].HUD_TabOjects[i].HUD_Object != null)
{
//Update HUD
HUD_Change_Position(_HUDTab[o].HUD_TabOjects[i]);
HUD_Set_Size(_HUDTab[o].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[o].HUD_TabOjects[i].HUD_Size);
HUD_Set_Scale(_HUDTab[o].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[o].HUD_TabOjects[i].HUD_Scale);
HUD_Set_SetOffSet(_HUDTab[o].HUD_TabOjects[i].HUD_RectTransform, _HUDTab[o].HUD_TabOjects[i].HUD_Offset);
_HUDTab[o].HUD_TabOjects[i].HUD_Object.name = _HUDTab[o].HUD_TabOjects[i].HUD_Name;
HUD_TextSize(_HUDTab[o].HUD_TabOjects[i]);
//Update canvas size / tab size
if (_MainCanvasRect == null)
_MainCanvasRect = _MainCanvas.GetComponent<RectTransform>();
if (_CheckMainCanvasRectSize != _MainCanvasRect.sizeDelta)
{
for (int j = 0; j < _HUDTab.Count; j++)
{
_HUDTab[j].HUD_TabParent.GetComponent<RectTransform>().sizeDelta = _MainCanvasRect.sizeDelta;
}
_CheckMainCanvasRectSize = _MainCanvasRect.sizeDelta;
}
//Update text size
for (int j = 0; j < _HUDTab[o].HUD_TabOjects.Count; j++)
{
if (_HUDTab[o].HUD_TabOjects[j].HUD_Type == Tool_QuickStartUI_Object.HUD_Types.Button)
{
for (int p = 0; p < _HUDTab[o].HUD_TabOjects[j].HUD_Text.Count; p++)
{
_HUDTab[o].HUD_TabOjects[j].HUD_Text[p].rectTransform.sizeDelta = _HUDTab[o].HUD_TabOjects[j].HUD_Size;
}
}
}
}
}
}
}
//Home > QuickUI : HUD Edit
void HUD_Change_Position(Tool_QuickStartUI_Object obj)
{
obj.HUD_RectTransform.position = _MainCanvas.transform.position;
switch (obj.HUD_Location)
{
case Tool_QuickStartUI_Object.HUD_Locations.TopLeft: HUD_Set_Rect(obj.HUD_RectTransform, "topleft"); break;
case Tool_QuickStartUI_Object.HUD_Locations.TopMiddle: HUD_Set_Rect(obj.HUD_RectTransform, "topmiddle"); break;
case Tool_QuickStartUI_Object.HUD_Locations.TopRight: HUD_Set_Rect(obj.HUD_RectTransform, "topright"); break;
case Tool_QuickStartUI_Object.HUD_Locations.RightMiddle: HUD_Set_Rect(obj.HUD_RectTransform, "rightmiddle"); break;
case Tool_QuickStartUI_Object.HUD_Locations.LeftMiddle: HUD_Set_Rect(obj.HUD_RectTransform, "leftmiddle"); break;
case Tool_QuickStartUI_Object.HUD_Locations.BottomLeft: HUD_Set_Rect(obj.HUD_RectTransform, "bottomleft"); break;
case Tool_QuickStartUI_Object.HUD_Locations.BottomMiddle: HUD_Set_Rect(obj.HUD_RectTransform, "bottommiddle"); break;
case Tool_QuickStartUI_Object.HUD_Locations.BottomRight: HUD_Set_Rect(obj.HUD_RectTransform, "bottomright"); break;
case Tool_QuickStartUI_Object.HUD_Locations.Middle: HUD_Set_Rect(obj.HUD_RectTransform, "middle"); break;
}
}
void HUD_Change_Type(Tool_QuickStartUI_Object obj)
{
//Change Type
switch(obj.HUD_Type)
{
case Tool_QuickStartUI_Object.HUD_Types.Text:
obj.HUD_Object = HUD_Create_Text();
obj.HUD_Object.name = "New Text";
break;
case Tool_QuickStartUI_Object.HUD_Types.Button:
obj.HUD_Object = HUD_Create_Button();
obj.HUD_Object.name = "New Button";
break;
case Tool_QuickStartUI_Object.HUD_Types.Dropdown:
obj.HUD_Object = HUD_Create_DropDown();
obj.HUD_Object.name = "New Dropdown";
break;
case Tool_QuickStartUI_Object.HUD_Types.Slider:
obj.HUD_Object = HUD_Create_Slider();
obj.HUD_Object.name = "New Slider";
obj.HUD_Size = new Vector2(obj.HUD_Size.x, obj.HUD_Size.y / 3);
break;
case Tool_QuickStartUI_Object.HUD_Types.Bar:
obj.HUD_Object = HUD_Create_Bar();
obj.HUD_Object.name = "New Bar";
break;
}
if(obj.HUD_Type != Tool_QuickStartUI_Object.HUD_Types.Slider && obj.HUD_CheckType == Tool_QuickStartUI_Object.HUD_Types.Slider)
obj.HUD_Size = new Vector2(obj.HUD_Size.x, obj.HUD_Size.y * 3);
if (obj.HUD_Name == "" || obj.HUD_Name == null || obj.HUD_Name == "New Text" || obj.HUD_Name == "New Button" || obj.HUD_Name == "New Dropdown" || obj.HUD_Name == "New Slider" || obj.HUD_Name == "New Bar")
obj.HUD_Name = obj.HUD_Object.name;
obj.HUD_RectTransform = obj.HUD_Object.GetComponent<RectTransform>();
HUD_Change_Position(obj);
//Add to tab
obj.HUD_Object.transform.SetParent(_HUDTab[_HUDTabID].HUD_TabParent.transform);
//Update UI Obj text ref
obj.HUD_Text.Clear();
for (int i = 0; i < obj.HUD_Object.transform.childCount; i++)
{
if (obj.HUD_Object.transform.GetChild(i).GetComponent<TextMeshProUGUI>() != null)
obj.HUD_Text.Add(obj.HUD_Object.transform.GetChild(i).GetComponent<TextMeshProUGUI>());
}
}
void HUD_TextSize(Tool_QuickStartUI_Object obj)
{
for (int i = 0; i < obj.HUD_Text.Count; i++)
{
obj.HUD_Text[i].fontSize = obj.HUD_TextFontSize;
}
}
//Home > QuickUI : HUD Create
GameObject HUD_Create_Text()
{
GameObject newhud_text = HUD_Create_Template();
newhud_text.AddComponent<TextMeshProUGUI>().text = "New Text";
return newhud_text;
}
GameObject HUD_Create_Button()
{
GameObject newhud_button = HUD_Create_Template();
newhud_button.AddComponent<CanvasRenderer>();
Image buttonimage = newhud_button.AddComponent<Image>();
buttonimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
buttonimage.type = Image.Type.Sliced;
Button buttonbutton = newhud_button.AddComponent<Button>();
buttonbutton.targetGraphic = buttonimage;
GameObject buttontextemplate = new GameObject();
RectTransform buttontextrect = buttontextemplate.AddComponent<RectTransform>();
buttontextrect.anchoredPosition = new Vector3(5,0,0);
TextMeshProUGUI buttontexttmpro = buttontextemplate.AddComponent<TextMeshProUGUI>();
buttontexttmpro.text = "New Button";
buttontexttmpro.alignment = TextAlignmentOptions.MidlineLeft;
buttontexttmpro.color = Color.black;
buttontextemplate.name = name + "text";
buttontextemplate.transform.SetParent(newhud_button.transform);
newhud_button.transform.SetParent(_MainCanvas.transform);
return newhud_button;
}
GameObject HUD_Create_DropDown()
{
//Create objects
GameObject dropdownobj = new GameObject();
GameObject dropdown_label = new GameObject();
GameObject dropdown_arrow = new GameObject();
GameObject dropdown_template = new GameObject();
GameObject dropdown_viewport = new GameObject();
GameObject dropdown_content = new GameObject();
GameObject dropdown_item = new GameObject();
GameObject dropdown_item_background = new GameObject();
GameObject dropdown_item_checkmark = new GameObject();
GameObject dropdown_item_label = new GameObject();
GameObject dropdown_scrollbar = new GameObject();
GameObject dropdown_slidingarea = new GameObject();
GameObject dropdown_handle = new GameObject();
dropdown_template.SetActive(false);
//Set Name
dropdownobj.name = name;
dropdown_label.name = "Label";
dropdown_arrow.name = "Arrow";
dropdown_template.name = "Template";
dropdown_viewport.name = "Viewport";
dropdown_content.name = "Content";
dropdown_item.name = "Item";
dropdown_item_background.name = "Item Background";
dropdown_item_checkmark.name = "Item Checkmark";
dropdown_item_label.name = "Item Label";
dropdown_scrollbar.name = "Scrollbar";
dropdown_slidingarea.name = "Sliding Area";
dropdown_handle.name = "Handle";
//Add RectTransform
RectTransform dropdownobjrect = dropdownobj.AddComponent<RectTransform>();
RectTransform dropdown_labelrect = dropdown_label.AddComponent<RectTransform>();
RectTransform dropdown_arrowrect = dropdown_arrow.AddComponent<RectTransform>();
RectTransform dropdown_templaterect = dropdown_template.AddComponent<RectTransform>();
RectTransform dropdown_viewportrect = dropdown_viewport.AddComponent<RectTransform>();
RectTransform dropdown_contentrect = dropdown_content.AddComponent<RectTransform>();
RectTransform dropdown_itemrect = dropdown_item.AddComponent<RectTransform>();
RectTransform dropdown_item_backgroundrect = dropdown_item_background.AddComponent<RectTransform>();
RectTransform dropdown_item_checkmarkrect = dropdown_item_checkmark.AddComponent<RectTransform>();
RectTransform dropdown_item_labelrect = dropdown_item_label.AddComponent<RectTransform>();
RectTransform dropdown_scrollbarrect = dropdown_scrollbar.AddComponent<RectTransform>();
RectTransform dropdown_slidingarearect = dropdown_slidingarea.AddComponent<RectTransform>();
RectTransform dropdown_handlerect = dropdown_handle.AddComponent<RectTransform>();
//SetParent
dropdown_label.transform.SetParent(dropdownobj.transform);
dropdown_arrow.transform.SetParent(dropdownobj.transform);
dropdown_template.transform.SetParent(dropdownobj.transform);
dropdown_viewport.transform.SetParent(dropdown_template.transform);
dropdown_content.transform.SetParent(dropdown_viewport.transform);
dropdown_item.transform.SetParent(dropdown_content.transform);
dropdown_item_background.transform.SetParent(dropdown_item.transform);
dropdown_item_checkmark.transform.SetParent(dropdown_item.transform);
dropdown_item_label.transform.SetParent(dropdown_item.transform);
dropdown_scrollbar.transform.SetParent(dropdown_template.transform);
dropdown_slidingarea.transform.SetParent(dropdown_scrollbar.transform);
dropdown_handle.transform.SetParent(dropdown_slidingarea.transform);
//Set Rect dropdownobj
Image dropdownimage = dropdownobj.AddComponent<Image>();
dropdownimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
dropdownimage.type = Image.Type.Sliced;
TMP_Dropdown dropdowntmp = dropdownobj.AddComponent<TMP_Dropdown>();
List<TMP_Dropdown.OptionData> newoptions = new List<TMP_Dropdown.OptionData>();
TMP_Dropdown.OptionData option1 = new TMP_Dropdown.OptionData();
TMP_Dropdown.OptionData option2 = new TMP_Dropdown.OptionData();
TMP_Dropdown.OptionData option3 = new TMP_Dropdown.OptionData();
option1.text = "Option A";
option2.text = "Option B";
option3.text = "Option C";
newoptions.Add(option1);
newoptions.Add(option2);
newoptions.Add(option3);
dropdowntmp.AddOptions(newoptions);
//Set Rect Label
dropdown_labelrect.anchorMin = new Vector2(0, 0);
dropdown_labelrect.anchorMax = new Vector2(1, 1);
dropdown_labelrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_labelrect.sizeDelta = new Vector2(0, 0);
dropdown_labelrect.anchoredPosition = new Vector4(0, 0);
//Set Rect Arrow
dropdown_arrowrect.anchorMin = new Vector2(1, 0.5f);
dropdown_arrowrect.anchorMax = new Vector2(1, 0.5f);
dropdown_arrowrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_arrowrect.sizeDelta = new Vector2(20, 20);
dropdown_arrowrect.anchoredPosition = new Vector4(-15, 0);
//Set Rect Template
dropdown_templaterect.anchorMin = new Vector2(0, 0);
dropdown_templaterect.anchorMax = new Vector2(1, 0);
dropdown_templaterect.pivot = new Vector2(0.5f, 1);
dropdown_templaterect.sizeDelta = new Vector2(0, 150);
dropdown_templaterect.anchoredPosition = new Vector4(0, 2);
//Set Rect Viewport
dropdown_viewportrect.anchorMin = new Vector2(0, 0);
dropdown_viewportrect.anchorMax = new Vector2(1, 1);
dropdown_viewportrect.pivot = new Vector2(0, 1);
dropdown_viewportrect.sizeDelta = new Vector2(0, 0);
dropdown_viewportrect.anchoredPosition = new Vector4(0, 0);
//Set Rect Content
dropdown_contentrect.anchorMin = new Vector2(0, 1);
dropdown_contentrect.anchorMax = new Vector2(1, 1);
dropdown_contentrect.pivot = new Vector2(0.5f, 1);
dropdown_contentrect.sizeDelta = new Vector2(0, 28);
dropdown_contentrect.anchoredPosition = new Vector4(0, 0);
//Set Rect Item
dropdown_itemrect.anchorMin = new Vector2(0, 0.5f);
dropdown_itemrect.anchorMax = new Vector2(1, 0.5f);
dropdown_itemrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_itemrect.sizeDelta = new Vector2(0,28);
dropdown_itemrect.anchoredPosition = new Vector4(0, -15); //NotDy
//Set Rect Item Background
dropdown_item_backgroundrect.anchorMin = new Vector2(0, 0);
dropdown_item_backgroundrect.anchorMax = new Vector2(1, 1);
dropdown_item_backgroundrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_item_backgroundrect.sizeDelta = new Vector2(0, 0);
dropdown_item_backgroundrect.anchoredPosition = new Vector4(0, 0);
//Set Rect Item Checkmark
dropdown_item_checkmarkrect.anchorMin = new Vector2(0, 0.5f);
dropdown_item_checkmarkrect.anchorMax = new Vector2(0, 0.5f);
dropdown_item_checkmarkrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_item_checkmarkrect.sizeDelta = new Vector2(20, 20);
dropdown_item_checkmarkrect.anchoredPosition = new Vector4(10, 0);
//Set Rect Item Label
dropdown_item_labelrect.anchorMin = new Vector2(0, 0);
dropdown_item_labelrect.anchorMax = new Vector2(1, 1);
dropdown_item_labelrect.pivot = new Vector2(0.5f, 0.5f);
dropdown_item_labelrect.sizeDelta = new Vector2(10, 1);
dropdown_item_labelrect.anchoredPosition = new Vector4(20, 2);
//Set Rect Scrollbar
dropdown_scrollbarrect.anchorMin = new Vector2(1, 0);
dropdown_scrollbarrect.anchorMax = new Vector2(1, 1);
dropdown_scrollbarrect.pivot = new Vector2(1, 1);
dropdown_scrollbarrect.sizeDelta = new Vector2(20, 0);
dropdown_scrollbarrect.anchoredPosition = new Vector4(0, 0);
//Set Rect Sliding Area
dropdown_slidingarearect.anchorMin = new Vector2(0, 0);
dropdown_slidingarearect.anchorMax = new Vector2(1, 1);
dropdown_slidingarearect.pivot = new Vector2(0.5f, 0.5f);
dropdown_slidingarearect.sizeDelta = new Vector2(10, 10);
dropdown_slidingarearect.anchoredPosition = new Vector4(10, 10);
//Set Rect Handle
dropdown_handlerect.anchorMin = new Vector2(0, 0);
dropdown_handlerect.anchorMax = new Vector2(1, 0.2f);
dropdown_handlerect.pivot = new Vector2(0.5f, 0.5f);
dropdown_handlerect.sizeDelta = new Vector2(-10, -10);
dropdown_handlerect.anchoredPosition = new Vector4(-10, -10);
//
dropdown_arrow.AddComponent<Image>().sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/DropdownArrow.psd"); ;
//
dropdowntmp.template = dropdown_templaterect;
dropdowntmp.captionText = dropdown_label.GetComponent<TextMeshProUGUI>();
dropdowntmp.itemText = dropdown_item_label.GetComponent<TextMeshProUGUI>();
//handle
Image dropdown_handleimage = dropdown_handle.AddComponent<Image>();
dropdown_handleimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd"); ;
dropdown_handleimage.type = Image.Type.Sliced;
//scrollbar
Image dropdown_scrollbarimage = dropdown_scrollbar.AddComponent<Image>();
dropdown_scrollbarimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Background.psd"); ;
dropdown_scrollbarimage.type = Image.Type.Sliced;
Scrollbar dropdown_scrollbar_scroll = dropdown_scrollbar.AddComponent<Scrollbar>();
dropdown_scrollbar_scroll.targetGraphic = dropdown_handleimage;
dropdown_scrollbar_scroll.handleRect = dropdown_handlerect;
dropdown_scrollbar_scroll.direction = Scrollbar.Direction.BottomToTop;
//Template
Image dropdown_templateimage = dropdown_template.AddComponent<Image>();
dropdown_templateimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
dropdown_templateimage.type = Image.Type.Sliced;
ScrollRect dropdown_templatescrollrect = dropdown_template.AddComponent<ScrollRect>();
dropdown_templatescrollrect.content = dropdown_contentrect;
dropdown_templatescrollrect.decelerationRate = 0.135f;
dropdown_templatescrollrect.scrollSensitivity = 1;
dropdown_templatescrollrect.viewport = dropdown_viewportrect;
dropdown_templatescrollrect.movementType = ScrollRect.MovementType.Clamped;
dropdown_templatescrollrect.verticalScrollbar = dropdown_scrollbar_scroll;
dropdown_templatescrollrect.horizontal = false;
dropdown_templatescrollrect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
dropdown_templatescrollrect.verticalScrollbarSpacing = -3;
//viewport
Mask dropdown_viewportmask = dropdown_viewport.AddComponent<Mask>();
Image dropdown_viewportimage = dropdown_viewport.AddComponent<Image>();
dropdown_viewportimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd");
dropdown_viewportimage.type = Image.Type.Sliced;
//Item Background
dropdown_item_background.AddComponent<Image>();
//Item Checkmark
dropdown_item_checkmark.AddComponent<Image>().sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Checkmark.psd"); ;
//Item Label
TextMeshProUGUI dropdown_item_labeltmp = dropdown_item_label.AddComponent<TextMeshProUGUI>();
dropdown_item_labeltmp.text = "Option A";
dropdown_item_labeltmp.color = Color.black;
//LabelText
TextMeshProUGUI dropdown_labeltext = dropdown_label.AddComponent<TextMeshProUGUI>();
dropdown_labeltext.alignment = TextAlignmentOptions.MidlineLeft;
dropdown_labeltext.color = Color.black;
dropdown_labeltext.text = "Option A";
//Item
Toggle dropdown_itemtoggle = dropdown_item.AddComponent<Toggle>();
dropdown_itemtoggle.targetGraphic = dropdown_item_background.GetComponent<Image>();
dropdown_itemtoggle.graphic = dropdown_item_checkmark.GetComponent<Image>();
dropdown_itemtoggle.isOn = true;
//dropdownobj
dropdowntmp.targetGraphic = dropdownimage;
dropdowntmp.itemText = dropdown_item_labeltmp;
//AddToOptions
dropdownobj.transform.SetParent(_MainCanvas.transform);
dropdowntmp.captionText = dropdown_labeltext;
//dropdownobjrect.sizeDelta = new Vector2(0,0);
return dropdownobj;
}
GameObject HUD_Create_Slider()
{
//Create Objects
GameObject newsliderbackground = new GameObject();
GameObject newsliderobj = new GameObject();
GameObject newsliderfillarea = new GameObject();
GameObject newsliderfill = new GameObject();
GameObject newsliderslidearea = new GameObject();
GameObject newsliderhandle = new GameObject();
newsliderobj.name = name;
//Set Parents
newsliderbackground.transform.SetParent(newsliderobj.transform);
newsliderfill.transform.SetParent(newsliderfillarea.transform);
newsliderfillarea.transform.SetParent(newsliderobj.transform);
newsliderhandle.transform.SetParent(newsliderslidearea.transform);
newsliderslidearea.transform.SetParent(newsliderobj.transform);
//Add RectTransform
RectTransform newsliderbackgroundrect = newsliderbackground.AddComponent<RectTransform>();
RectTransform buttonfillarearect = newsliderfillarea.AddComponent<RectTransform>();
RectTransform buttonfillrect = newsliderfill.AddComponent<RectTransform>();
RectTransform buttonslidearearect = newsliderslidearea.AddComponent<RectTransform>();
RectTransform buttonhandlerect = newsliderhandle.AddComponent<RectTransform>();
//Add Images
Image newsliderbackgroundimage = newsliderbackground.AddComponent<Image>();
Image newsliderfillimage = newsliderfill.AddComponent<Image>();
newsliderfillimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
newsliderfillimage.type = Image.Type.Sliced;
newsliderfillimage.color = Color.grey;
Image newsliderhandleimage = newsliderhandle.AddComponent<Image>();
//Set Rect NewObj
Slider newsliderslider = newsliderobj.AddComponent<Slider>();
//Set Rect Background
newsliderbackgroundrect.anchorMin = new Vector2(0, 0.25f);
newsliderbackgroundrect.anchorMax = new Vector2(1, 0.75f);
newsliderbackgroundrect.pivot = new Vector2(0.5f, 0.5f);
newsliderbackgroundrect.sizeDelta = new Vector2(0, 0);
newsliderbackgroundrect.anchoredPosition = new Vector2(0, 0);
newsliderbackground.name = "BackGround";
//Set Rect FillArea
buttonfillarearect.anchorMin = new Vector2(0, 0.25f);
buttonfillarearect.anchorMax = new Vector2(1, 0.75f);
buttonfillarearect.pivot = new Vector2(0.5f, 0.5f);
buttonfillarearect.sizeDelta = new Vector2(15, 0);
buttonfillarearect.anchoredPosition = new Vector2(5, 0);
newsliderfillarea.name = "FillArea";
//Set Rect Fill
buttonfillrect.anchorMin = new Vector2(0, 0.25f);
buttonfillrect.anchorMax = new Vector2(1, 0.75f);
buttonfillrect.pivot = new Vector2(0.5f, 0.5f);
buttonfillrect.sizeDelta = new Vector2(10, 0);
buttonfillrect.anchoredPosition = new Vector4(0, 0);
newsliderfill.name = "Fill";
//Set Rect SliderArea
buttonslidearearect.anchorMin = new Vector2(0, 0);
buttonslidearearect.anchorMax = new Vector2(1, 1);
buttonslidearearect.pivot = new Vector2(0.5f, 0.5f);
buttonslidearearect.sizeDelta = new Vector2(10, 0);
buttonslidearearect.anchoredPosition = new Vector2(10, 0);
newsliderslidearea.name = "Handle Slide Area";
//Set Rect Handle
buttonhandlerect.anchorMin = new Vector2(0, 0.25f);
buttonhandlerect.anchorMax = new Vector2(1, 0.75f);
buttonhandlerect.pivot = new Vector2(0.5f, 0.5f);
buttonhandlerect.sizeDelta = new Vector2(20, 0);
buttonhandlerect.anchoredPosition = new Vector2(0, 0);
newsliderhandleimage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");
newsliderslider.image = newsliderhandleimage;
newsliderslider.fillRect = buttonfillrect;
newsliderslider.handleRect = buttonhandlerect;
newsliderhandle.name = "Handle";
newsliderobj.transform.SetParent(_MainCanvas.transform);
return newsliderobj;
}
GameObject HUD_Create_Bar()
{
GameObject newhud_text = HUD_Create_Template();
return newhud_text;
}
GameObject HUD_Create_Template()
{
GameObject newhudobj = new GameObject();
newhudobj.AddComponent<RectTransform>();
newhudobj.transform.SetParent(_MainCanvas.transform);
return newhudobj;
}
GameObject HUD_Create_Canvas()
{
GameObject canvasobj = new GameObject();
canvasobj.name = "TestCanvas";
Canvas canvasobj_canvas = canvasobj.AddComponent<Canvas>();
canvasobj_canvas.worldCamera = Camera.main;
CanvasScaler canvasscale = canvasobj.AddComponent<CanvasScaler>();
canvasscale.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasscale.referenceResolution = new Vector2(1920, 1080);
canvasobj.AddComponent<GraphicRaycaster>();
if (GameObject.Find("EventSystem") == null)
{
GameObject eventsystemobj = new GameObject();
eventsystemobj.name = "EventSystem";
eventsystemobj.AddComponent<EventSystem>();
eventsystemobj.AddComponent<StandaloneInputModule>();
}
Canvas canvascomponent = canvasobj.GetComponent<Canvas>();
canvascomponent.renderMode = RenderMode.ScreenSpaceCamera;
return canvasobj;
}
//Home > QuickUI : HUD Set
void HUD_Set_Rect(RectTransform rect, string anchorpos)
{
switch (anchorpos)
{
case "topleft":
rect.anchorMin = new Vector2(0, 1);
rect.anchorMax = new Vector2(0, 1);
rect.pivot = new Vector2(0, 1);
break;
case "topmiddle":
rect.anchorMin = new Vector2(0.5f, 1);
rect.anchorMax = new Vector2(0.5f, 1);
rect.pivot = new Vector2(0.5f, 1);
break;
case "topright":
rect.anchorMin = new Vector2(1, 1);
rect.anchorMax = new Vector2(1, 1);
rect.pivot = new Vector2(1, 1);
break;
case "rightmiddle":
rect.anchorMin = new Vector2(1, 0.5f);
rect.anchorMax = new Vector2(1, 0.5f);
rect.pivot = new Vector2(1, 0.5f);
break;
case "bottomright":
rect.anchorMin = new Vector2(1, 0);
rect.anchorMax = new Vector2(1, 0);
rect.pivot = new Vector2(1, 0);
break;
case "bottommiddle":
rect.anchorMin = new Vector2(0.5f, 0);
rect.anchorMax = new Vector2(0.5f, 0);
rect.pivot = new Vector2(0.5f, 0);
break;
case "bottomleft":
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(0, 0);
rect.pivot = new Vector2(0, 0);
break;
case "leftmiddle":
rect.anchorMin = new Vector2(0, 0.5f);
rect.anchorMax = new Vector2(0, 0.5f);
rect.pivot = new Vector2(0, 0.5f);
break;
case "middle":
rect.anchorMin = new Vector2(0.5f, 0.5f);
rect.anchorMax = new Vector2(0.5f, 0.5f);
rect.pivot = new Vector2(0.5f, 0.5f);
break;
}
}
void HUD_Set_Size(RectTransform rect, Vector2 size)
{
rect.sizeDelta = size;
}
void HUD_Set_Scale(RectTransform rect, Vector3 scale)
{
rect.localScale = scale;
}
void HUD_Set_SetOffSet(RectTransform rect, Vector3 offset)
{
rect.anchoredPosition = offset;
}
//Home > QuickUI : HUD Add
void HUD_Add_Tab()
{
Tool_QuickStartUI_Tab newtab = new Tool_QuickStartUI_Tab();
newtab.HUD_TabParent = HUD_Create_Template();
RectTransform rect_main = _MainCanvas.GetComponent<RectTransform>();
RectTransform rect_tab = newtab.HUD_TabParent.GetComponent<RectTransform>();
rect_tab.anchorMin = new Vector2(0, 1);
rect_tab.anchorMax = new Vector2(0, 1);
rect_tab.pivot = new Vector2(0, 1);
rect_tab.sizeDelta = rect_main.sizeDelta;
rect_tab.localScale = new Vector3(1, 1, 1);
rect_tab.position = _MainCanvas.transform.position;
rect_tab.anchoredPosition = new Vector3(0, 0, 0);
newtab.HUD_TabParent.name = _HUDTab.Count.ToString();
_HUDTab.Add(newtab);
}
//Home > QuickUI : HUD Profiles
void HUD_ClearLoaded()
{
for (int i = 0; i < _HUDTab.Count; i++)
{
DestroyImmediate(_HUDTab[i].HUD_TabParent);
}
_HUDTab.Clear();
_HUDTabID = 0;
}
void HUD_LoadProfile_Refresh()
{
//Update
for (int i = 0; i < _HUDTab.Count; i++)
{
_HUDTabID = i;
for (int j = 0; j < _HUDTab[i].HUD_TabOjects.Count; j++)
{
_HUDTab[i].HUD_TabOjects[j].HUD_RectTransform = null;
DestroyImmediate(_HUDTab[i].HUD_TabOjects[j].HUD_Object);
HUD_Change_Type(_HUDTab[i].HUD_TabOjects[j]);
_HUDTab[i].HUD_TabOjects[j].HUD_CheckType = _HUDTab[i].HUD_TabOjects[j].HUD_Type;
}
}
_HUDTabID = 0;
HUDEditorRefresh();
}
void HUD_LoadProfile_AdvancedMenu()
{
HUD_Add_Tab(); //0 Home
HUD_Add_Tab(); //1 Display
HUD_Add_Tab(); //2 Graphics
HUD_Add_Tab(); //3 Gameplay
HUD_Add_Tab(); //4 Controls
//============================================================================================= 0 Home
Tool_QuickStartUI_Object tab_home_startbutton = new Tool_QuickStartUI_Object();
tab_home_startbutton.HUD_Name = "Button_Start";
tab_home_startbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_startbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_startbutton.HUD_Offset = new Vector3(40, 450, 0);
tab_home_startbutton.HUD_Size = new Vector2(500, 100);
tab_home_startbutton.HUD_Scale = new Vector3(1, 1, 1);
Tool_QuickStartUI_Object tab_home_optionsbutton = new Tool_QuickStartUI_Object();
tab_home_optionsbutton.HUD_Name = "Button_Options";
tab_home_optionsbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_optionsbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_optionsbutton.HUD_Offset = new Vector3(40, 330, 0);
tab_home_optionsbutton.HUD_Size = new Vector2(500, 100);
tab_home_optionsbutton.HUD_Scale = new Vector3(1, 1, 1);
Tool_QuickStartUI_Object tab_home_quitbutton = new Tool_QuickStartUI_Object();
tab_home_quitbutton.HUD_Name = "Button_Quit";
tab_home_quitbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_quitbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_quitbutton.HUD_Offset = new Vector3(40, 210, 0);
tab_home_quitbutton.HUD_Size = new Vector2(500, 100);
tab_home_quitbutton.HUD_Scale = new Vector3(1, 1, 1);
_HUDTab[0].HUD_TabOjects.Add(tab_home_startbutton);
_HUDTab[0].HUD_TabOjects.Add(tab_home_optionsbutton);
_HUDTab[0].HUD_TabOjects.Add(tab_home_quitbutton);
//============================================================================================= 1 Display
Tool_QuickStartUI_Object tab_display_title = new Tool_QuickStartUI_Object();
tab_display_title.HUD_Name = "Title_Display";
tab_display_title.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Text;
tab_display_title.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_display_title.HUD_Offset = new Vector3(800, 800, 0);
Tool_QuickStartUI_Object tab_display_resolution = new Tool_QuickStartUI_Object();
tab_display_resolution.HUD_Name = "Dropdown_Resolution";
tab_display_resolution.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Dropdown;
tab_display_resolution.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_display_resolution.HUD_Size = new Vector2(500,60);
tab_display_resolution.HUD_Offset = new Vector3(800, 700, 0);
Tool_QuickStartUI_Object tab_display_resolution_text = new Tool_QuickStartUI_Object();
tab_display_resolution_text.HUD_Name = "Text_Resolution";
tab_display_resolution_text.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Text;
tab_display_resolution_text.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_display_resolution_text.HUD_Offset = new Vector3(600, 700, 0);
Tool_QuickStartUI_Object tab_display_quality = new Tool_QuickStartUI_Object();
tab_display_quality.HUD_Name = "Dropdown_Resolution";
tab_display_quality.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Dropdown;
tab_display_quality.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_display_quality.HUD_Size = new Vector2(500, 60);
tab_display_quality.HUD_Offset = new Vector3(800, 630, 0);
Tool_QuickStartUI_Object tab_display_fullscreen = new Tool_QuickStartUI_Object();
tab_display_fullscreen.HUD_Name = "Dropown_Windowmode";
tab_display_fullscreen.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Dropdown;
tab_display_fullscreen.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_display_fullscreen.HUD_Size = new Vector2(500, 60);
tab_display_fullscreen.HUD_Offset = new Vector3(800, 560, 0);
_HUDTab[1].HUD_TabOjects.Add(tab_display_title);
_HUDTab[1].HUD_TabOjects.Add(tab_display_resolution);
_HUDTab[1].HUD_TabOjects.Add(tab_display_resolution_text);
_HUDTab[1].HUD_TabOjects.Add(tab_display_quality);
_HUDTab[1].HUD_TabOjects.Add(tab_display_fullscreen);
HUD_LoadProfile_Refresh();
}
void HUD_LoadProfile_BasicStartMenu()
{
HUD_Add_Tab();
//============================================================================================= 0 Home
Tool_QuickStartUI_Object tab_home_startbutton = new Tool_QuickStartUI_Object();
tab_home_startbutton.HUD_Name = "Button_Start";
tab_home_startbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_startbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_startbutton.HUD_Offset = new Vector3(40, 450, 0);
tab_home_startbutton.HUD_Size = new Vector2(500, 100);
tab_home_startbutton.HUD_Scale = new Vector3(1, 1, 1);
Tool_QuickStartUI_Object tab_home_optionsbutton = new Tool_QuickStartUI_Object();
tab_home_optionsbutton.HUD_Name = "Button_Options";
tab_home_optionsbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_optionsbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_optionsbutton.HUD_Offset = new Vector3(40, 330, 0);
tab_home_optionsbutton.HUD_Size = new Vector2(500, 100);
tab_home_optionsbutton.HUD_Scale = new Vector3(1, 1, 1);
Tool_QuickStartUI_Object tab_home_quitbutton = new Tool_QuickStartUI_Object();
tab_home_quitbutton.HUD_Name = "Button_Quit";
tab_home_quitbutton.HUD_Type = Tool_QuickStartUI_Object.HUD_Types.Button;
tab_home_quitbutton.HUD_Location = Tool_QuickStartUI_Object.HUD_Locations.BottomLeft;
tab_home_quitbutton.HUD_Offset = new Vector3(40, 210, 0);
tab_home_quitbutton.HUD_Size = new Vector2(500, 100);
tab_home_quitbutton.HUD_Scale = new Vector3(1, 1, 1);
_HUDTab[0].HUD_TabOjects.Add(tab_home_startbutton);
_HUDTab[0].HUD_TabOjects.Add(tab_home_optionsbutton);
_HUDTab[0].HUD_TabOjects.Add(tab_home_quitbutton);
HUD_LoadProfile_Refresh();
}
void HUD_LoadProfile_Settings()
{
}
//Home > QuickUI : Set Script Refs
void Set_SettingsHandler()
{
if (ScriptExist("SettingsHandler"))
{
string UniType = "SettingsHandler";
Type UnityType = Type.GetType(UniType + ", Assembly-CSharp");
GameObject settingshandlerobj = new GameObject();
settingshandlerobj.AddComponent(UnityType);
TMP_Dropdown[] dropdowns = Resources.FindObjectsOfTypeAll<TMP_Dropdown>();
for (int i = 0; i < dropdowns.Length; i++)
{
if(dropdowns[i].name == "Dropdown_Resolution")
{
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_Resolution", dropdowns[i]);
}
if (dropdowns[i].name == "Dropdown_Quality")
{
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_Quality", dropdowns[i]);
}
if (dropdowns[i].name == "Dropdown_Antialiasing")
{
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_AA", dropdowns[i]);
}
if (dropdowns[i].name == "Dropdown_TextureQuality")
{
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_TextureQuality", dropdowns[i]);
}
}
/*
TMP_Dropdown resolution = Resources.FindObjectsOfTypeAll<TMP_Dropdown>(); //GameObject.Find("Dropdown_Resolution").GetComponent<TMP_Dropdown>();
TMP_Dropdown quality = GameObject.Find("").GetComponent<TMP_Dropdown>();
TMP_Dropdown texturequality = GameObject.Find("").GetComponent<TMP_Dropdown>();
TMP_Dropdown aa = GameObject.Find("").GetComponent<TMP_Dropdown>();
Slider volumeslider = GameObject.Find("").GetComponent<Slider>();
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_Quality", quality);
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_TextureQuality", texturequality);
settingshandlerobj.GetComponent(UnityType).SendMessage("SetDropDown_AA", aa);
settingshandlerobj.GetComponent(UnityType).SendMessage("SetSlider_VolumeSlider", volumeslider);
*/
settingshandlerobj.name = "SettingsHandler";
}
}
//FileFinder
void FileFinder()
{
_ToolState = GUILayout.Toolbar(_ToolState, new string[] { "Assets", "Scene" });
if (_ToolState == 0)
{
FileFinder_Search();
FileFinder_SearchAssets();
}
else
{
FileFinder_SceneSearch();
_FF_Scene_InsceneInfo = EditorGUILayout.Toggle("InScene Info", _FF_Scene_InsceneInfo);
FileFinder_Scene();
}
//stop focus when switching
if (_ToolStateCheck != _ToolState)
{
EditorGUI.FocusTextInControl("searchproject");
_ToolStateCheck = _ToolState;
}
}
void FileFinder_Search()
{
_FF_Search = EditorGUILayout.TextField("Search:", _FF_Search);
_FF_Type = EditorGUILayout.TextField("Type:", _FF_Type);
GUILayout.Label("(" + _FF_Results + "/" + _FF_Total + ")");
_FF_Results = 0;
_FF_Total = 0;
if (_FF_Search != _FF_SearchCheck || _FF_Type != _FF_TypeCheck)
{
_FF_SearchResults = System.IO.Directory.GetFiles("Assets/", "*" + _FF_Type, System.IO.SearchOption.AllDirectories);
_FF_SearchCheck = _FF_Search;
_FF_TypeCheck = _FF_Type;
}
}
void FileFinder_SearchAssets()
{
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
for (int i = 0; i < _FF_SearchResults.Length; i++)
{
if (_FF_SearchResults[i].ToLower().Contains(_FF_Search.ToLower()))
{
GUILayout.BeginHorizontal("Box");
GUILayout.Label(_FF_SearchResults[i], GUILayout.Width(Screen.width - 80));
if (GUILayout.Button("Select", GUILayout.Width(50)))
{
Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(_FF_SearchResults[i]);
}
GUILayout.EndHorizontal();
_FF_Results++;
}
_FF_Total++;
}
EditorGUILayout.EndScrollView();
}
void FileFinder_SceneSearch()
{
_FF_Scene_Search = EditorGUILayout.TextField("Search:", _FF_Scene_Search);
GUILayout.Label("(" + _FF_Results + "/" + _FF_Total + ")");
_FF_Results = 0;
_FF_Total = 0;
if (_FF_Scene_Objects.Length == 0)
_FF_Scene_Objects = FindObjectsOfType<GameObject>();
}
void FileFinder_Scene()
{
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
for (int i = 0; i < _FF_Scene_Objects.Length; i++)
{
if (_FF_Scene_Objects[i].name.ToLower().Contains(_FF_Scene_Search.ToLower()))
{
GUILayout.BeginHorizontal("Box");
GUILayout.Label(_FF_Scene_Objects[i].name, GUILayout.Width(Screen.width - 80));
if (GUILayout.Button("Select", GUILayout.Width(50)))
{
Selection.activeObject = _FF_Scene_Objects[i];
}
GUILayout.EndHorizontal();
_FF_Results++;
}
_FF_Total++;
}
EditorGUILayout.EndScrollView();
}
//Script To String
void ScriptToString_Menu()
{
if (GUILayout.Button("Convert", GUILayout.Height(30)))
_STS_ScriptOutput = STS_ConvertScriptToString();
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
STS_InputOutput();
STS_StringExample();
EditorGUILayout.EndScrollView();
}
void STS_InputOutput()
{
GUILayout.Space(20);
//Input
GUILayout.Label("Input: ", EditorStyles.boldLabel);
_STS_InputScript = EditorGUILayout.ObjectField(_STS_InputScript, typeof(MonoScript), false) as MonoScript;
//Output
GUILayout.Label("Output: ", EditorStyles.boldLabel);
EditorGUILayout.TextField("", _STS_ScriptOutput);
GUILayout.Space(20);
}
void STS_StringExample()
{
//Preview
List<string> output = new List<string>();
List<string> output2 = new List<string>();
for (int i = 0; i < _STS_ScriptOutput.Length; i++)
{
output.Add(System.Convert.ToString(_STS_ScriptOutput[i]));
}
int begincalc = 0;
int endcalc = 0;
for (int i = 0; i < output.Count; i++)
{
if (i + 1 < output.Count)
{
if (output[i] + output[i + 1] == "\\n")
{
endcalc = i;
string addstring = "";
for (int j = 0; j < endcalc - begincalc; j++)
{
addstring += output[begincalc + j];
}
addstring += output[endcalc] + output[endcalc + 1];
output2.Add(addstring);
endcalc = endcalc + 1;
begincalc = endcalc + 1;
}
}
}
for (int i = 0; i < output2.Count; i++)
{
GUILayout.BeginHorizontal();
if (output2[i].Contains("//"))
{
EditorGUILayout.TextField("", "x", GUILayout.MaxWidth(15));
}
else
{
EditorGUILayout.TextField("", "", GUILayout.MaxWidth(15));
}
EditorGUILayout.TextField("", output2[i]);
GUILayout.EndHorizontal();
}
}
string STS_ConvertScriptToString()
{
string newstring = "\"";
string[] readText = File.ReadAllLines(STS_GetPath());
for (int i = 0; i < readText.Length; i++)
{
string newline = "";
for (int j = 0; j < readText[i].Length; j++)
{
if (System.Convert.ToString(readText[i][j]) == "\"")
newline += "\\";
newline += System.Convert.ToString(readText[i][j]);
}
readText[i] = newline + "\\n";
newstring += readText[i];
}
newstring += "\"";
return newstring;
}
string STS_GetPath()
{
string[] filepaths = System.IO.Directory.GetFiles("Assets/", "*.cs", System.IO.SearchOption.AllDirectories);
for (int i = 0; i < filepaths.Length; i++)
{
if (filepaths[i].Contains(_STS_InputScript.name + ".cs"))
{
return filepaths[i];
}
}
return "";
}
//MapEditor
void MapEditor_Menu()
{
if (_ME_FirstLoad)
{
ME_Load_Prefabs();
_ME_FirstLoad = false;
}
GUILayout.BeginVertical("Box");
//Refresh/Info
GUILayout.BeginHorizontal();
if (GUILayout.Button("Refresh", GUILayout.Width(80)))
{
ME_Load_Prefabs();
}
if (GUILayout.Button("Fix", GUILayout.Width(80)))
{
ME_FixPreview();
}
GUILayout.Label("Loaded objects: " + _ME_SearchResults.Length);
GUILayout.EndHorizontal();
//Windows
ME_ObjectView_Header();
ME_ObjectView_Objects();
ME_ObjectView_Options();
GUILayout.EndVertical();
}
void ME_ObjectView_Header()
{
GUILayout.BeginHorizontal();
_ME_OptionsStates = GUILayout.Toolbar(_ME_OptionsStates, new string[] { "Icon", "Text" });
_ME_ButtonSize = EditorGUILayout.Slider(_ME_ButtonSize, 0.25f, 2);
if (!_ME_HideNames)
{
if (GUILayout.Button("Hide Names", GUILayout.Width(100)))
_ME_HideNames = true;
}
else
{
if (GUILayout.Button("Show Names", GUILayout.Width(100)))
_ME_HideNames = false;
}
GUILayout.EndHorizontal();
_ME_SearchPrefab = EditorGUILayout.TextField("Search: ", _ME_SearchPrefab);
}
void ME_ObjectView_Objects()
{
Color defaultColor = GUI.backgroundColor;
GUILayout.BeginVertical("Box");
float calcWidth = 100 * _ME_ButtonSize;
_ME_CollomLength = position.width / calcWidth;
int x = 0;
int y = 0;
//Show/Hide Options
if (_ME_HideOptions)
_ME_ScrollPos1 = GUILayout.BeginScrollView(_ME_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 125));
else
{
if (_ME_PlacementStates == 0)
_ME_ScrollPos1 = GUILayout.BeginScrollView(_ME_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 266));
else
_ME_ScrollPos1 = GUILayout.BeginScrollView(_ME_ScrollPos1, GUILayout.Width(position.width - 20), GUILayout.Height(position.height - 285));
}
//Object Icons
for (int i = 0; i < _ME_SearchResults.Length; i++)
{
if (_ME_Prefabs[i] != null && _ME_Prefabs[i].name.ToLower().Contains(_ME_SearchPrefab.ToLower()))
{
if (_ME_OptionsStates == 0) //Icons
{
//Select Color
if (_ME_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = new Color(1, 0, 0); }
//Create Button
GUIContent content = new GUIContent();
content.image = _ME_PrefabIcon[i];
GUI.skin.button.imagePosition = ImagePosition.ImageAbove;
if (!_ME_HideNames)
content.text = _ME_Prefabs[i].name;
if (GUI.Button(new Rect(x * 100 * _ME_ButtonSize, y * 100 * _ME_ButtonSize, 100 * _ME_ButtonSize, 100 * _ME_ButtonSize), content))
if (_ME_SelectedID == i) { _ME_SelectedID = 99999999; _ME_CheckSelectedID = 99999999; DestroyImmediate(_ME_ExampleObj); } else { _ME_SelectedID = i; }
//Reset Button Position
x++;
if (x >= _ME_CollomLength - 1)
{
y++;
x = 0;
}
GUI.backgroundColor = defaultColor;
}
else //Text Buttons
{
if (_ME_SelectedID == i) { GUI.backgroundColor = new Color(0, 1, 0); } else { GUI.backgroundColor = defaultColor; }
if (GUILayout.Button(_ME_Prefabs[i].name))
if (_ME_SelectedID == i) { _ME_SelectedID = 99999999; _ME_CheckSelectedID = 99999999; DestroyImmediate(_ME_ExampleObj); } else { _ME_SelectedID = i; }
GUI.backgroundColor = defaultColor;
}
}
}
if (_ME_OptionsStates == 0)
{
GUILayout.Space(y * 100 * _ME_ButtonSize + 100);
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
void ME_ObjectView_Options()
{
GUILayout.BeginVertical("Box");
if (!_ME_HideOptions)
{
//Paint Options
GUILayout.BeginVertical("Box");
_ME_PlacementStates = GUILayout.Toolbar(_ME_PlacementStates, new string[] { "Click", "Paint" });
if (_ME_PlacementStates == 1)
_ME_PaintSpeed = EditorGUILayout.FloatField("Paint Speed: ", _ME_PaintSpeed);
//Parent Options
GUILayout.BeginHorizontal();
_ME_ParentObj = (GameObject)EditorGUILayout.ObjectField("Parent Object: ", _ME_ParentObj, typeof(GameObject), true);
if (_ME_ParentObj != null)
if (GUILayout.Button("Clean Parent"))
ME_CleanParent();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
//Grid Options
GUILayout.BeginVertical("Box");
_ME_GridSize = EditorGUILayout.Vector2Field("Grid Size: ", _ME_GridSize);
_ME_RandomRot = EditorGUILayout.Toggle("Random Rotation: ", _ME_RandomRot);
_ME_SnapPosActive = EditorGUILayout.Toggle("Use Grid: ", _ME_SnapPosActive);
GUILayout.EndVertical();
}
//Hide/Show Options
if (_ME_HideOptions)
{
if (GUILayout.Button("Show Options"))
_ME_HideOptions = false;
}
else
{
if (GUILayout.Button("Hide Options"))
_ME_HideOptions = true;
}
GUILayout.EndVertical();
}
//Load/Fix
void ME_Load_Prefabs()
{
_ME_SearchResults = System.IO.Directory.GetFiles("Assets/", "*.prefab", System.IO.SearchOption.AllDirectories);
_ME_Prefabs = new GameObject[_ME_SearchResults.Length];
_ME_PrefabIcon = new Texture2D[_ME_SearchResults.Length];
for (int i = 0; i < _ME_SearchResults.Length; i++)
{
UnityEngine.Object prefab = null;
prefab = AssetDatabase.LoadAssetAtPath(_ME_SearchResults[i], typeof(GameObject));
_ME_Prefabs[i] = prefab as GameObject;
_ME_PrefabIcon[i] = AssetPreview.GetAssetPreview(_ME_Prefabs[i]);
}
}
void ME_FixPreview()
{
ME_Load_Prefabs();
_ME_SearchResults = System.IO.Directory.GetFiles("Assets/", "*.prefab", System.IO.SearchOption.AllDirectories);
for (int i = 0; i < _ME_SearchResults.Length; i++)
{
if (_ME_PrefabIcon[i] == null)
AssetDatabase.ImportAsset(_ME_SearchResults[i]);
}
ME_Load_Prefabs();
}
//Create Prefab/Clean Parent
void ME_CreatePrefab(Vector3 createPos)
{
if (ME_CheckPositionEmpty(true))
{
GameObject createdObj = PrefabUtility.InstantiatePrefab(_ME_Prefabs[_ME_SelectedID]) as GameObject;
createdObj.transform.position = createPos;
createdObj.transform.localScale = new Vector3(_ME_Size, _ME_Size, _ME_Size);
if (_ME_ParentObj == null)
{
_ME_ParentObj = new GameObject();
_ME_ParentObj.name = "MapEditor_Parent";
}
createdObj.transform.parent = _ME_ParentObj.transform;
//SnapPos
if (_ME_SnapPosActive)
createdObj.transform.position = _ME_SnapPos;
else
createdObj.transform.position = _ME_MousePos;
//Rotation
/*
if (_ME_RandomRot)
createdObj.transform.rotation = Quaternion.Euler(0, UnityEngine.Random.Range(0, 360), 0);
else
createdObj.transform.rotation = Quaternion.Euler(0, _ME_Rotation, 0);
*/
if (_ME_RotateWithObject)
createdObj.transform.rotation = Quaternion.Euler(_ME_HitObject.eulerAngles.x, _ME_Rotation, _ME_HitObject.eulerAngles.z);
else
createdObj.transform.rotation = Quaternion.Euler(0, _ME_Rotation, 0);
//Test
}
}
void ME_CleanParent()
{
int childAmount = _ME_ParentObj.transform.childCount;
int childCalc = childAmount - 1;
for (int i = 0; i < childAmount; i++)
{
DestroyImmediate(_ME_ParentObj.transform.GetChild(childCalc).gameObject);
childCalc -= 1;
}
}
bool ME_CheckPositionEmpty(bool checky)
{
if (_ME_ParentObj != null)
{
bool check = true;
for (int i = 0; i < _ME_ParentObj.transform.childCount; i++)
{
if (checky)
{
if (_ME_ParentObj.transform.GetChild(i).position.x == _ME_SnapPos.x && _ME_ParentObj.transform.GetChild(i).position.z == _ME_SnapPos.z)
check = false;
}
else
if (_ME_ParentObj.transform.GetChild(i).position == _ME_SnapPos)
check = false;
}
return check;
}
else
{
return true;
}
}
//Enable/Disable
void OnEnable()
{
SceneView.duringSceneGui += this.OnSceneGUI;
SceneView.duringSceneGui += this.OnScene;
}
void OnDisable()
{
SceneView.duringSceneGui -= this.OnSceneGUI;
SceneView.duringSceneGui -= this.OnScene;
DestroyImmediate(_ME_ExampleObj);
}
//OnSceneGUI
void OnSceneGUI(SceneView sceneView)
{
//MapEditor
if (_WindowID == 4)
{
Event e = Event.current;
Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(worldRay, out hitInfo))
{
//Check MousePosition
_ME_MousePos = hitInfo.point;
//Hit Object
_ME_HitObject = hitInfo.transform;
//Create Example Object
if (_ME_SelectedID <= _ME_Prefabs.Length)
{
if (_ME_CheckSelectedID != _ME_SelectedID)
{
DestroyImmediate(_ME_ExampleObj);
_ME_ExampleObj = Instantiate(_ME_Prefabs[_ME_SelectedID], hitInfo.point, Quaternion.identity);
_ME_ExampleObj.layer = LayerMask.NameToLayer("Ignore Raycast");
for (int i = 0; i < _ME_ExampleObj.transform.childCount; i++)
{
_ME_ExampleObj.transform.GetChild(i).gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
for (int o = 0; o < _ME_ExampleObj.transform.GetChild(i).childCount; o++)
{
_ME_ExampleObj.transform.GetChild(i).GetChild(o).gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
}
}
_ME_ExampleObj.name = "Example Object";
_ME_CheckSelectedID = _ME_SelectedID;
}
}
//Set Example Object Position + Rotation
if (_ME_ExampleObj != null)
{
//Rotate with hit object
//Debug.Log("Transform: X" + _ME_HitObject.eulerAngles.x.ToString() + " Y " + _ME_HitObject.eulerAngles.z.ToString());
//Rotation
if (_ME_RotateWithObject)
_ME_ExampleObj.transform.rotation = Quaternion.Euler(_ME_HitObject.eulerAngles.x, _ME_Rotation, _ME_HitObject.eulerAngles.z);
else
_ME_ExampleObj.transform.rotation = Quaternion.Euler(0, _ME_Rotation, 0);
_ME_ExampleObj.transform.localScale = new Vector3(_ME_Size, _ME_Size, _ME_Size);
if (!e.shift && !e.control)
{
if (!_ME_SnapPosActive)
{ _ME_ExampleObj.transform.position = hitInfo.point; }
else
{ _ME_ExampleObj.transform.position = _ME_SnapPos; }
}
}
//Check Buttons Pressed
if (!Event.current.alt && _ME_SelectedID != 99999999)
{
if (Event.current.type == EventType.Layout)
HandleUtility.AddDefaultControl(0);
//Mouse Button 0 Pressed
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
_ME_MouseDown = true;
_ME_PaintTimer = _ME_PaintSpeed;
if (e.mousePosition.y <= 20)
_ME_ClickMenu = true;
}
//Mouse Button 0 Released
if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
{
_ME_MouseDown = false;
_ME_ClickMenu = false;
}
//Check Shift
if (e.shift)
_ME_ShiftDown = true;
else
_ME_ShiftDown = false;
//Check Ctrl
if (e.control)
_ME_CtrlDown = true;
else
_ME_CtrlDown = false;
if (e.shift || e.control)
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
_ME_ClickPos = Event.current.mousePosition;
}
//Place Object
if (!_ME_ShiftDown && !_ME_CtrlDown && !_ME_ClickMenu)
{
if (_ME_PlacementStates == 0)
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
ME_CreatePrefab(hitInfo.point);
}
else
{
float timer1Final = _ME_PaintSpeed;
if (_ME_MouseDown)
{
_ME_PaintTimer += 1 * Time.deltaTime;
if (_ME_PaintTimer >= timer1Final)
{
ME_CreatePrefab(hitInfo.point);
_ME_PaintTimer = 0;
}
}
}
}
}
// Draw obj location
if (_ME_SelectedID != 99999999)
{
//Draw Red Cross + Sphere on object location
Handles.color = new Color(1, 0, 0);
Handles.DrawLine(new Vector3(hitInfo.point.x - 0.3f, hitInfo.point.y, hitInfo.point.z), new Vector3(hitInfo.point.x + 0.3f, hitInfo.point.y, hitInfo.point.z));
Handles.DrawLine(new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z - 0.3f), new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z + 0.3f));
if (_ME_SnapPosActive)
{
Handles.SphereHandleCap(1, new Vector3(_ME_SnapPos.x, hitInfo.point.y, _ME_SnapPos.z), Quaternion.identity, 0.1f, EventType.Repaint);
}
else
Handles.SphereHandleCap(1, new Vector3(hitInfo.point.x, hitInfo.point.y, hitInfo.point.z), Quaternion.identity, 0.1f, EventType.Repaint);
//Check Snap Position
if (_ME_SnapPosActive)
{
Vector2 calc = new Vector2(_ME_MousePos.x / _ME_GridSize.x, _ME_MousePos.z / _ME_GridSize.y);
Vector2 calc2 = new Vector2(Mathf.RoundToInt(calc.x) * _ME_GridSize.x, Mathf.RoundToInt(calc.y) * _ME_GridSize.y);
_ME_SnapPos = new Vector3(calc2.x, _ME_MousePos.y, calc2.y);
//Draw Grid
Handles.color = new Color(0, 1, 0);
float lineLength = 0;
if (_ME_GridSize.x > _ME_GridSize.y)
lineLength = _ME_GridSize.x + 1;
else
lineLength = _ME_GridSize.y + 1;
for (int hor = 0; hor < 3; hor++)
{
Handles.DrawLine(new Vector3(calc2.x - lineLength, hitInfo.point.y, calc2.y - _ME_GridSize.y + _ME_GridSize.y * hor), new Vector3(calc2.x + lineLength, hitInfo.point.y, calc2.y - _ME_GridSize.y + _ME_GridSize.y * hor));
}
for (int ver = 0; ver < 3; ver++)
{
Handles.DrawLine(new Vector3(calc2.x - _ME_GridSize.x + _ME_GridSize.x * ver, hitInfo.point.y, calc2.y - lineLength), new Vector3(calc2.x - _ME_GridSize.x + _ME_GridSize.x * ver, hitInfo.point.y, calc2.y + lineLength));
}
}
}
}
}
//FileFinder
if (_FF_Scene_InsceneInfo)
{
Handles.color = new Color(0, 1, 0, 0.3f);
for (int i = 0; i < _FF_Scene_Objects.Length; i++)
{
if (_FF_Scene_Objects[i].name.ToLower().Contains(_FF_Scene_Search.ToLower()))
{
Handles.SphereHandleCap(1, _FF_Scene_Objects[i].transform.position, Quaternion.identity, 3f, EventType.Repaint);
Handles.Label(_FF_Scene_Objects[i].transform.position, _FF_Scene_Objects[i].name);
}
}
}
}
//OnScene
void OnScene(SceneView sceneView)
{
if (_WindowID == 4)
{
//InScene Option Bar
Handles.BeginGUI();
if (_ME_ShowOptionsInScene)
{
//Option Bar
GUI.Box(new Rect(0, 0, Screen.width, 22), GUIContent.none);
_ME_InScene_SelectedID = GUI.Toolbar(new Rect(22, 1, Screen.width / 2 - 30, 20), _ME_InScene_SelectedID, new string[] { "Settings", "Placement", "Transform", "Grid" });
switch (_ME_InScene_SelectedID)
{
case 0: //Settings
GUI.Label(new Rect(Screen.width / 2 - 5, 3, 50, 20), "Parent: ");
_ME_ParentObj = (GameObject)EditorGUI.ObjectField(new Rect(Screen.width / 2 + 50, 1, 150, 20), _ME_ParentObj, typeof(GameObject), true);
if (GUI.Button(new Rect(Screen.width - 110, 1, 90, 20), "Clean Parent"))
{
ME_CleanParent();
}
break;
case 1: //Placement
_ME_PlacementStates = GUI.Toolbar(new Rect(Screen.width / 2 - 5, 1, 100, 20), _ME_PlacementStates, new string[] { "Click", "Paint" });
_ME_PaintSpeed = EditorGUI.FloatField(new Rect(Screen.width / 2 + 185, 1, 50, 20), _ME_PaintSpeed);
GUI.Label(new Rect(Screen.width / 2 + 100, 3, 500, 20), "Paint speed: ");
break;
case 2: //Transform
_ME_Size = EditorGUI.FloatField(new Rect(Screen.width / 2 + 125, 1, 100, 20), _ME_Size);
break;
case 3: //Grid
GUI.Label(new Rect(Screen.width / 2 + 80, 3, 100, 20), "Grid Size: ");
_ME_GridSize.x = EditorGUI.FloatField(new Rect(Screen.width / 2 + 150, 1, 50, 20), _ME_GridSize.x);
_ME_GridSize.y = EditorGUI.FloatField(new Rect(Screen.width / 2 + 200, 1, 50, 20), _ME_GridSize.y);
GUI.Label(new Rect(Screen.width / 2, 3, 100, 20), "Enable: ");
_ME_SnapPosActive = EditorGUI.Toggle(new Rect(Screen.width / 2 + 50, 3, 20, 20), _ME_SnapPosActive);
break;
}
}
//Hotkeys Resize / Rotate
//Shift+MouseDown = Resize
Vector2 prevmove = _ME_PrevMousePos - Event.current.mousePosition;
if (_ME_ShiftDown && _ME_MouseDown)
{
_ME_Size = EditorGUI.Slider(new Rect(_ME_ClickPos.x - 15, _ME_ClickPos.y - 40, 50, 20), _ME_Size, 0.01f, 1000000);
_ME_Size -= (prevmove.x + prevmove.y) * 0.05f;
GUI.Label(new Rect(_ME_ClickPos.x - 50, _ME_ClickPos.y - 40, 500, 20), "Size: ");
}
//Ctrl+MouseDown = Rotate
if (_ME_CtrlDown && _ME_MouseDown)
{
_ME_Rotation = EditorGUI.Slider(new Rect(_ME_ClickPos.x - 15, _ME_ClickPos.y - 40, 50, 20), _ME_Rotation, -1000000, 1000000);
_ME_Rotation += prevmove.x + prevmove.y;
GUI.Label(new Rect(_ME_ClickPos.x - 80, _ME_ClickPos.y - 40, 500, 20), "Rotation: ");
}
_ME_PrevMousePos = Event.current.mousePosition;
//Inscene Show OptionButton
GUI.color = new Color(1f, 1f, 1f, 1f);
if (!_ME_ShowOptionsInScene)
{
if (GUI.Button(new Rect(1, 1, 20, 20), " +"))
_ME_ShowOptionsInScene = true;
}
else
{
if (GUI.Button(new Rect(1, 1, 20, 20), " -"))
_ME_ShowOptionsInScene = false;
}
Handles.EndGUI();
}
}
//TabChange
void ChangeTab()
{
if (_ME_ExampleObj != null)
DestroyImmediate(_ME_ExampleObj);
}
//UpdateLog
void UpdateLog()
{
_ScrollPos = EditorGUILayout.BeginScrollView(_ScrollPos);
EditorGUILayout.BeginVertical("box");
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Github"))
Application.OpenURL("https://github.com/MarcelvanDuijnDev/Unity-Presets-Scripts-Tools");
EditorGUILayout.EndHorizontal();
GUILayout.Label("Update Log", EditorStyles.boldLabel);
GUILayout.Label(
"\n" +
"V1.0.12 (24-oct-2021)\n" +
"* Added FadeInOut.cs\n" +
"\n" +
"V1.0.11 (17-oct-2021)\n" +
"* Added Multi Select option\n" +
"* Fix MapEditor not working\n" +
"\n" +
"V1.0.10 (15-oct-2021)\n" +
"* Updated AudioHandler code\n" +
"\n" +
"V1.0.9 (5-sep-2021)\n" +
"* Fix QuickUI formating\n" +
"* Added QuickUI profiles\n" +
"* Updated QuickUI editor layout\n" +
"\n" +
"V1.0.8 (22-aug-2021)\n" +
"* Fix update log not scrolling\n" +
"\n" +
"V1.0.7 (20-aug-2021)\n" +
"* Updated AudioZoneBox.cs\n" +
"* Updated AudioZoneSphere.cs\n" +
"\n" +
"V1.0.6 (18-aug-2021)\n" +
"* Added AudioZoneBox.cs\n" +
"* Added AudioZoneSphere.cs\n" +
"\n" +
"V1.0.5 (13-aug-2021)\n" +
"* Added dates to updatelog\n" +
"* Fixed Loading wrong script (SaveLoad_JSON) \n" +
"\n" +
"V1.0.4 (23-jul-2021)\n" +
"* Added DialogSystem.cs + DialogSystemEditor.cs\n" +
"\n" +
"V1.0.3 (22-jul-2021)\n" +
"* Fixed Typo > Scripts\n" +
"\n" +
"V1.0.2 (22-jul-2021)\n" +
"* Added Update log\n" +
"\n" +
"V1.0.1 (22-jul-2021)\n" +
"* Updated Cleanup Script To String (STS)\n" +
"* File Finder (FF) Now updates when changing type\n" +
"\n" +
"V1.0.0 (22-jul-2021)\n" +
"* Start QuickStart update log \n" +
"* Added Scripts\n" +
"* Fixed Scripts formating\n" +
"* Refactor Script To String (STS)");
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
}
public class Tool_QuickStartUI_Tab
{
public GameObject HUD_TabParent;
public List<Tool_QuickStartUI_Object> HUD_TabOjects = new List<Tool_QuickStartUI_Object>();
}
public class Tool_QuickStartUI_Object
{
//Object / Components
public GameObject HUD_Object;
public RectTransform HUD_RectTransform;
//Settings
public string HUD_Name;
public Vector3 HUD_Offset;
public Vector2 HUD_Size = new Vector2(100,25);
public Vector3 HUD_Scale = new Vector3(1,1,1);
public float HUD_TextFontSize = 16;
//Other
public bool HUD_FoldOut;
//DropDown
public enum HUD_Types {Text , Slider, Dropdown, Bar, Button }
public HUD_Types HUD_Type;
public HUD_Types HUD_CheckType;
public enum HUD_Locations {TopLeft,TopMiddle,TopRight,LeftMiddle,RightMiddle,BottomLeft,BottomMiddle,BottomRight,Middle }
public HUD_Locations HUD_Location;
//Info
public List<TextMeshProUGUI> HUD_Text = new List<TextMeshProUGUI>();
}
public class Tool_QuickStart_Script
{
private string _Script_Name;
private string _Script_Tag;
private string _Script_State;
private string _Script_Code;
private string _Script_Path;
public bool Exist;
public string ScriptName { get { return _Script_Name; } }
public string ScriptTag { get { return _Script_Tag; } }
public string ScriptState { get { return _Script_State; } }
public string ScriptCode { get { return _Script_Code; } }
public string ScriptPath { get { return _Script_Path; } set { _Script_Path = value; } }
public Tool_QuickStart_Script(string name, string tags, string state, string code)
{
_Script_Name = name;
_Script_Tag = tags;
_Script_State = state;
_Script_Code = code;
}
} | 109.481182 | 21,722 | 0.580225 | [
"MIT"
] | MarcelvanDuijnDev/UnityPresetsHDRP | Assets/Editor/Tool_QuickStart.cs | 311,257 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Instagram.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Instagram.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<User> userManager,
SignInManager<User> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
//[Required]
//[EmailAddress]
//[Display(Name = "Email")]
//public string Email { get; set; }
[StringLength(30)]
[Required]
[RegularExpression(@"^[a-zA-Z]+[a-zA-Z\d_-]*$")]
//[Remote(action: "VerifyUsername", controller: "Users")]
public string Username { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 5)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public void OnGet(string returnUrl = null)
{
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new User { UserName = Input.Username };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Page(
// "/Account/ConfirmEmail",
// pageHandler: null,
// values: new { userId = user.Id, code = code },
// protocol: Request.Scheme);
//await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
// $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}
| 36.509434 | 132 | 0.577261 | [
"MIT"
] | ParsaHejabi/ASP.NET-Instagram-Project | Instagram/Areas/Identity/Pages/Account/Register.cshtml.cs | 3,872 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using NBitcoin;
using NBitcoin.Crypto;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.Base;
using Stratis.Bitcoin.BlockPulling;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Consensus.Rules;
using Stratis.Bitcoin.Consensus.Validators;
using Stratis.Bitcoin.Features.Consensus.CoinViews;
using Stratis.Bitcoin.Features.Consensus.Rules;
using Stratis.Bitcoin.Features.Consensus.Rules.CommonRules;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.Tests.Common;
using Stratis.Bitcoin.Utilities;
using Xunit;
namespace Stratis.Bitcoin.Features.Consensus.Tests.Rules.CommonRules
{
/// <summary>
/// Test cases related to the <see cref="PosCoinviewRule"/>.
/// </summary>
public class PosCoinViewRuleTests : TestPosConsensusRulesUnitTestBase
{
/// <summary>
/// Creates the consensus manager used by <see cref="PosCoinViewRuleFailsAsync"/>.
/// </summary>
/// <param name="unspentOutputs">The dictionary used to mock up the <see cref="ICoinView"/>.</param>
/// <returns>The constructed consensus manager.</returns>
private async Task<ConsensusManager> CreateConsensusManagerAsync(Dictionary<OutPoint, UnspentOutput> unspentOutputs)
{
this.consensusSettings = new ConsensusSettings(Configuration.NodeSettings.Default(this.network));
var initialBlockDownloadState = new InitialBlockDownloadState(this.chainState.Object, this.network, this.consensusSettings, new Checkpoints(), DateTimeProvider.Default);
var signals = new Signals.Signals(this.loggerFactory.Object, null);
var asyncProvider = new AsyncProvider(this.loggerFactory.Object, signals);
var consensusRulesContainer = new ConsensusRulesContainer();
foreach (var ruleType in this.network.Consensus.ConsensusRules.FullValidationRules)
consensusRulesContainer.FullValidationRules.Add(Activator.CreateInstance(ruleType) as FullValidationConsensusRule);
// Register POS consensus rules.
// new FullNodeBuilderConsensusExtension.PosConsensusRulesRegistration().RegisterRules(this.network.Consensus);
var consensusRuleEngine = new PosConsensusRuleEngine(this.network, this.loggerFactory.Object, DateTimeProvider.Default,
this.ChainIndexer, this.nodeDeployments, this.consensusSettings, this.checkpoints.Object, this.coinView.Object, this.stakeChain.Object,
this.stakeValidator.Object, this.chainState.Object, new InvalidBlockHashStore(this.dateTimeProvider.Object), new Mock<INodeStats>().Object, this.rewindDataIndexStore.Object, this.asyncProvider, consensusRulesContainer)
.SetupRulesEngineParent();
var headerValidator = new HeaderValidator(consensusRuleEngine, this.loggerFactory.Object);
var integrityValidator = new IntegrityValidator(consensusRuleEngine, this.loggerFactory.Object);
var partialValidator = new PartialValidator(asyncProvider, consensusRuleEngine, this.loggerFactory.Object);
var fullValidator = new FullValidator(consensusRuleEngine, this.loggerFactory.Object);
// Create the chained header tree.
var chainedHeaderTree = new ChainedHeaderTree(this.network, this.loggerFactory.Object, headerValidator, this.checkpoints.Object,
this.chainState.Object, new Mock<IFinalizedBlockInfoRepository>().Object, this.consensusSettings, new InvalidBlockHashStore(new DateTimeProvider()), new ChainWorkComparer());
// Create consensus manager.
var consensus = new ConsensusManager(chainedHeaderTree, this.network, this.loggerFactory.Object, this.chainState.Object, integrityValidator,
partialValidator, fullValidator, consensusRuleEngine, new Mock<IFinalizedBlockInfoRepository>().Object, signals,
new Mock<IPeerBanning>().Object, initialBlockDownloadState, this.ChainIndexer, new Mock<IBlockPuller>().Object, new Mock<IBlockStore>().Object,
new Mock<IConnectionManager>().Object, new Mock<INodeStats>().Object, new Mock<INodeLifetime>().Object, this.consensusSettings, this.dateTimeProvider.Object);
// Mock the coinviews "FetchCoinsAsync" method. We will use the "unspentOutputs" dictionary to track spendable outputs.
this.coinView.Setup(d => d.FetchCoins(It.IsAny<OutPoint[]>()))
.Returns((OutPoint[] txIds) =>
{
var result = new FetchCoinsResponse();
for (int i = 0; i < txIds.Length; i++)
{
unspentOutputs.TryGetValue(txIds[i], out UnspentOutput unspent);
result.UnspentOutputs.Add(txIds[i], unspent);
}
return result;
});
// Mock the coinviews "GetTipHashAsync" method.
this.coinView.Setup(d => d.GetTipHash()).Returns(() =>
{
return new HashHeightPair(this.ChainIndexer.Tip);
});
// Since we are mocking the stake validator ensure that GetNextTargetRequired returns something sensible. Otherwise we get the "bad-diffbits" error.
this.stakeValidator.Setup(s => s.GetNextTargetRequired(It.IsAny<IStakeChain>(), It.IsAny<ChainedHeader>(), It.IsAny<IConsensus>(), It.IsAny<bool>()))
.Returns(this.network.Consensus.PowLimit);
// Skip validation of signature in the proven header
this.stakeValidator.Setup(s => s.VerifySignature(It.IsAny<UnspentOutput>(), It.IsAny<Transaction>(), 0, It.IsAny<ScriptVerify>()))
.Returns(true);
// Skip validation of stake kernel
this.stakeValidator.Setup(s => s.CheckStakeKernelHash(It.IsAny<PosRuleContext>(), It.IsAny<uint>(), It.IsAny<uint256>(), It.IsAny<UnspentOutput>(), It.IsAny<OutPoint>(), It.IsAny<uint>()))
.Returns(true);
// Since we are mocking the stakechain ensure that the Get returns a BlockStake. Otherwise this results in "previous stake is not found".
this.stakeChain.Setup(d => d.Get(It.IsAny<uint256>())).Returns(new BlockStake()
{
Flags = BlockFlag.BLOCK_PROOF_OF_STAKE,
StakeModifierV2 = 0,
StakeTime = (this.ChainIndexer.Tip.Header.Time + 60) & ~PosConsensusOptions.StakeTimestampMask
});
// Since we are mocking the chainState ensure that the BlockStoreTip returns a usable value.
this.chainState.Setup(d => d.BlockStoreTip).Returns(this.ChainIndexer.Tip);
// Since we are mocking the chainState ensure that the ConsensusTip returns a usable value.
this.chainState.Setup(d => d.ConsensusTip).Returns(this.ChainIndexer.Tip);
// Initialize the consensus manager.
await consensus.InitializeAsync(this.ChainIndexer.Tip);
return consensus;
}
/// <summary>
/// Tests whether an error is raised when a miner attempts to stake an output which he can't spend with his private key.
/// </summary>
/// <remarks>
/// <para>Create a "previous transaction" with 2 outputs. The first output is sent to miner 2 and the second output is sent to miner 1.
/// Now miner 2 creates a proof of stake block with coinstake transaction which will have two inputs corresponding to both the
/// outputs of the previous transaction. The coinstake transaction will be just two outputs, first is the coinstake marker and
/// the second is normal pay to public key that belongs to miner 2 with value that equals to the sum of the inputs.
/// The testable outcome is whether the consensus engine accepts such a block. Obviously, the test should fail if the block is accepted.
/// </para><para>
/// We use <see cref="ConsensusManager.BlockMinedAsync(Block)"/> to run partial validation and full validation rules and expect that
/// the rules engine will reject the block with the specific error of <see cref="ConsensusErrors.BadTransactionScriptError"/>,
/// which confirms that there was no valid signature on the second input - which corresponds to the output sent to miner 1.
/// </para></remarks>
[Fact]
public async Task PosCoinViewRuleFailsAsync()
{
var unspentOutputs = new Dictionary<OutPoint, UnspentOutput>();
ConsensusManager consensusManager = await this.CreateConsensusManagerAsync(unspentOutputs);
// The keys used by miner 1 and miner 2.
var minerKey1 = new Key();
var minerKey2 = new Key();
// The scriptPubKeys (P2PK) of the miners.
Script scriptPubKey1 = minerKey1.PubKey.ScriptPubKey;
Script scriptPubKey2 = minerKey2.PubKey.ScriptPubKey;
// Create the block that we want to validate.
Block block = this.network.Consensus.ConsensusFactory.CreateBlock();
// Add dummy first transaction.
Transaction transaction = this.network.CreateTransaction();
transaction.Inputs.Add(TxIn.CreateCoinbase(this.ChainIndexer.Tip.Height + 1));
transaction.Outputs.Add(new TxOut(Money.Zero, (IDestination)null));
Assert.True(transaction.IsCoinBase);
// Add first transaction to block.
block.Transactions.Add(transaction);
// Create a previous transaction with scriptPubKey outputs.
Transaction prevTransaction = this.network.CreateTransaction();
uint blockTime = (this.ChainIndexer.Tip.Header.Time + 60) & ~PosConsensusOptions.StakeTimestampMask;
// Coins sent to miner 2.
prevTransaction.Outputs.Add(new TxOut(Money.COIN * 5_000_000, scriptPubKey2));
// Coins sent to miner 1.
prevTransaction.Outputs.Add(new TxOut(Money.COIN * 10_000_000, scriptPubKey1));
// Record the spendable outputs.
unspentOutputs.Add(new OutPoint(prevTransaction, 0), new UnspentOutput(new OutPoint(prevTransaction, 0), new Coins(1, prevTransaction.Outputs[0], prevTransaction.IsCoinBase)));
unspentOutputs.Add(new OutPoint(prevTransaction, 1), new UnspentOutput(new OutPoint(prevTransaction, 1), new Coins(1, prevTransaction.Outputs[1], prevTransaction.IsCoinBase)));
// Create coin stake transaction.
Transaction coinstakeTransaction = this.network.CreateTransaction();
coinstakeTransaction.Inputs.Add(new TxIn(new OutPoint(prevTransaction, 0)));
coinstakeTransaction.Inputs.Add(new TxIn(new OutPoint(prevTransaction, 1)));
// Coinstake marker.
coinstakeTransaction.Outputs.Add(new TxOut(Money.Zero, (IDestination)null));
// We need to pay the Cirrus reward to the correct scriptPubKey to prevent failing that consensus rule.
coinstakeTransaction.Outputs.Add(new TxOut(Money.COIN * 9, StraxCoinstakeRule.CirrusRewardScript));
// Normal pay to public key that belongs to the second miner with value that
// equals to the sum of the inputs.
coinstakeTransaction.Outputs.Add(new TxOut(Money.COIN * 15_000_000, scriptPubKey2));
// The second miner signs the first transaction input which requires minerKey2.
// Miner 2 will not have minerKey1 so we leave the second ScriptSig empty/invalid.
new TransactionBuilder(this.network)
.AddKeys(minerKey2)
.AddCoins(new Coin(new OutPoint(prevTransaction, 0), prevTransaction.Outputs[0]))
.SignTransactionInPlace(coinstakeTransaction);
Assert.True(coinstakeTransaction.IsCoinStake);
// Add second transaction to block.
block.Transactions.Add(coinstakeTransaction);
// Finalize the block and add it to the chain.
block.Header.HashPrevBlock = this.ChainIndexer.Tip.HashBlock;
block.Header.Time = blockTime;
block.Header.Bits = block.Header.GetWorkRequired(this.network, this.ChainIndexer.Tip);
block.SetPrivatePropertyValue("BlockSize", 1L);
block.UpdateMerkleRoot();
Assert.True(BlockStake.IsProofOfStake(block));
// Add a signature to the block.
ECDSASignature signature = minerKey2.Sign(block.GetHash());
(block as PosBlock).BlockSignature = new BlockSignature { Signature = signature.ToDER() };
// Execute the rule and check the outcome against what is expected.
ConsensusException error = await Assert.ThrowsAsync<ConsensusException>(async () => await consensusManager.BlockMinedAsync(block));
Assert.Equal(ConsensusErrors.BadTransactionScriptError.Message, error.Message);
}
}
}
| 59.348416 | 234 | 0.682601 | [
"MIT"
] | Amazastrophic/StratisFullNode | src/Stratis.Bitcoin.Features.Consensus.Tests/Rules/CommonRules/PosCoinViewRuleTest.cs | 13,118 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace NetCoreMicro.Common.Events
{
public class CreateActivityRejected : IRejectedEvent
{
public Guid Id { get; set; }
public string Reason { get; set; }
public string Code { get; set; }
protected CreateActivityRejected()
{
}
public CreateActivityRejected(Guid id,
string code, string reason)
{
Id = id;
Code = code;
Reason = reason;
}
}
}
| 20.296296 | 56 | 0.565693 | [
"MIT"
] | lucasven/NetCoreMicro | NetCoreMicro.Common/Events/CreateActivityRejected.cs | 550 | C# |
using AutoMapper;
using NetCoreLibrary.Core.Domain;
using NetCoreLibrary.Core.DTOs;
using System;
namespace NetCoreLibrary.Web.Infrastructure.AutoMappers
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
VehicleMap();
CustomerMap();
EventMap();
}
public void CustomerMap()
{
/// <summary>
/// Dönüştürmek istediğimiz class ile entity class ı arasında property farklılıkları var ise ForMember ile belirtmeliyiz.
/// dest : Dönüştürmek istediğim class'ım
/// src : dönüşüm için ihtiyacım olan class
/// </summary>
CreateMap<Customer, CustomerDTO>()
.IncludeMembers(p => p.Vehicle) //Vehicle içerisindeki property'leri DTO classındaki property'lere mapleyecek (isimler aynı olmalı)
.ForMember(dest => dest.DateOfBirth, src => src.MapFrom(p => p.BirthDay)) //Source ile Destination property isimleri farklı olduğu için automapper'a bildiriyorum.
.ForMember(dest => dest.Mail, src => src.MapFrom(p => p.Email))
.ForMember(dest => dest.FullName, src => src.MapFrom(p => p.NameAndLastName())) //Metot ile property eşleştirmesi
.ForMember(dest => dest.CVV, src => src.MapFrom(p => p.CreditCard.CardValidationValue))
.ReverseMap();
}
public void VehicleMap()
{
CreateMap<Vehicle, CustomerDTO>().ReverseMap(); //IncludeMembers için bu map'i yapmalıyız.
}
public void EventMap()
{
//Note: Dağıtık property'lerde ReverseMap() çalışmaz.
CreateMap<EventDateDTO, EventDate>()
.ForMember(src => src.Date, dest => dest.MapFrom(dest => new DateTime(dest.Year, dest.Month, dest.Day)));
CreateMap<EventDate, EventDateDTO>()
.ForMember(src => src.Year, dest => dest.MapFrom(dest => dest.Date.Year))
.ForMember(src => src.Month, dest => dest.MapFrom(dest => dest.Date.Month))
.ForMember(src => src.Day, dest => dest.MapFrom(dest => dest.Date.Day));
}
}
}
| 42.076923 | 178 | 0.600091 | [
"MIT"
] | cihatsolak/netcore-librarires | NetCoreImportantLibraries/NetCoreLibrary.Web/Infrastructure/AutoMappers/AutoMapperProfile.cs | 2,230 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472)
// Version 5.472.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Drawing;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Draws a separator at the bottom of the tabs when ribbon minimized.
/// </summary>
internal class ViewDrawRibbonMinimizeBar : ViewLayoutRibbonSeparator
{
#region Static Fields
private const int SEP_WIDTH = 2;
#endregion
#region Instance Fields
private readonly IPaletteRibbonGeneral _palette;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawRibbonMinimizeBar class.
/// </summary>
/// <param name="palette">Source for palette values.</param>
public ViewDrawRibbonMinimizeBar(IPaletteRibbonGeneral palette)
: base(SEP_WIDTH, true)
{
Debug.Assert(palette != null);
_palette = palette;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawRibbonMinimizeBar:" + Id;
}
#endregion
#region Paint
/// <summary>
/// Perform rendering before child elements are rendered.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void RenderBefore(RenderContext context)
{
using (Pen darkPen = new Pen(_palette.GetRibbonMinimizeBarDark(PaletteState.Normal)),
lightPen = new Pen(_palette.GetRibbonMinimizeBarLight(PaletteState.Normal)))
{
context.Graphics.DrawLine(darkPen, ClientRectangle.Left, ClientRectangle.Bottom - 2, ClientRectangle.Right - 1, ClientRectangle.Bottom - 2);
context.Graphics.DrawLine(lightPen, ClientRectangle.Left, ClientRectangle.Bottom - 1, ClientRectangle.Right - 1, ClientRectangle.Bottom - 1);
}
}
#endregion
}
}
| 40.123288 | 157 | 0.616251 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.472 | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonMinimizeBar.cs | 2,932 | C# |
using System;
using Xunit;
using Caf.Etl.Nodes.CosmosDBSqlApi.Extract;
using Caf.Etl.Models.CosmosDBSqlApi.Core;
using System.Collections.Generic;
using Caf.Etl.Nodes.CosmosDBSqlApi.Transform;
using Caf.Etl.Models.LtarDataPortal.CORe;
using System.Globalization;
using Caf.Etl.Models.CosmosDBSqlApi.Measurement;
namespace Caf.Etl.Nodes.CosmosDBSqlApi.Tests
{
public class LtarDataPortalCOReTransformerTests
{
[Fact]
public void ToCOReContent_ValidData_ReturnsCorrectCORe()
{
// Arrange
LtarDataPortalCOReTransformer sut = new LtarDataPortalCOReTransformer();
List<Observation> expected = getValidObservations();
// Act
List<Observation> actual = sut.ToCOReObservations("CAF", "001", 'L', -8, getValidMeasurements());
// Assert
// TODO: Add Equals functions to Measurement class
Assert.Equal(expected[0].AirPressure, actual[0].AirPressure);
Assert.Equal(expected[0].AirTemperature, actual[0].AirTemperature);
Assert.Equal(expected[0].BatteryVoltage, actual[0].BatteryVoltage);
Assert.Equal(expected[0].DateTime, actual[0].DateTime);
Assert.Equal(expected[0].LoggerTemperature, actual[0].LoggerTemperature);
Assert.Equal(expected[0].LongWaveIn, actual[0].LongWaveIn);
Assert.Equal(expected[0].LTARSiteAcronym, actual[0].LTARSiteAcronym);
Assert.Equal(expected[0].PAR, actual[0].PAR);
Assert.Equal(expected[0].Precipitation, actual[0].Precipitation);
Assert.Equal(expected[0].RecordType, actual[0].RecordType);
Assert.Equal(expected[0].RelativeHumidity, actual[0].RelativeHumidity);
Assert.Equal(expected[0].ShortWaveIn, actual[0].ShortWaveIn);
Assert.Equal(expected[0].StationID, actual[0].StationID);
Assert.Equal(expected[0].WindDirection, actual[0].WindDirection);
Assert.Equal(expected[0].WindSpeed, actual[0].WindSpeed);
}
private List<MeasurementV1> getValidMeasurements()
{
List<MeasurementV1> results = new List<MeasurementV1>()
{
new MeasurementV1(
"", "", "", "WindSpeedTsResultant", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(3.014338m, "m/s", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "TemperatureAirTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(27.80702m, "C", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "PrecipitationTsAccum", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(0m, "m", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "WindDirection", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(125.9m, "deg", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "RelativeHumidityTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(22.4503m, "%", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "BatteryVoltageTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(13.01541m, "V", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "PressureAirTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(93334.82m, "Pa", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "ParDensityTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(0.0002833229m, "mol/(m^2 s)", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
}),
new MeasurementV1(
"", "", "", "TemperaturePanelTsAvg", "", "", "", "", "", "", null, "", null, DateTime.ParseExact("2017-09-06T00:00:00Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), new List<PhysicalQuantityV1>()
{
new PhysicalQuantityV1(29.87764m, "C", 0, 0, 0, DateTime.Parse("2017-09-06T00:04:15.9797575Z"), "DocumentDbMeasurementTransformer")
})
};
return results;
}
private List<Observation> getValidObservations()
{
List<Observation> result = new List<Observation>()
{
new Observation("CAF", "001", new DateTimeOffset(2017, 09, 05, 16, 0, 0, new TimeSpan(-8, 0, 0)), -8, 'L', 27.80702m, 3.014338m, 125.9m, 22.4503m, 0, 93.33482m, 283.3229m, null, null, 13.01541m, 29.87764m)
};
return result;
}
}
}
| 68.827273 | 298 | 0.589486 | [
"CC0-1.0"
] | benichka/Caf.Etl | Caf.Etl.UnitTests/Nodes/CosmosDBSqlApi/LtarDataPortalCOReTransformerTests.cs | 7,571 | C# |
using lox.constants;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using static lox.Expr;
namespace lox.test.parser
{
[TestClass]
public class LogicalExprTest : ParserTestBase
{
#region Instance Methods
[TestMethod]
public void CanParseLogicalAndExpression()
{
var source = "true and 1 == 1";
var expr = this.AssertExpr<Logical>(source);
this.AssertExpr<Literal>(expr.left);
this.AssertExpr<Binary>(expr.right);
Assert.AreEqual(TokenType.AND,
expr.op.Type);
}
[TestMethod]
public void CanParseLogicalOrExpression()
{
var source = "true or false";
var expr = this.AssertExpr<Logical>(source);
this.AssertExpr<Literal>(expr.left);
this.AssertExpr<Literal>(expr.right);
Assert.AreEqual(TokenType.OR,
expr.op.Type);
}
#endregion
}
} | 25.375 | 56 | 0.562562 | [
"MIT"
] | andrewtyped/cslox | test/lox.test/parser/LogicalExprTest.cs | 1,017 | 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 codebuild-2016-10-06.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.CodeBuild.Model;
using Amazon.CodeBuild.Model.Internal.MarshallTransformations;
using Amazon.CodeBuild.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CodeBuild
{
/// <summary>
/// Implementation for accessing CodeBuild
///
/// AWS CodeBuild
/// <para>
/// AWS CodeBuild is a fully managed build service in the cloud. AWS CodeBuild compiles
/// your source code, runs unit tests, and produces artifacts that are ready to deploy.
/// AWS CodeBuild eliminates the need to provision, manage, and scale your own build servers.
/// It provides prepackaged build environments for the most popular programming languages
/// and build tools, such as Apache Maven, Gradle, and more. You can also fully customize
/// build environments in AWS CodeBuild to use your own build tools. AWS CodeBuild scales
/// automatically to meet peak build requests. You pay only for the build time you consume.
/// For more information about AWS CodeBuild, see the <i> <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html">AWS
/// CodeBuild User Guide</a>.</i>
/// </para>
///
/// <para>
/// AWS CodeBuild supports these operations:
/// </para>
/// <ul> <li>
/// <para>
/// <code>BatchDeleteBuilds</code>: Deletes one or more builds.
/// </para>
/// </li> <li>
/// <para>
/// <code>BatchGetBuilds</code>: Gets information about one or more builds.
/// </para>
/// </li> <li>
/// <para>
/// <code>BatchGetProjects</code>: Gets information about one or more build projects.
/// A <i>build project</i> defines how AWS CodeBuild runs a build. This includes information
/// such as where to get the source code to build, the build environment to use, the build
/// commands to run, and where to store the build output. A <i>build environment</i> is
/// a representation of operating system, programming language runtime, and tools that
/// AWS CodeBuild uses to run a build. You can add tags to build projects to help manage
/// your resources and costs.
/// </para>
/// </li> <li>
/// <para>
/// <code>BatchGetReportGroups</code>: Returns an array of report groups.
/// </para>
/// </li> <li>
/// <para>
/// <code>BatchGetReports</code>: Returns an array of reports.
/// </para>
/// </li> <li>
/// <para>
/// <code>CreateProject</code>: Creates a build project.
/// </para>
/// </li> <li>
/// <para>
/// <code>CreateReportGroup</code>: Creates a report group. A report group contains a
/// collection of reports.
/// </para>
/// </li> <li>
/// <para>
/// <code>CreateWebhook</code>: For an existing AWS CodeBuild build project that has
/// its source code stored in a GitHub or Bitbucket repository, enables AWS CodeBuild
/// to start rebuilding the source code every time a code change is pushed to the repository.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteProject</code>: Deletes a build project.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteReport</code>: Deletes a report.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteReportGroup</code>: Deletes a report group.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteResourcePolicy</code>: Deletes a resource policy that is identified by
/// its resource ARN.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteSourceCredentials</code>: Deletes a set of GitHub, GitHub Enterprise,
/// or Bitbucket source credentials.
/// </para>
/// </li> <li>
/// <para>
/// <code>DeleteWebhook</code>: For an existing AWS CodeBuild build project that has
/// its source code stored in a GitHub or Bitbucket repository, stops AWS CodeBuild from
/// rebuilding the source code every time a code change is pushed to the repository.
/// </para>
/// </li> <li>
/// <para>
/// <code>DescribeTestCases</code>: Returns a list of details about test cases for a
/// report.
/// </para>
/// </li> <li>
/// <para>
/// <code>GetResourcePolicy</code>: Gets a resource policy that is identified by its
/// resource ARN.
/// </para>
/// </li> <li>
/// <para>
/// <code>ImportSourceCredentials</code>: Imports the source repository credentials for
/// an AWS CodeBuild project that has its source code stored in a GitHub, GitHub Enterprise,
/// or Bitbucket repository.
/// </para>
/// </li> <li>
/// <para>
/// <code>InvalidateProjectCache</code>: Resets the cache for a project.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListBuilds</code>: Gets a list of build IDs, with each build ID representing
/// a single build.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListBuildsForProject</code>: Gets a list of build IDs for the specified build
/// project, with each build ID representing a single build.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListCuratedEnvironmentImages</code>: Gets information about Docker images that
/// are managed by AWS CodeBuild.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListProjects</code>: Gets a list of build project names, with each build project
/// name representing a single build project.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListReportGroups</code>: Gets a list ARNs for the report groups in the current
/// AWS account.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListReports</code>: Gets a list ARNs for the reports in the current AWS account.
///
/// </para>
/// </li> <li>
/// <para>
/// <code>ListReportsForReportGroup</code>: Returns a list of ARNs for the reports that
/// belong to a <code>ReportGroup</code>.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListSharedProjects</code>: Gets a list of ARNs associated with projects shared
/// with the current AWS account or user.
/// </para>
/// </li> <li>
/// <para>
/// <code>ListSharedReportGroups</code>: Gets a list of ARNs associated with report groups
/// shared with the current AWS account or user
/// </para>
/// </li> <li>
/// <para>
/// <code>ListSourceCredentials</code>: Returns a list of <code>SourceCredentialsInfo</code>
/// objects. Each <code>SourceCredentialsInfo</code> object includes the authentication
/// type, token ARN, and type of source provider for one set of credentials.
/// </para>
/// </li> <li>
/// <para>
/// <code>PutResourcePolicy</code>: Stores a resource policy for the ARN of a <code>Project</code>
/// or <code>ReportGroup</code> object.
/// </para>
/// </li> <li>
/// <para>
/// <code>StartBuild</code>: Starts running a build.
/// </para>
/// </li> <li>
/// <para>
/// <code>StopBuild</code>: Attempts to stop running a build.
/// </para>
/// </li> <li>
/// <para>
/// <code>UpdateProject</code>: Changes the settings of an existing build project.
/// </para>
/// </li> <li>
/// <para>
/// <code>UpdateReportGroup</code>: Changes a report group.
/// </para>
/// </li> <li>
/// <para>
/// <code>UpdateWebhook</code>: Changes the settings of an existing webhook.
/// </para>
/// </li> </ul>
/// </summary>
public partial class AmazonCodeBuildClient : AmazonServiceClient, IAmazonCodeBuild
{
private static IServiceMetadata serviceMetadata = new AmazonCodeBuildMetadata();
private ICodeBuildPaginatorFactory _paginators;
/// <summary>
/// Paginators for the service
/// </summary>
public ICodeBuildPaginatorFactory Paginators
{
get
{
if (this._paginators == null)
{
this._paginators = new CodeBuildPaginatorFactory(this);
}
return this._paginators;
}
}
#region Constructors
/// <summary>
/// Constructs AmazonCodeBuildClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCodeBuildClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeBuildConfig()) { }
/// <summary>
/// Constructs AmazonCodeBuildClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCodeBuildClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeBuildConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCodeBuildClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCodeBuildClient Configuration Object</param>
public AmazonCodeBuildClient(AmazonCodeBuildConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCodeBuildClient(AWSCredentials credentials)
: this(credentials, new AmazonCodeBuildConfig())
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeBuildClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCodeBuildConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Credentials and an
/// AmazonCodeBuildClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCodeBuildClient Configuration Object</param>
public AmazonCodeBuildClient(AWSCredentials credentials, AmazonCodeBuildConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeBuildConfig())
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeBuildConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeBuildClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCodeBuildClient Configuration Object</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCodeBuildConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeBuildConfig())
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeBuildConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeBuildClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeBuildClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCodeBuildClient Configuration Object</param>
public AmazonCodeBuildClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCodeBuildConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region BatchDeleteBuilds
/// <summary>
/// Deletes one or more builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchDeleteBuilds service method.</param>
///
/// <returns>The response from the BatchDeleteBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchDeleteBuilds">REST API Reference for BatchDeleteBuilds Operation</seealso>
public virtual BatchDeleteBuildsResponse BatchDeleteBuilds(BatchDeleteBuildsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchDeleteBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchDeleteBuildsResponseUnmarshaller.Instance;
return Invoke<BatchDeleteBuildsResponse>(request, options);
}
/// <summary>
/// Deletes one or more builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchDeleteBuilds service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchDeleteBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchDeleteBuilds">REST API Reference for BatchDeleteBuilds Operation</seealso>
public virtual Task<BatchDeleteBuildsResponse> BatchDeleteBuildsAsync(BatchDeleteBuildsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchDeleteBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchDeleteBuildsResponseUnmarshaller.Instance;
return InvokeAsync<BatchDeleteBuildsResponse>(request, options, cancellationToken);
}
#endregion
#region BatchGetBuildBatches
/// <summary>
/// Retrieves information about one or more batch builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetBuildBatches service method.</param>
///
/// <returns>The response from the BatchGetBuildBatches service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildBatches">REST API Reference for BatchGetBuildBatches Operation</seealso>
public virtual BatchGetBuildBatchesResponse BatchGetBuildBatches(BatchGetBuildBatchesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetBuildBatchesRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetBuildBatchesResponseUnmarshaller.Instance;
return Invoke<BatchGetBuildBatchesResponse>(request, options);
}
/// <summary>
/// Retrieves information about one or more batch builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetBuildBatches service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchGetBuildBatches service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildBatches">REST API Reference for BatchGetBuildBatches Operation</seealso>
public virtual Task<BatchGetBuildBatchesResponse> BatchGetBuildBatchesAsync(BatchGetBuildBatchesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetBuildBatchesRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetBuildBatchesResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetBuildBatchesResponse>(request, options, cancellationToken);
}
#endregion
#region BatchGetBuilds
/// <summary>
/// Gets information about one or more builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetBuilds service method.</param>
///
/// <returns>The response from the BatchGetBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuilds">REST API Reference for BatchGetBuilds Operation</seealso>
public virtual BatchGetBuildsResponse BatchGetBuilds(BatchGetBuildsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetBuildsResponseUnmarshaller.Instance;
return Invoke<BatchGetBuildsResponse>(request, options);
}
/// <summary>
/// Gets information about one or more builds.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetBuilds service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchGetBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuilds">REST API Reference for BatchGetBuilds Operation</seealso>
public virtual Task<BatchGetBuildsResponse> BatchGetBuildsAsync(BatchGetBuildsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetBuildsResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetBuildsResponse>(request, options, cancellationToken);
}
#endregion
#region BatchGetProjects
/// <summary>
/// Gets information about one or more build projects.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetProjects service method.</param>
///
/// <returns>The response from the BatchGetProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetProjects">REST API Reference for BatchGetProjects Operation</seealso>
public virtual BatchGetProjectsResponse BatchGetProjects(BatchGetProjectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetProjectsResponseUnmarshaller.Instance;
return Invoke<BatchGetProjectsResponse>(request, options);
}
/// <summary>
/// Gets information about one or more build projects.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetProjects service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchGetProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetProjects">REST API Reference for BatchGetProjects Operation</seealso>
public virtual Task<BatchGetProjectsResponse> BatchGetProjectsAsync(BatchGetProjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetProjectsResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetProjectsResponse>(request, options, cancellationToken);
}
#endregion
#region BatchGetReportGroups
/// <summary>
/// Returns an array of report groups.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetReportGroups service method.</param>
///
/// <returns>The response from the BatchGetReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReportGroups">REST API Reference for BatchGetReportGroups Operation</seealso>
public virtual BatchGetReportGroupsResponse BatchGetReportGroups(BatchGetReportGroupsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetReportGroupsResponseUnmarshaller.Instance;
return Invoke<BatchGetReportGroupsResponse>(request, options);
}
/// <summary>
/// Returns an array of report groups.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetReportGroups service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchGetReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReportGroups">REST API Reference for BatchGetReportGroups Operation</seealso>
public virtual Task<BatchGetReportGroupsResponse> BatchGetReportGroupsAsync(BatchGetReportGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetReportGroupsResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetReportGroupsResponse>(request, options, cancellationToken);
}
#endregion
#region BatchGetReports
/// <summary>
/// Returns an array of reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetReports service method.</param>
///
/// <returns>The response from the BatchGetReports service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReports">REST API Reference for BatchGetReports Operation</seealso>
public virtual BatchGetReportsResponse BatchGetReports(BatchGetReportsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetReportsResponseUnmarshaller.Instance;
return Invoke<BatchGetReportsResponse>(request, options);
}
/// <summary>
/// Returns an array of reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetReports service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchGetReports service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetReports">REST API Reference for BatchGetReports Operation</seealso>
public virtual Task<BatchGetReportsResponse> BatchGetReportsAsync(BatchGetReportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetReportsResponseUnmarshaller.Instance;
return InvokeAsync<BatchGetReportsResponse>(request, options, cancellationToken);
}
#endregion
#region CreateProject
/// <summary>
/// Creates a build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateProject service method.</param>
///
/// <returns>The response from the CreateProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateProject">REST API Reference for CreateProject Operation</seealso>
public virtual CreateProjectResponse CreateProject(CreateProjectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateProjectResponseUnmarshaller.Instance;
return Invoke<CreateProjectResponse>(request, options);
}
/// <summary>
/// Creates a build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateProject service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateProject">REST API Reference for CreateProject Operation</seealso>
public virtual Task<CreateProjectResponse> CreateProjectAsync(CreateProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateProjectResponseUnmarshaller.Instance;
return InvokeAsync<CreateProjectResponse>(request, options, cancellationToken);
}
#endregion
#region CreateReportGroup
/// <summary>
/// Creates a report group. A report group contains a collection of reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateReportGroup service method.</param>
///
/// <returns>The response from the CreateReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateReportGroup">REST API Reference for CreateReportGroup Operation</seealso>
public virtual CreateReportGroupResponse CreateReportGroup(CreateReportGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateReportGroupResponseUnmarshaller.Instance;
return Invoke<CreateReportGroupResponse>(request, options);
}
/// <summary>
/// Creates a report group. A report group contains a collection of reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateReportGroup service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateReportGroup">REST API Reference for CreateReportGroup Operation</seealso>
public virtual Task<CreateReportGroupResponse> CreateReportGroupAsync(CreateReportGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateReportGroupResponseUnmarshaller.Instance;
return InvokeAsync<CreateReportGroupResponse>(request, options, cancellationToken);
}
#endregion
#region CreateWebhook
/// <summary>
/// For an existing AWS CodeBuild build project that has its source code stored in a GitHub
/// or Bitbucket repository, enables AWS CodeBuild to start rebuilding the source code
/// every time a code change is pushed to the repository.
///
/// <important>
/// <para>
/// If you enable webhooks for an AWS CodeBuild project, and the project is used as a
/// build step in AWS CodePipeline, then two identical builds are created for each commit.
/// One build is triggered through webhooks, and one through AWS CodePipeline. Because
/// billing is on a per-build basis, you are billed for both builds. Therefore, if you
/// are using AWS CodePipeline, we recommend that you disable webhooks in AWS CodeBuild.
/// In the AWS CodeBuild console, clear the Webhook box. For more information, see step
/// 5 in <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-console">Change
/// a Build Project's Settings</a>.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateWebhook service method.</param>
///
/// <returns>The response from the CreateWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateWebhook">REST API Reference for CreateWebhook Operation</seealso>
public virtual CreateWebhookResponse CreateWebhook(CreateWebhookRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateWebhookResponseUnmarshaller.Instance;
return Invoke<CreateWebhookResponse>(request, options);
}
/// <summary>
/// For an existing AWS CodeBuild build project that has its source code stored in a GitHub
/// or Bitbucket repository, enables AWS CodeBuild to start rebuilding the source code
/// every time a code change is pushed to the repository.
///
/// <important>
/// <para>
/// If you enable webhooks for an AWS CodeBuild project, and the project is used as a
/// build step in AWS CodePipeline, then two identical builds are created for each commit.
/// One build is triggered through webhooks, and one through AWS CodePipeline. Because
/// billing is on a per-build basis, you are billed for both builds. Therefore, if you
/// are using AWS CodePipeline, we recommend that you disable webhooks in AWS CodeBuild.
/// In the AWS CodeBuild console, clear the Webhook box. For more information, see step
/// 5 in <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-console">Change
/// a Build Project's Settings</a>.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateWebhook service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/CreateWebhook">REST API Reference for CreateWebhook Operation</seealso>
public virtual Task<CreateWebhookResponse> CreateWebhookAsync(CreateWebhookRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateWebhookResponseUnmarshaller.Instance;
return InvokeAsync<CreateWebhookResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteBuildBatch
/// <summary>
/// Deletes a batch build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBuildBatch service method.</param>
///
/// <returns>The response from the DeleteBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteBuildBatch">REST API Reference for DeleteBuildBatch Operation</seealso>
public virtual DeleteBuildBatchResponse DeleteBuildBatch(DeleteBuildBatchRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBuildBatchResponseUnmarshaller.Instance;
return Invoke<DeleteBuildBatchResponse>(request, options);
}
/// <summary>
/// Deletes a batch build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBuildBatch service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteBuildBatch">REST API Reference for DeleteBuildBatch Operation</seealso>
public virtual Task<DeleteBuildBatchResponse> DeleteBuildBatchAsync(DeleteBuildBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBuildBatchResponseUnmarshaller.Instance;
return InvokeAsync<DeleteBuildBatchResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteProject
/// <summary>
/// Deletes a build project. When you delete a project, its builds are not deleted.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteProject service method.</param>
///
/// <returns>The response from the DeleteProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteProject">REST API Reference for DeleteProject Operation</seealso>
public virtual DeleteProjectResponse DeleteProject(DeleteProjectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProjectResponseUnmarshaller.Instance;
return Invoke<DeleteProjectResponse>(request, options);
}
/// <summary>
/// Deletes a build project. When you delete a project, its builds are not deleted.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteProject service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteProject">REST API Reference for DeleteProject Operation</seealso>
public virtual Task<DeleteProjectResponse> DeleteProjectAsync(DeleteProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProjectResponseUnmarshaller.Instance;
return InvokeAsync<DeleteProjectResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteReport
/// <summary>
/// Deletes a report.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteReport service method.</param>
///
/// <returns>The response from the DeleteReport service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReport">REST API Reference for DeleteReport Operation</seealso>
public virtual DeleteReportResponse DeleteReport(DeleteReportRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteReportRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteReportResponseUnmarshaller.Instance;
return Invoke<DeleteReportResponse>(request, options);
}
/// <summary>
/// Deletes a report.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteReport service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteReport service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReport">REST API Reference for DeleteReport Operation</seealso>
public virtual Task<DeleteReportResponse> DeleteReportAsync(DeleteReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteReportRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteReportResponseUnmarshaller.Instance;
return InvokeAsync<DeleteReportResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteReportGroup
/// <summary>
/// Deletes a report group. Before you delete a report group, you must delete its reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteReportGroup service method.</param>
///
/// <returns>The response from the DeleteReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReportGroup">REST API Reference for DeleteReportGroup Operation</seealso>
public virtual DeleteReportGroupResponse DeleteReportGroup(DeleteReportGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteReportGroupResponseUnmarshaller.Instance;
return Invoke<DeleteReportGroupResponse>(request, options);
}
/// <summary>
/// Deletes a report group. Before you delete a report group, you must delete its reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteReportGroup service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteReportGroup">REST API Reference for DeleteReportGroup Operation</seealso>
public virtual Task<DeleteReportGroupResponse> DeleteReportGroupAsync(DeleteReportGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteReportGroupResponseUnmarshaller.Instance;
return InvokeAsync<DeleteReportGroupResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteResourcePolicy
/// <summary>
/// Deletes a resource policy that is identified by its resource ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteResourcePolicy service method.</param>
///
/// <returns>The response from the DeleteResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteResourcePolicy">REST API Reference for DeleteResourcePolicy Operation</seealso>
public virtual DeleteResourcePolicyResponse DeleteResourcePolicy(DeleteResourcePolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteResourcePolicyResponseUnmarshaller.Instance;
return Invoke<DeleteResourcePolicyResponse>(request, options);
}
/// <summary>
/// Deletes a resource policy that is identified by its resource ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteResourcePolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteResourcePolicy">REST API Reference for DeleteResourcePolicy Operation</seealso>
public virtual Task<DeleteResourcePolicyResponse> DeleteResourcePolicyAsync(DeleteResourcePolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteResourcePolicyResponseUnmarshaller.Instance;
return InvokeAsync<DeleteResourcePolicyResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteSourceCredentials
/// <summary>
/// Deletes a set of GitHub, GitHub Enterprise, or Bitbucket source credentials.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSourceCredentials service method.</param>
///
/// <returns>The response from the DeleteSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteSourceCredentials">REST API Reference for DeleteSourceCredentials Operation</seealso>
public virtual DeleteSourceCredentialsResponse DeleteSourceCredentials(DeleteSourceCredentialsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteSourceCredentialsResponseUnmarshaller.Instance;
return Invoke<DeleteSourceCredentialsResponse>(request, options);
}
/// <summary>
/// Deletes a set of GitHub, GitHub Enterprise, or Bitbucket source credentials.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSourceCredentials service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteSourceCredentials">REST API Reference for DeleteSourceCredentials Operation</seealso>
public virtual Task<DeleteSourceCredentialsResponse> DeleteSourceCredentialsAsync(DeleteSourceCredentialsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteSourceCredentialsResponseUnmarshaller.Instance;
return InvokeAsync<DeleteSourceCredentialsResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteWebhook
/// <summary>
/// For an existing AWS CodeBuild build project that has its source code stored in a GitHub
/// or Bitbucket repository, stops AWS CodeBuild from rebuilding the source code every
/// time a code change is pushed to the repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteWebhook service method.</param>
///
/// <returns>The response from the DeleteWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteWebhook">REST API Reference for DeleteWebhook Operation</seealso>
public virtual DeleteWebhookResponse DeleteWebhook(DeleteWebhookRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteWebhookResponseUnmarshaller.Instance;
return Invoke<DeleteWebhookResponse>(request, options);
}
/// <summary>
/// For an existing AWS CodeBuild build project that has its source code stored in a GitHub
/// or Bitbucket repository, stops AWS CodeBuild from rebuilding the source code every
/// time a code change is pushed to the repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteWebhook service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteWebhook">REST API Reference for DeleteWebhook Operation</seealso>
public virtual Task<DeleteWebhookResponse> DeleteWebhookAsync(DeleteWebhookRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteWebhookResponseUnmarshaller.Instance;
return InvokeAsync<DeleteWebhookResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeCodeCoverages
/// <summary>
/// Retrieves one or more code coverage reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeCodeCoverages service method.</param>
///
/// <returns>The response from the DescribeCodeCoverages service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeCodeCoverages">REST API Reference for DescribeCodeCoverages Operation</seealso>
public virtual DescribeCodeCoveragesResponse DescribeCodeCoverages(DescribeCodeCoveragesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeCodeCoveragesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeCodeCoveragesResponseUnmarshaller.Instance;
return Invoke<DescribeCodeCoveragesResponse>(request, options);
}
/// <summary>
/// Retrieves one or more code coverage reports.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeCodeCoverages service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeCodeCoverages service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeCodeCoverages">REST API Reference for DescribeCodeCoverages Operation</seealso>
public virtual Task<DescribeCodeCoveragesResponse> DescribeCodeCoveragesAsync(DescribeCodeCoveragesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeCodeCoveragesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeCodeCoveragesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeCodeCoveragesResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeTestCases
/// <summary>
/// Returns a list of details about test cases for a report.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTestCases service method.</param>
///
/// <returns>The response from the DescribeTestCases service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeTestCases">REST API Reference for DescribeTestCases Operation</seealso>
public virtual DescribeTestCasesResponse DescribeTestCases(DescribeTestCasesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeTestCasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeTestCasesResponseUnmarshaller.Instance;
return Invoke<DescribeTestCasesResponse>(request, options);
}
/// <summary>
/// Returns a list of details about test cases for a report.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTestCases service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeTestCases service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeTestCases">REST API Reference for DescribeTestCases Operation</seealso>
public virtual Task<DescribeTestCasesResponse> DescribeTestCasesAsync(DescribeTestCasesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeTestCasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeTestCasesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeTestCasesResponse>(request, options, cancellationToken);
}
#endregion
#region GetReportGroupTrend
/// <summary>
///
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetReportGroupTrend service method.</param>
///
/// <returns>The response from the GetReportGroupTrend service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetReportGroupTrend">REST API Reference for GetReportGroupTrend Operation</seealso>
public virtual GetReportGroupTrendResponse GetReportGroupTrend(GetReportGroupTrendRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetReportGroupTrendRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetReportGroupTrendResponseUnmarshaller.Instance;
return Invoke<GetReportGroupTrendResponse>(request, options);
}
/// <summary>
///
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetReportGroupTrend service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetReportGroupTrend service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetReportGroupTrend">REST API Reference for GetReportGroupTrend Operation</seealso>
public virtual Task<GetReportGroupTrendResponse> GetReportGroupTrendAsync(GetReportGroupTrendRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetReportGroupTrendRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetReportGroupTrendResponseUnmarshaller.Instance;
return InvokeAsync<GetReportGroupTrendResponse>(request, options, cancellationToken);
}
#endregion
#region GetResourcePolicy
/// <summary>
/// Gets a resource policy that is identified by its resource ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourcePolicy service method.</param>
///
/// <returns>The response from the GetResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetResourcePolicy">REST API Reference for GetResourcePolicy Operation</seealso>
public virtual GetResourcePolicyResponse GetResourcePolicy(GetResourcePolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetResourcePolicyResponseUnmarshaller.Instance;
return Invoke<GetResourcePolicyResponse>(request, options);
}
/// <summary>
/// Gets a resource policy that is identified by its resource ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourcePolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/GetResourcePolicy">REST API Reference for GetResourcePolicy Operation</seealso>
public virtual Task<GetResourcePolicyResponse> GetResourcePolicyAsync(GetResourcePolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetResourcePolicyResponseUnmarshaller.Instance;
return InvokeAsync<GetResourcePolicyResponse>(request, options, cancellationToken);
}
#endregion
#region ImportSourceCredentials
/// <summary>
/// Imports the source repository credentials for an AWS CodeBuild project that has its
/// source code stored in a GitHub, GitHub Enterprise, or Bitbucket repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ImportSourceCredentials service method.</param>
///
/// <returns>The response from the ImportSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ImportSourceCredentials">REST API Reference for ImportSourceCredentials Operation</seealso>
public virtual ImportSourceCredentialsResponse ImportSourceCredentials(ImportSourceCredentialsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ImportSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ImportSourceCredentialsResponseUnmarshaller.Instance;
return Invoke<ImportSourceCredentialsResponse>(request, options);
}
/// <summary>
/// Imports the source repository credentials for an AWS CodeBuild project that has its
/// source code stored in a GitHub, GitHub Enterprise, or Bitbucket repository.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ImportSourceCredentials service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ImportSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceAlreadyExistsException">
/// The specified AWS resource cannot be created, because an AWS resource with the same
/// settings already exists.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ImportSourceCredentials">REST API Reference for ImportSourceCredentials Operation</seealso>
public virtual Task<ImportSourceCredentialsResponse> ImportSourceCredentialsAsync(ImportSourceCredentialsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ImportSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ImportSourceCredentialsResponseUnmarshaller.Instance;
return InvokeAsync<ImportSourceCredentialsResponse>(request, options, cancellationToken);
}
#endregion
#region InvalidateProjectCache
/// <summary>
/// Resets the cache for a project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the InvalidateProjectCache service method.</param>
///
/// <returns>The response from the InvalidateProjectCache service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/InvalidateProjectCache">REST API Reference for InvalidateProjectCache Operation</seealso>
public virtual InvalidateProjectCacheResponse InvalidateProjectCache(InvalidateProjectCacheRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = InvalidateProjectCacheRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvalidateProjectCacheResponseUnmarshaller.Instance;
return Invoke<InvalidateProjectCacheResponse>(request, options);
}
/// <summary>
/// Resets the cache for a project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the InvalidateProjectCache service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the InvalidateProjectCache service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/InvalidateProjectCache">REST API Reference for InvalidateProjectCache Operation</seealso>
public virtual Task<InvalidateProjectCacheResponse> InvalidateProjectCacheAsync(InvalidateProjectCacheRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = InvalidateProjectCacheRequestMarshaller.Instance;
options.ResponseUnmarshaller = InvalidateProjectCacheResponseUnmarshaller.Instance;
return InvokeAsync<InvalidateProjectCacheResponse>(request, options, cancellationToken);
}
#endregion
#region ListBuildBatches
/// <summary>
/// Retrieves the identifiers of your build batches in the current region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildBatches service method.</param>
///
/// <returns>The response from the ListBuildBatches service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatches">REST API Reference for ListBuildBatches Operation</seealso>
public virtual ListBuildBatchesResponse ListBuildBatches(ListBuildBatchesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildBatchesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildBatchesResponseUnmarshaller.Instance;
return Invoke<ListBuildBatchesResponse>(request, options);
}
/// <summary>
/// Retrieves the identifiers of your build batches in the current region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildBatches service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListBuildBatches service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatches">REST API Reference for ListBuildBatches Operation</seealso>
public virtual Task<ListBuildBatchesResponse> ListBuildBatchesAsync(ListBuildBatchesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildBatchesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildBatchesResponseUnmarshaller.Instance;
return InvokeAsync<ListBuildBatchesResponse>(request, options, cancellationToken);
}
#endregion
#region ListBuildBatchesForProject
/// <summary>
/// Retrieves the identifiers of the build batches for a specific project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildBatchesForProject service method.</param>
///
/// <returns>The response from the ListBuildBatchesForProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatchesForProject">REST API Reference for ListBuildBatchesForProject Operation</seealso>
public virtual ListBuildBatchesForProjectResponse ListBuildBatchesForProject(ListBuildBatchesForProjectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildBatchesForProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildBatchesForProjectResponseUnmarshaller.Instance;
return Invoke<ListBuildBatchesForProjectResponse>(request, options);
}
/// <summary>
/// Retrieves the identifiers of the build batches for a specific project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildBatchesForProject service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListBuildBatchesForProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatchesForProject">REST API Reference for ListBuildBatchesForProject Operation</seealso>
public virtual Task<ListBuildBatchesForProjectResponse> ListBuildBatchesForProjectAsync(ListBuildBatchesForProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildBatchesForProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildBatchesForProjectResponseUnmarshaller.Instance;
return InvokeAsync<ListBuildBatchesForProjectResponse>(request, options, cancellationToken);
}
#endregion
#region ListBuilds
/// <summary>
/// Gets a list of build IDs, with each build ID representing a single build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuilds service method.</param>
///
/// <returns>The response from the ListBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds">REST API Reference for ListBuilds Operation</seealso>
public virtual ListBuildsResponse ListBuilds(ListBuildsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildsResponseUnmarshaller.Instance;
return Invoke<ListBuildsResponse>(request, options);
}
/// <summary>
/// Gets a list of build IDs, with each build ID representing a single build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuilds service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListBuilds service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds">REST API Reference for ListBuilds Operation</seealso>
public virtual Task<ListBuildsResponse> ListBuildsAsync(ListBuildsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildsResponseUnmarshaller.Instance;
return InvokeAsync<ListBuildsResponse>(request, options, cancellationToken);
}
#endregion
#region ListBuildsForProject
/// <summary>
/// Gets a list of build IDs for the specified build project, with each build ID representing
/// a single build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildsForProject service method.</param>
///
/// <returns>The response from the ListBuildsForProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildsForProject">REST API Reference for ListBuildsForProject Operation</seealso>
public virtual ListBuildsForProjectResponse ListBuildsForProject(ListBuildsForProjectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildsForProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildsForProjectResponseUnmarshaller.Instance;
return Invoke<ListBuildsForProjectResponse>(request, options);
}
/// <summary>
/// Gets a list of build IDs for the specified build project, with each build ID representing
/// a single build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBuildsForProject service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListBuildsForProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildsForProject">REST API Reference for ListBuildsForProject Operation</seealso>
public virtual Task<ListBuildsForProjectResponse> ListBuildsForProjectAsync(ListBuildsForProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBuildsForProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBuildsForProjectResponseUnmarshaller.Instance;
return InvokeAsync<ListBuildsForProjectResponse>(request, options, cancellationToken);
}
#endregion
#region ListCuratedEnvironmentImages
/// <summary>
/// Gets information about Docker images that are managed by AWS CodeBuild.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListCuratedEnvironmentImages service method.</param>
///
/// <returns>The response from the ListCuratedEnvironmentImages service method, as returned by CodeBuild.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListCuratedEnvironmentImages">REST API Reference for ListCuratedEnvironmentImages Operation</seealso>
public virtual ListCuratedEnvironmentImagesResponse ListCuratedEnvironmentImages(ListCuratedEnvironmentImagesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListCuratedEnvironmentImagesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListCuratedEnvironmentImagesResponseUnmarshaller.Instance;
return Invoke<ListCuratedEnvironmentImagesResponse>(request, options);
}
/// <summary>
/// Gets information about Docker images that are managed by AWS CodeBuild.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListCuratedEnvironmentImages service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListCuratedEnvironmentImages service method, as returned by CodeBuild.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListCuratedEnvironmentImages">REST API Reference for ListCuratedEnvironmentImages Operation</seealso>
public virtual Task<ListCuratedEnvironmentImagesResponse> ListCuratedEnvironmentImagesAsync(ListCuratedEnvironmentImagesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListCuratedEnvironmentImagesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListCuratedEnvironmentImagesResponseUnmarshaller.Instance;
return InvokeAsync<ListCuratedEnvironmentImagesResponse>(request, options, cancellationToken);
}
#endregion
#region ListProjects
/// <summary>
/// Gets a list of build project names, with each build project name representing a single
/// build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListProjects service method.</param>
///
/// <returns>The response from the ListProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListProjects">REST API Reference for ListProjects Operation</seealso>
public virtual ListProjectsResponse ListProjects(ListProjectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProjectsResponseUnmarshaller.Instance;
return Invoke<ListProjectsResponse>(request, options);
}
/// <summary>
/// Gets a list of build project names, with each build project name representing a single
/// build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListProjects service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListProjects">REST API Reference for ListProjects Operation</seealso>
public virtual Task<ListProjectsResponse> ListProjectsAsync(ListProjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProjectsResponseUnmarshaller.Instance;
return InvokeAsync<ListProjectsResponse>(request, options, cancellationToken);
}
#endregion
#region ListReportGroups
/// <summary>
/// Gets a list ARNs for the report groups in the current AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReportGroups service method.</param>
///
/// <returns>The response from the ListReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportGroups">REST API Reference for ListReportGroups Operation</seealso>
public virtual ListReportGroupsResponse ListReportGroups(ListReportGroupsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportGroupsResponseUnmarshaller.Instance;
return Invoke<ListReportGroupsResponse>(request, options);
}
/// <summary>
/// Gets a list ARNs for the report groups in the current AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReportGroups service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportGroups">REST API Reference for ListReportGroups Operation</seealso>
public virtual Task<ListReportGroupsResponse> ListReportGroupsAsync(ListReportGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportGroupsResponseUnmarshaller.Instance;
return InvokeAsync<ListReportGroupsResponse>(request, options, cancellationToken);
}
#endregion
#region ListReports
/// <summary>
/// Returns a list of ARNs for the reports in the current AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReports service method.</param>
///
/// <returns>The response from the ListReports service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReports">REST API Reference for ListReports Operation</seealso>
public virtual ListReportsResponse ListReports(ListReportsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportsResponseUnmarshaller.Instance;
return Invoke<ListReportsResponse>(request, options);
}
/// <summary>
/// Returns a list of ARNs for the reports in the current AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReports service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListReports service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReports">REST API Reference for ListReports Operation</seealso>
public virtual Task<ListReportsResponse> ListReportsAsync(ListReportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportsResponseUnmarshaller.Instance;
return InvokeAsync<ListReportsResponse>(request, options, cancellationToken);
}
#endregion
#region ListReportsForReportGroup
/// <summary>
/// Returns a list of ARNs for the reports that belong to a <code>ReportGroup</code>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReportsForReportGroup service method.</param>
///
/// <returns>The response from the ListReportsForReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportsForReportGroup">REST API Reference for ListReportsForReportGroup Operation</seealso>
public virtual ListReportsForReportGroupResponse ListReportsForReportGroup(ListReportsForReportGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportsForReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportsForReportGroupResponseUnmarshaller.Instance;
return Invoke<ListReportsForReportGroupResponse>(request, options);
}
/// <summary>
/// Returns a list of ARNs for the reports that belong to a <code>ReportGroup</code>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReportsForReportGroup service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListReportsForReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListReportsForReportGroup">REST API Reference for ListReportsForReportGroup Operation</seealso>
public virtual Task<ListReportsForReportGroupResponse> ListReportsForReportGroupAsync(ListReportsForReportGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReportsForReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReportsForReportGroupResponseUnmarshaller.Instance;
return InvokeAsync<ListReportsForReportGroupResponse>(request, options, cancellationToken);
}
#endregion
#region ListSharedProjects
/// <summary>
/// Gets a list of projects that are shared with other AWS accounts or users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSharedProjects service method.</param>
///
/// <returns>The response from the ListSharedProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedProjects">REST API Reference for ListSharedProjects Operation</seealso>
public virtual ListSharedProjectsResponse ListSharedProjects(ListSharedProjectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSharedProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSharedProjectsResponseUnmarshaller.Instance;
return Invoke<ListSharedProjectsResponse>(request, options);
}
/// <summary>
/// Gets a list of projects that are shared with other AWS accounts or users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSharedProjects service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListSharedProjects service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedProjects">REST API Reference for ListSharedProjects Operation</seealso>
public virtual Task<ListSharedProjectsResponse> ListSharedProjectsAsync(ListSharedProjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSharedProjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSharedProjectsResponseUnmarshaller.Instance;
return InvokeAsync<ListSharedProjectsResponse>(request, options, cancellationToken);
}
#endregion
#region ListSharedReportGroups
/// <summary>
/// Gets a list of report groups that are shared with other AWS accounts or users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSharedReportGroups service method.</param>
///
/// <returns>The response from the ListSharedReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedReportGroups">REST API Reference for ListSharedReportGroups Operation</seealso>
public virtual ListSharedReportGroupsResponse ListSharedReportGroups(ListSharedReportGroupsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSharedReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSharedReportGroupsResponseUnmarshaller.Instance;
return Invoke<ListSharedReportGroupsResponse>(request, options);
}
/// <summary>
/// Gets a list of report groups that are shared with other AWS accounts or users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSharedReportGroups service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListSharedReportGroups service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSharedReportGroups">REST API Reference for ListSharedReportGroups Operation</seealso>
public virtual Task<ListSharedReportGroupsResponse> ListSharedReportGroupsAsync(ListSharedReportGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSharedReportGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSharedReportGroupsResponseUnmarshaller.Instance;
return InvokeAsync<ListSharedReportGroupsResponse>(request, options, cancellationToken);
}
#endregion
#region ListSourceCredentials
/// <summary>
/// Returns a list of <code>SourceCredentialsInfo</code> objects.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSourceCredentials service method.</param>
///
/// <returns>The response from the ListSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSourceCredentials">REST API Reference for ListSourceCredentials Operation</seealso>
public virtual ListSourceCredentialsResponse ListSourceCredentials(ListSourceCredentialsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSourceCredentialsResponseUnmarshaller.Instance;
return Invoke<ListSourceCredentialsResponse>(request, options);
}
/// <summary>
/// Returns a list of <code>SourceCredentialsInfo</code> objects.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSourceCredentials service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListSourceCredentials service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSourceCredentials">REST API Reference for ListSourceCredentials Operation</seealso>
public virtual Task<ListSourceCredentialsResponse> ListSourceCredentialsAsync(ListSourceCredentialsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSourceCredentialsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSourceCredentialsResponseUnmarshaller.Instance;
return InvokeAsync<ListSourceCredentialsResponse>(request, options, cancellationToken);
}
#endregion
#region PutResourcePolicy
/// <summary>
/// Stores a resource policy for the ARN of a <code>Project</code> or <code>ReportGroup</code>
/// object.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutResourcePolicy service method.</param>
///
/// <returns>The response from the PutResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/PutResourcePolicy">REST API Reference for PutResourcePolicy Operation</seealso>
public virtual PutResourcePolicyResponse PutResourcePolicy(PutResourcePolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutResourcePolicyResponseUnmarshaller.Instance;
return Invoke<PutResourcePolicyResponse>(request, options);
}
/// <summary>
/// Stores a resource policy for the ARN of a <code>Project</code> or <code>ReportGroup</code>
/// object.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutResourcePolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PutResourcePolicy service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/PutResourcePolicy">REST API Reference for PutResourcePolicy Operation</seealso>
public virtual Task<PutResourcePolicyResponse> PutResourcePolicyAsync(PutResourcePolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PutResourcePolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutResourcePolicyResponseUnmarshaller.Instance;
return InvokeAsync<PutResourcePolicyResponse>(request, options, cancellationToken);
}
#endregion
#region RetryBuild
/// <summary>
/// Restarts a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryBuild service method.</param>
///
/// <returns>The response from the RetryBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuild">REST API Reference for RetryBuild Operation</seealso>
public virtual RetryBuildResponse RetryBuild(RetryBuildRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RetryBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = RetryBuildResponseUnmarshaller.Instance;
return Invoke<RetryBuildResponse>(request, options);
}
/// <summary>
/// Restarts a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryBuild service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RetryBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuild">REST API Reference for RetryBuild Operation</seealso>
public virtual Task<RetryBuildResponse> RetryBuildAsync(RetryBuildRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RetryBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = RetryBuildResponseUnmarshaller.Instance;
return InvokeAsync<RetryBuildResponse>(request, options, cancellationToken);
}
#endregion
#region RetryBuildBatch
/// <summary>
/// Restarts a failed batch build. Only batch builds that have failed can be retried.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryBuildBatch service method.</param>
///
/// <returns>The response from the RetryBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuildBatch">REST API Reference for RetryBuildBatch Operation</seealso>
public virtual RetryBuildBatchResponse RetryBuildBatch(RetryBuildBatchRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RetryBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = RetryBuildBatchResponseUnmarshaller.Instance;
return Invoke<RetryBuildBatchResponse>(request, options);
}
/// <summary>
/// Restarts a failed batch build. Only batch builds that have failed can be retried.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryBuildBatch service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RetryBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuildBatch">REST API Reference for RetryBuildBatch Operation</seealso>
public virtual Task<RetryBuildBatchResponse> RetryBuildBatchAsync(RetryBuildBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RetryBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = RetryBuildBatchResponseUnmarshaller.Instance;
return InvokeAsync<RetryBuildBatchResponse>(request, options, cancellationToken);
}
#endregion
#region StartBuild
/// <summary>
/// Starts running a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartBuild service method.</param>
///
/// <returns>The response from the StartBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild">REST API Reference for StartBuild Operation</seealso>
public virtual StartBuildResponse StartBuild(StartBuildRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartBuildResponseUnmarshaller.Instance;
return Invoke<StartBuildResponse>(request, options);
}
/// <summary>
/// Starts running a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartBuild service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StartBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.AccountLimitExceededException">
/// An AWS service limit was exceeded for the calling AWS account.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild">REST API Reference for StartBuild Operation</seealso>
public virtual Task<StartBuildResponse> StartBuildAsync(StartBuildRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StartBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartBuildResponseUnmarshaller.Instance;
return InvokeAsync<StartBuildResponse>(request, options, cancellationToken);
}
#endregion
#region StartBuildBatch
/// <summary>
/// Starts a batch build for a project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartBuildBatch service method.</param>
///
/// <returns>The response from the StartBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuildBatch">REST API Reference for StartBuildBatch Operation</seealso>
public virtual StartBuildBatchResponse StartBuildBatch(StartBuildBatchRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartBuildBatchResponseUnmarshaller.Instance;
return Invoke<StartBuildBatchResponse>(request, options);
}
/// <summary>
/// Starts a batch build for a project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartBuildBatch service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StartBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuildBatch">REST API Reference for StartBuildBatch Operation</seealso>
public virtual Task<StartBuildBatchResponse> StartBuildBatchAsync(StartBuildBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StartBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartBuildBatchResponseUnmarshaller.Instance;
return InvokeAsync<StartBuildBatchResponse>(request, options, cancellationToken);
}
#endregion
#region StopBuild
/// <summary>
/// Attempts to stop running a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopBuild service method.</param>
///
/// <returns>The response from the StopBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild">REST API Reference for StopBuild Operation</seealso>
public virtual StopBuildResponse StopBuild(StopBuildRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StopBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopBuildResponseUnmarshaller.Instance;
return Invoke<StopBuildResponse>(request, options);
}
/// <summary>
/// Attempts to stop running a build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopBuild service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StopBuild service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild">REST API Reference for StopBuild Operation</seealso>
public virtual Task<StopBuildResponse> StopBuildAsync(StopBuildRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StopBuildRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopBuildResponseUnmarshaller.Instance;
return InvokeAsync<StopBuildResponse>(request, options, cancellationToken);
}
#endregion
#region StopBuildBatch
/// <summary>
/// Stops a running batch build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopBuildBatch service method.</param>
///
/// <returns>The response from the StopBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuildBatch">REST API Reference for StopBuildBatch Operation</seealso>
public virtual StopBuildBatchResponse StopBuildBatch(StopBuildBatchRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StopBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopBuildBatchResponseUnmarshaller.Instance;
return Invoke<StopBuildBatchResponse>(request, options);
}
/// <summary>
/// Stops a running batch build.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopBuildBatch service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StopBuildBatch service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuildBatch">REST API Reference for StopBuildBatch Operation</seealso>
public virtual Task<StopBuildBatchResponse> StopBuildBatchAsync(StopBuildBatchRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StopBuildBatchRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopBuildBatchResponseUnmarshaller.Instance;
return InvokeAsync<StopBuildBatchResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateProject
/// <summary>
/// Changes the settings of a build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateProject service method.</param>
///
/// <returns>The response from the UpdateProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject">REST API Reference for UpdateProject Operation</seealso>
public virtual UpdateProjectResponse UpdateProject(UpdateProjectRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateProjectResponseUnmarshaller.Instance;
return Invoke<UpdateProjectResponse>(request, options);
}
/// <summary>
/// Changes the settings of a build project.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateProject service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateProject service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject">REST API Reference for UpdateProject Operation</seealso>
public virtual Task<UpdateProjectResponse> UpdateProjectAsync(UpdateProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateProjectRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateProjectResponseUnmarshaller.Instance;
return InvokeAsync<UpdateProjectResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateReportGroup
/// <summary>
/// Updates a report group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateReportGroup service method.</param>
///
/// <returns>The response from the UpdateReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup">REST API Reference for UpdateReportGroup Operation</seealso>
public virtual UpdateReportGroupResponse UpdateReportGroup(UpdateReportGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateReportGroupResponseUnmarshaller.Instance;
return Invoke<UpdateReportGroupResponse>(request, options);
}
/// <summary>
/// Updates a report group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateReportGroup service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateReportGroup service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup">REST API Reference for UpdateReportGroup Operation</seealso>
public virtual Task<UpdateReportGroupResponse> UpdateReportGroupAsync(UpdateReportGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateReportGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateReportGroupResponseUnmarshaller.Instance;
return InvokeAsync<UpdateReportGroupResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateWebhook
/// <summary>
/// Updates the webhook associated with an AWS CodeBuild build project.
///
/// <note>
/// <para>
/// If you use Bitbucket for your repository, <code>rotateSecret</code> is ignored.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateWebhook service method.</param>
///
/// <returns>The response from the UpdateWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook">REST API Reference for UpdateWebhook Operation</seealso>
public virtual UpdateWebhookResponse UpdateWebhook(UpdateWebhookRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateWebhookResponseUnmarshaller.Instance;
return Invoke<UpdateWebhookResponse>(request, options);
}
/// <summary>
/// Updates the webhook associated with an AWS CodeBuild build project.
///
/// <note>
/// <para>
/// If you use Bitbucket for your repository, <code>rotateSecret</code> is ignored.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateWebhook service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateWebhook service method, as returned by CodeBuild.</returns>
/// <exception cref="Amazon.CodeBuild.Model.InvalidInputException">
/// The input value that was provided is not valid.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.OAuthProviderException">
/// There was a problem with the underlying OAuth provider.
/// </exception>
/// <exception cref="Amazon.CodeBuild.Model.ResourceNotFoundException">
/// The specified AWS resource cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook">REST API Reference for UpdateWebhook Operation</seealso>
public virtual Task<UpdateWebhookResponse> UpdateWebhookAsync(UpdateWebhookRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateWebhookRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateWebhookResponseUnmarshaller.Instance;
return InvokeAsync<UpdateWebhookResponse>(request, options, cancellationToken);
}
#endregion
}
} | 53.025771 | 227 | 0.671242 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/CodeBuild/Generated/_bcl45/AmazonCodeBuildClient.cs | 146,086 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GeoToolkit.FuzzyLogic
{
class StringDistance
{
}
}
| 13.416667 | 33 | 0.732919 | [
"MIT"
] | geoser/geotoolkit | GeoToolkit/FuzzyLogic/StringDistance.cs | 163 | C# |
namespace MassTransit.KafkaIntegration.Specifications
{
using System;
using System.Collections.Generic;
using Configurators;
using Confluent.Kafka;
using GreenPipes;
using MassTransit.Configurators;
using MassTransit.Registration;
using Pipeline.Observables;
using Serializers;
using Transport;
public class KafkaConsumerSpecification<TKey, TValue> :
IKafkaConsumerSpecification
where TValue : class
{
readonly Action<IKafkaTopicReceiveEndpointConfigurator<TKey, TValue>> _configure;
readonly ConsumerConfig _consumerConfig;
readonly ReceiveEndpointObservable _endpointObservers;
readonly IHeadersDeserializer _headersDeserializer;
public KafkaConsumerSpecification(ConsumerConfig consumerConfig, string topicName, IHeadersDeserializer headersDeserializer,
Action<IKafkaTopicReceiveEndpointConfigurator<TKey, TValue>> configure)
{
_consumerConfig = consumerConfig;
Name = topicName;
_endpointObservers = new ReceiveEndpointObservable();
_headersDeserializer = headersDeserializer;
_configure = configure;
}
public string Name { get; }
public IKafkaReceiveEndpoint CreateReceiveEndpoint(IBusInstance busInstance)
{
var endpointConfiguration = busInstance.HostConfiguration.CreateReceiveEndpointConfiguration($"{KafkaTopicAddress.PathPrefix}/{Name}");
endpointConfiguration.ConnectReceiveEndpointObserver(_endpointObservers);
var configurator =
new KafkaTopicReceiveEndpointConfiguration<TKey, TValue>(_consumerConfig, Name, busInstance, endpointConfiguration, _headersDeserializer);
_configure?.Invoke(configurator);
var result = BusConfigurationResult.CompileResults(configurator.Validate());
try
{
return configurator.Build();
}
catch (Exception ex)
{
throw new ConfigurationException(result, $"An exception occurred creating the {nameof(IKafkaReceiveEndpoint)}", ex);
}
}
public IEnumerable<ValidationResult> Validate()
{
if (string.IsNullOrEmpty(Name))
yield return this.Failure("Topic", "should not be empty");
if (string.IsNullOrEmpty(_consumerConfig.GroupId))
yield return this.Failure("GroupId", "should not be empty");
if (string.IsNullOrEmpty(_consumerConfig.BootstrapServers))
yield return this.Failure("BootstrapServers", "should not be empty. Please use cfg.Host() to configure it");
}
public ConnectHandle ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return _endpointObservers.Connect(observer);
}
}
}
| 38.693333 | 154 | 0.678498 | [
"ECL-2.0",
"Apache-2.0"
] | AlexGoemanDigipolis/MassTransit | src/Transports/MassTransit.KafkaIntegration/Configuration/Specifications/KafkaConsumerSpecification.cs | 2,902 | C# |
using Bangumi.Api;
using Bangumi.Common;
using Bangumi.ContentDialogs;
using Bangumi.Controls;
using Bangumi.Data;
using Bangumi.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Background;
using Windows.Storage;
namespace Bangumi.ViewModels
{
public class SettingViewModel : ViewModelBase
{
public List<Url> Urls { get; set; } = new List<Url>
{
new Url {Uri="https://github.com/bangumi/api", Desc="Bangumi API(https://github.com/bangumi/api)"},
new Url {Uri="https://www.newtonsoft.com/json", Desc="Newtonsoft.Json(https://www.newtonsoft.com/json)"},
new Url {Uri="https://github.com/Microsoft/microsoft-ui-xaml", Desc="Microsoft.UI.Xaml(https://github.com/Microsoft/microsoft-ui-xaml)"},
new Url {Uri="https://github.com/windows-toolkit/WindowsCommunityToolkit", Desc="WindowsCommunityToolkit(https://github.com/windows-toolkit/WindowsCommunityToolkit)"},
new Url {Uri="https://github.com/bangumi-data/bangumi-data", Desc="bangumi-data(https://github.com/bangumi-data/bangumi-data)"},
new Url {Uri="https://flurl.dev", Desc="Flurl(https://flurl.dev)"},
new Url {Uri="https://github.com/Tlaster/WeiPo", Desc="WeiPo(https://github.com/Tlaster/WeiPo)"},
new Url {Uri="https://github.com/tobiichiamane/pixivfs-uwp", Desc="pixivfs-uwp(https://github.com/tobiichiamane/pixivfs-uwp)"},
};
public string Version => string.Format("版本:{0} v{1}.{2}.{3}.{4} {5}",
Package.Current.DisplayName,
Package.Current.Id.Version.Major,
Package.Current.Id.Version.Minor,
Package.Current.Id.Version.Build,
Package.Current.Id.Version.Revision,
Package.Current.Id.Architecture);
public string PackageName => string.Format("包名:{0}", Package.Current.Id.Name);
public string InstalledDate => string.Format("安装时间:{0}", Package.Current.InstalledDate.ToLocalTime().DateTime);
public bool EpsBatch
{
get => SettingHelper.EpsBatch;
set
{
SettingHelper.EpsBatch = value;
OnPropertyChanged();
}
}
public bool SubjectComplete
{
get => SettingHelper.SubjectComplete;
set
{
SettingHelper.SubjectComplete = value;
OnPropertyChanged();
}
}
public bool OrderByAirTime
{
get => SettingHelper.OrderByAirTime;
set
{
SettingHelper.OrderByAirTime = value;
OnPropertyChanged();
}
}
public bool EnableBackgroundTask
{
get
{
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == Constants.RefreshTokenTask)
{
return true;
}
}
return false;
}
set
{
if (value)
{
if (!BangumiApi.BgmOAuth.IsLogin)
{
NotificationHelper.Notify("请先登录!", NotifyType.Warn);
OnPropertyChanged();
return;
}
// If the user denies access, the task will not run.
var requestTask = BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = Constants.RefreshTokenTask;
builder.SetTrigger(new TimeTrigger((uint)TimeSpan.FromDays(1).TotalMinutes, false));
builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
// If the condition changes while the background task is executing then it will
// be canceled.
builder.CancelOnConditionLoss = true;
builder.Register();
}
else
{
EnableBangumiAirToast = false;
// 取消所有后台任务
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
cur.Value.Unregister(true);
}
}
OnPropertyChanged();
}
}
public bool UseBangumiData
{
get => SettingHelper.UseBangumiData;
set
{
SettingHelper.UseBangumiData = value;
if (value)
{
// 获取数据版本
BangumiData.Init(Path.Combine(ApplicationData.Current.LocalFolder.Path, "bangumi-data"),
SettingHelper.UseBiliApp);
}
else
{
BangumiData.AutoCheck = false;
}
OnPropertyChanged();
OnPropertyChanged(nameof(BangumiDataVersion));
OnPropertyChanged(nameof(UseBangumiDataAirSites));
OnPropertyChanged(nameof(UseBiliApp));
OnPropertyChanged(nameof(UseBangumiDataAirTime));
OnPropertyChanged(nameof(BangumiDataAutoCheck));
OnPropertyChanged(nameof(BangumiDataCheckInterval));
OnPropertyChanged(nameof(BangumiDataAutoUpdate));
}
}
public bool BangumiDataAutoCheck
{
get => BangumiData.AutoCheck;
set
{
BangumiData.AutoCheck = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BangumiDataCheckInterval));
OnPropertyChanged(nameof(BangumiDataAutoUpdate));
}
}
public int BangumiDataCheckInterval
{
get => BangumiData.CheckInterval;
set
{
BangumiData.CheckInterval = value;
OnPropertyChanged();
}
}
public bool BangumiDataAutoUpdate
{
get => BangumiData.AutoUpdate;
set
{
BangumiData.AutoUpdate = value;
OnPropertyChanged();
}
}
public bool UseBangumiDataAirSites
{
get => SettingHelper.UseBangumiDataAirSites;
set
{
SettingHelper.UseBangumiDataAirSites = value;
OnPropertyChanged();
OnPropertyChanged(nameof(UseBiliApp));
}
}
public bool UseBiliApp
{
get => SettingHelper.UseBiliApp;
set
{
SettingHelper.UseBiliApp = value;
BangumiData.UseBiliApp = value;
OnPropertyChanged();
}
}
public bool UseBangumiDataAirTime
{
get => SettingHelper.UseBangumiDataAirTime;
set
{
SettingHelper.UseBangumiDataAirTime = value;
OnPropertyChanged();
OnPropertyChanged(nameof(EnableBangumiAirToast));
OnPropertyChanged(nameof(UseActionCenterMode));
}
}
public bool EnableBangumiAirToast
{
get => SettingHelper.EnableBangumiAirToast;
set
{
if (value)
{
if (!EnableBackgroundTask)
{
NotificationHelper.Notify("该选项需启用后台任务后可用", NotifyType.Warn);
value = false;
}
}
else
{
UseActionCenterMode = false;
ToastNotificationHelper.RemoveAllScheduledToasts();
}
SettingHelper.EnableBangumiAirToast = value;
OnPropertyChanged();
OnPropertyChanged(nameof(UseActionCenterMode));
}
}
public bool UseActionCenterMode
{
get
{
var v = BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(Constants.ToastBackgroundTask));
SettingHelper.UseActionCenterMode = v;
return v;
}
set
{
if (value)
{
// If the user denies access, the task will not run.
var requestTask = BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = Constants.ToastBackgroundTask;
builder.SetTrigger(new ToastNotificationActionTrigger());
builder.Register();
}
else
{
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == Constants.ToastBackgroundTask)
{
cur.Value.Unregister(true);
}
}
}
SettingHelper.UseActionCenterMode = value;
OnPropertyChanged();
}
}
private bool _userCacheCanDelete;
public bool UserCacheCanDelete
{
get => _userCacheCanDelete;
set => Set(ref _userCacheCanDelete, value);
}
private string _userCacheSize;
public string UserCacheSize
{
get => _userCacheSize;
set => Set(ref _userCacheSize, value);
}
private bool _imageCacheCanDelete;
public bool ImageCacheCanDelete
{
get => _imageCacheCanDelete;
set => Set(ref _imageCacheCanDelete, value);
}
private string _imageCacheSize;
public string ImageCacheSize
{
get => _imageCacheSize;
set => Set(ref _imageCacheSize, value);
}
private string _bangumiDataStatus = "检查更新";
public string BangumiDataStatus
{
get => _bangumiDataStatus;
set
{
Set(ref _bangumiDataStatus, value);
OnPropertyChanged(nameof(BangumiDataVersion));
OnPropertyChanged(nameof(LastUpdate));
}
}
private bool _bangumiDataVersionChecking;
public bool BangumiDataVersionChecking
{
get => _bangumiDataVersionChecking;
set => Set(ref _bangumiDataVersionChecking, value);
}
public string BangumiDataVersion
{
get
{
// 显示当前数据版本及更新后版本
var version = string.IsNullOrEmpty(BangumiData.Version) ?
"无数据" : BangumiData.Version;
version += ((string.IsNullOrEmpty(BangumiData.LatestVersion) || BangumiData.Version == BangumiData.LatestVersion) ?
string.Empty :
$" -> {BangumiData.LatestVersion}");
return version;
}
}
public string LastUpdate
{
get
{
if (BangumiData.LastUpdate == DateTimeOffset.MinValue)
{
return "从未更新";
}
return BangumiData.LastUpdate.ToString("yyyy-MM-dd");
}
}
public async Task Load()
{
if (UserCacheSize == "正在计算")
{
return;
}
ImageCacheCanDelete = false;
ImageCacheSize = "正在计算";
UserCacheCanDelete = false;
UserCacheSize = "正在计算";
// 获取缓存文件大小
UserCacheSize = FileSizeHelper.GetSizeString(BangumiApi.BgmCache.GetFileLength());
UserCacheCanDelete = true;
// 计算文件夹 ImageCache 中文件大小
if (Directory.Exists(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "ImageCache")))
{
StorageFolder imageCacheFolder = await ApplicationData.Current.TemporaryFolder.GetFolderAsync("ImageCache");
var files = await imageCacheFolder.GetFilesAsync();
ulong fileSize = 0;
foreach (var file in files)
{
var fileInfo = await file.GetBasicPropertiesAsync();
fileSize += fileInfo.Size;
}
ImageCacheSize = FileSizeHelper.GetSizeString(fileSize);
ImageCacheCanDelete = true;
}
else
{
// 文件夹 ImageCache 不存在
ImageCacheSize = "无缓存";
}
}
public void DeleteUserCacheFile()
{
// 删除缓存文件
BangumiApi.BgmCache.Delete();
UserCacheSize = "无缓存";
UserCacheCanDelete = false;
}
/// <summary>
/// 删除图片缓存文件夹
/// </summary>
public async Task DeleteImageTempFile()
{
ImageCacheCanDelete = false;
if (Directory.Exists(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "ImageCache")))
{
await (await ApplicationData.Current.TemporaryFolder.GetFolderAsync("ImageCache")).DeleteAsync();
}
ImageCacheSize = "无缓存";
}
/// <summary>
/// 检查更新并下载最新版本
/// </summary>
public async Task UpdateBangumiData()
{
BangumiDataStatus = "正在检查更新";
BangumiDataVersionChecking = true;
bool hasNew = false;
var startDownloadAction = new Action(() =>
{
hasNew = true;
BangumiDataStatus = "正在下载数据";
});
if (await BangumiData.DownloadLatestBangumiData(startDownloadAction))
{
if (hasNew)
{
NotificationHelper.Notify("数据下载成功!");
}
else
{
NotificationHelper.Notify("已是最新版本!");
}
}
else
{
if (hasNew)
{
NotificationHelper.Notify("数据下载失败,请重试或稍后再试!", NotifyType.Error);
}
else
{
NotificationHelper.Notify("获取最新版本失败!", NotifyType.Error);
}
}
BangumiDataStatus = "检查更新";
BangumiDataVersionChecking = false;
}
/// <summary>
/// 打开站点设置面板
/// </summary>
public async Task OpenSitesContentDialog()
{
var dg = new SitesContentDialog();
await dg.ShowAsync();
}
}
public class Url
{
public string Uri { get; set; }
public string Desc { get; set; }
}
}
| 32.760593 | 179 | 0.498286 | [
"MIT"
] | Teachoc/Bangumi | Bangumi/ViewModels/SettingViewModel.cs | 15,869 | C# |
namespace AgileCoding.Extentions.Attributes
{
using System;
using System.Linq;
using System.Reflection;
public static class AttributeExtentions
{
public static object GetAttribute<ANYType>(this ANYType genericType, Type TypeOfAttribute)
where ANYType : struct
{
Type genericEnumType = genericType.GetType();
MemberInfo[] memberInfo = genericEnumType.GetMember(genericType.ToString());
if ((memberInfo != null && memberInfo.Length > 0))
{
var _Attribs = memberInfo[0].GetCustomAttributes(TypeOfAttribute, false);
if ((_Attribs != null && _Attribs.Count() > 0))
{
return _Attribs.ElementAt(0);
}
}
return default(object);
}
}
}
| 31.296296 | 98 | 0.572781 | [
"MIT"
] | ToolMaker/AgileCoding.Extentions.Attributes | AgileCoding.Extentions.Attributes/AttributeExtentions.cs | 847 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// This is the response object from the CreateInstances operation.
/// </summary>
public partial class CreateInstancesResponse : AmazonWebServiceResponse
{
private List<Operation> _operations = new List<Operation>();
/// <summary>
/// Gets and sets the property Operations.
/// <para>
/// An array of objects that describe the result of the action, such as the status of
/// the request, the timestamp of the request, and the resources affected by the request.
/// </para>
/// </summary>
public List<Operation> Operations
{
get { return this._operations; }
set { this._operations = value; }
}
// Check to see if Operations property is set
internal bool IsSetOperations()
{
return this._operations != null && this._operations.Count > 0;
}
}
} | 32.473684 | 107 | 0.666126 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/CreateInstancesResponse.cs | 1,851 | C# |
using AgileDotNetHtml.Attributes;
namespace AgileDotNetHtml.Models.HtmlElements
{
[HtmlElementClass("track")]
public class HtmlTrackElement : HtmlSelfClosingTagElement
{
/// <summary>
/// Initialize a new instance of AgileDotNetHtml.Models.HtmlElements.HtmlTrackElement class represent HTML <track> tag.
/// </summary>
public HtmlTrackElement() : base("track") { }
}
}
| 25.933333 | 127 | 0.753213 | [
"MIT"
] | atanasgalchov/AgileDotNetHtml | src/Models/HtmlElements/Specific/HtmlTrackElement.cs | 389 | C# |
using System.Windows;
namespace MScResearchTool.Windows.WPF.Windows
{
public partial class MessageWindow : Window
{
public MessageWindow(string title, string content, string confirmation)
{
InitializeComponent();
TitleBlock.Text = title;
ContentBlock.Text = content;
CloseButton.Content = confirmation;
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
| 23.227273 | 79 | 0.604697 | [
"MIT"
] | zbigniewmarszolik/MScResearchTool | MScResearchTool.Windows/MScResearchTool.Windows.WPF/Windows/MessageWindow.xaml.cs | 513 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AspNetWebFormsRestConsumer {
public partial class Site_Mobile {
/// <summary>
/// HeadContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent;
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// FeaturedContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent;
/// <summary>
/// MainContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
}
}
| 35.25 | 88 | 0.513366 | [
"Apache-2.0"
] | DEV-MC01/documentum-rest-client-dotnet | MonoReST/AspNetWebFormsRestConsumer/Site.Mobile.Master.designer.cs | 1,833 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Delete a Dialable Caller ID Criteria.
/// The response is either a SuccessResponse or an ErrorResponse.
/// <see cref="SuccessResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""f3a93cf15de4abd7903673e44ee3e07b:3668""}]")]
public class GroupDialableCallerIDCriteriaDeleteRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _serviceProviderId;
[XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")]
[Group(@"f3a93cf15de4abd7903673e44ee3e07b:3668")]
[MinLength(1)]
[MaxLength(30)]
public string ServiceProviderId
{
get => _serviceProviderId;
set
{
ServiceProviderIdSpecified = true;
_serviceProviderId = value;
}
}
[XmlIgnore]
protected bool ServiceProviderIdSpecified { get; set; }
private string _groupId;
[XmlElement(ElementName = "groupId", IsNullable = false, Namespace = "")]
[Group(@"f3a93cf15de4abd7903673e44ee3e07b:3668")]
[MinLength(1)]
[MaxLength(30)]
public string GroupId
{
get => _groupId;
set
{
GroupIdSpecified = true;
_groupId = value;
}
}
[XmlIgnore]
protected bool GroupIdSpecified { get; set; }
private string _name;
[XmlElement(ElementName = "name", IsNullable = false, Namespace = "")]
[Group(@"f3a93cf15de4abd7903673e44ee3e07b:3668")]
[MinLength(1)]
[MaxLength(40)]
public string Name
{
get => _name;
set
{
NameSpecified = true;
_name = value;
}
}
[XmlIgnore]
protected bool NameSpecified { get; set; }
}
}
| 28.111111 | 130 | 0.578832 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/GroupDialableCallerIDCriteriaDeleteRequest.cs | 2,277 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConsoleApplication1.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.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;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=ANTONIO-WORK\\SQLLOCAL;Initial Catalog=AdventureWorks2014;User ID=sa;P" +
"assword=sasa")]
public string AdventureWorks2014ConnectionString {
get {
return ((string)(this["AdventureWorks2014ConnectionString"]));
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(" de nada")]
public string Nada {
get {
return ((string)(this["Nada"]));
}
set {
this["Nada"] = value;
}
}
}
}
| 42.58 | 153 | 0.605449 | [
"MIT"
] | ExpertSamples/Beca.Net | ConsoleApplication1/Properties/Settings.Designer.cs | 2,131 | C# |
using Rocket.API;
using Rocket.Unturned.Chat;
using Rocket.Unturned.Player;
using SDG.Unturned;
using System.Collections.Generic;
using UnityEngine;
namespace Rocket.Unturned.Commands
{
public class CommandHome : IRocketCommand
{
public AllowedCaller AllowedCaller
{
get
{
return AllowedCaller.Player;
}
}
public string Name
{
get { return "home"; }
}
public string Help
{
get { return "Teleports you to your last bed"; }
}
public string Syntax
{
get { return ""; }
}
public List<string> Aliases
{
get { return new List<string>(); }
}
public List<string> Permissions
{
get { return new List<string>() { "rocket.home" }; }
}
public void Execute(IRocketPlayer caller, string[] command)
{
UnturnedPlayer player = (UnturnedPlayer)caller;
Vector3 pos;
byte rot;
if (!BarricadeManager.tryGetBed(player.CSteamID, out pos, out rot))
{
UnturnedChat.Say(caller, U.Translate("command_bed_no_bed_found_private"));
throw new WrongUsageOfCommandException(caller, this);
}
else
{
if (player.Stance == EPlayerStance.DRIVING || player.Stance == EPlayerStance.SITTING)
{
UnturnedChat.Say(caller, U.Translate("command_generic_teleport_while_driving_error"));
throw new WrongUsageOfCommandException(caller, this);
}
else
{
player.Teleport(pos, rot);
}
}
}
}
} | 26.228571 | 106 | 0.513617 | [
"MIT"
] | iBowie/RocketMod | Rocket.Unturned/Commands/CommandHome.cs | 1,838 | C# |
/***********************************************************
Copyright (c) 2017-present Clicked, Inc.
Licensed under the MIT license found in the LICENSE file
in the Docs folder of the distributed package.
***********************************************************/
using System.Runtime.InteropServices;
using UnityEngine;
public class AirVRServerInputStream : AirVRInputStream {
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_BeginPendInput(int playerID, ref long timestamp);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_PendInputState(int playerID, byte device, byte control, byte state);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_PendInputRaycastHit(int playerID, byte device, byte control, AirVRVector3D origin, AirVRVector3D hitPosition, AirVRVector3D hitNormal);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_PendInputVibration(int playerID, byte device, byte control, float frequency, float amplitude);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_SendPendingInputs(int playerID, long timestamp);
[DllImport(AirVRServerPlugin.Name)]
private static extern long ocs_GetInputRecvTimestamp(int playerID);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputState(int playerID, byte device, byte control, ref byte state);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputByteAxis(int playerID, byte device, byte control, ref byte axis);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputAxis(int playerID, byte device, byte control, ref float axis);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputAxis2D(int playerID, byte device, byte control, ref AirVRVector2D axis2D);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputPose(int playerID, byte device, byte control, ref AirVRVector3D position, ref AirVRVector4D rotation);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputTouch2D(int playerID, byte device, byte control, ref AirVRVector2D position, ref byte state);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_IsInputActive(int playerID, byte device, byte control);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_IsInputDirectionActive(int playerID, byte device, byte control, byte direction);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputActivated(int playerID, byte device, byte control);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputDirectionActivated(int playerID, byte device, byte control, byte direction);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputDeactivated(int playerID, byte device, byte control);
[DllImport(AirVRServerPlugin.Name)]
private static extern bool ocs_GetInputDirectionDeactivated(int playerID, byte device, byte control, byte direction);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_UpdateInputFrame(int playerID);
[DllImport(AirVRServerPlugin.Name)]
private static extern void ocs_ClearInput(int playerID);
public AirVRServerInputStream(AirVRCameraRig owner) {
this.owner = owner;
}
public AirVRCameraRig owner { get; set; }
public long inputRecvTimestamp {
get {
return ocs_GetInputRecvTimestamp(owner.playerID);
}
}
// implements AirVRInputStream
protected override float maxSendingRatePerSec { get { return 90.0f; } }
protected override void BeginPendInputImpl(ref long timestamp) {
ocs_BeginPendInput(owner.playerID, ref timestamp);
}
protected override void PendStateImpl(byte device, byte control, byte state) {
if (owner.isBoundToClient == false) { return; }
ocs_PendInputState(owner.playerID, device, control, state);
}
protected override void PendByteAxisImpl(byte device, byte control, byte axis) { }
protected override void PendAxisImpl(byte device, byte control, float axis) { }
protected override void PendAxis2DImpl(byte device, byte control, Vector2 axis2D) { }
protected override void PendPoseImpl(byte device, byte control, Vector3 position, Quaternion rotation) { }
protected override void PendRaycastHitImpl(byte device, byte control, Vector3 origin, Vector3 hitPosition, Vector3 hitNormal) {
if (owner.isBoundToClient == false) { return; }
ocs_PendInputRaycastHit(owner.playerID, device, control, new AirVRVector3D(origin), new AirVRVector3D(hitPosition), new AirVRVector3D(hitNormal));
}
protected override void PendVibrationImpl(byte device, byte control, float frequency, float amplitude) {
if (owner.isBoundToClient == false) { return; }
ocs_PendInputVibration(owner.playerID, device, control, frequency, amplitude);
}
protected override void PendTouch2DImpl(byte device, byte control, Vector2 position, byte state, bool active) {}
protected override void SendPendingInputEventsImpl(long timestamp) {
ocs_SendPendingInputs(owner.playerID, timestamp);
}
protected override bool GetStateImpl(byte device, byte control, ref byte state) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputState(owner.playerID, device, control, ref state);
}
protected override bool GetByteAxisImpl(byte device, byte control, ref byte axis) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputByteAxis(owner.playerID, device, control, ref axis);
}
protected override bool GetAxisImpl(byte device, byte control, ref float axis) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputAxis(owner.playerID, device, control, ref axis);
}
protected override bool GetAxis2DImpl(byte device, byte control, ref Vector2 axis2D) {
if (owner.isBoundToClient == false) { return false; }
AirVRVector2D axis = new AirVRVector2D();
if (ocs_GetInputAxis2D(owner.playerID, device, control, ref axis) == false) { return false; }
axis2D = axis.toVector2();
return true;
}
protected override bool GetPoseImpl(byte device, byte control, ref Vector3 position, ref Quaternion rotation) {
if (owner.isBoundToClient == false) { return false; }
AirVRVector3D pos = new AirVRVector3D();
AirVRVector4D rot = new AirVRVector4D();
if (ocs_GetInputPose(owner.playerID, device, control, ref pos, ref rot) == false) { return false; }
position = pos.toVector3();
rotation = rot.toQuaternion();
return true;
}
protected override bool GetRaycastHitImpl(byte device, byte control, ref Vector3 origin, ref Vector3 hitPosition, ref Vector3 hitNormal) { return false; }
protected override bool GetVibrationImpl(byte device, byte control, ref float frequency, ref float amplitude) { return false; }
protected override bool GetTouch2DImpl(byte device, byte control, ref Vector2 position, ref byte state) {
if (owner.isBoundToClient == false) { return false; }
AirVRVector2D pos = new AirVRVector2D();
if (ocs_GetInputTouch2D(owner.playerID, device, control, ref pos, ref state) == false) { return false; }
position = pos.toVector2();
return true;
}
protected override bool IsActiveImpl(byte device, byte control) {
if (owner.isBoundToClient == false) { return false; }
return ocs_IsInputActive(owner.playerID, device, control);
}
protected override bool IsActiveImpl(byte device, byte control, AirVRInputDirection direction) {
if (owner.isBoundToClient == false) { return false; }
return ocs_IsInputDirectionActive(owner.playerID, device, control, (byte)direction);
}
protected override bool GetActivatedImpl(byte device, byte control) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputActivated(owner.playerID, device, control);
}
protected override bool GetActivatedImpl(byte device, byte control, AirVRInputDirection direction) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputDirectionActivated(owner.playerID, device, control, (byte)direction);
}
protected override bool GetDeactivatedImpl(byte device, byte control) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputDeactivated(owner.playerID, device, control);
}
protected override bool GetDeactivatedImpl(byte device, byte control, AirVRInputDirection direction) {
if (owner.isBoundToClient == false) { return false; }
return ocs_GetInputDirectionDeactivated(owner.playerID, device, control, (byte)direction);
}
protected override void UpdateInputFrameImpl() {
if (owner.isBoundToClient == false) { return; }
ocs_UpdateInputFrame(owner.playerID);
}
protected override void ClearInputImpl() {
if (owner.isBoundToClient == false) { return; }
ocs_ClearInput(owner.playerID);
}
}
| 41.384956 | 170 | 0.719448 | [
"MIT"
] | onairvr/onairvr-server-for-unity | Assets/onAirVR/Server/Scripts/Input/AirVRServerInputStream.cs | 9,355 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 12.02.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Object.SET_001.STD.Equals__obj2.Complete.EnumInt32.SByte{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1=TestTypes.Enums.EnumInt32;
using T_DATA2=System.SByte;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_003__paramObjs
public static class TestSet_003__paramObjs
{
private const string c_NameOf__TABLE="DUAL";
//-----------------------------------------------------------------------
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int64? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__param__param()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=T_DATA1.positive__SEVEN;
const T_DATA2 c_value2=7;
object vv1=(T_DATA1)c_value1;
object vv2=(T_DATA2)c_value2;
var recs=db.testTable.Where(r => object.Equals(vv1,vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001__param__param
//-----------------------------------------------------------------------
[Test]
public static void Test_002__null__param()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA2 c_value2=7;
object vv1=null;
object vv2=(T_DATA2)c_value2;
var recs=db.testTable.Where(r => !object.Equals(vv1,vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002__null__param
//-----------------------------------------------------------------------
[Test]
public static void Test_003__param__null()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=T_DATA1.positive__SEVEN;
object vv1=(T_DATA1)c_value1;
object vv2=null;
var recs=db.testTable.Where(r => !object.Equals(vv1,vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_003__param__null
};//class TestSet_003__paramObjs
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Object.SET_001.STD.Equals__obj2.Complete.EnumInt32.SByte
| 23.981308 | 142 | 0.53371 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/Object/STD/Equals__obj2/Complete/EnumInt32/SByte/TestSet_003__paramObjs.cs | 5,134 | C# |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tizen.NUI;
using Tizen.NUI.UIComponents;
using Tizen.NUI.BaseComponents;
using Tizen.NUI.Constants;
namespace UIControlSample
{
/// <summary>
/// A sample of popup.
/// </summary>
public class Popups
{
Tizen.NUI.UIComponents.Popup _popup;
PushButton cancelButton, okayButton;
private const string resources = "/home/owner/apps_rw/org.tizen.example.UIControlSample/res";
private string popupBGImage = resources + "/images/Popup/bg_popup_220_220_220_100.9.png";
private string barImage = resources + "/images/Popup/img_popup_bar_line.png";
private string shadowImage = resources + "/images/Popup/img_popup_bar_shadow.png";
/// <summary>
/// Constructor to create new Popups
/// </summary>
public Popups()
{
OnIntialize();
}
/// <summary>
/// Popups initialisation.
/// </summary>
private void OnIntialize()
{
_popup = CreatePopup();
_popup.SetContent(CreateContent());
_popup.Focusable = (true);
_popup.SetDisplayState(Tizen.NUI.UIComponents.Popup.DisplayStateType.Hidden);
}
/// <summary>
/// Get the initialized _popup
/// </summary>
/// <returns>
/// The _popup which be created in this class
/// </returns>
public Tizen.NUI.UIComponents.Popup GetPopup()
{
return _popup;
}
/// <summary>
/// Create popup
/// </summary>
/// <returns>
/// The _popup which be created in this function
/// </returns>
Tizen.NUI.UIComponents.Popup CreatePopup()
{
Tizen.NUI.UIComponents.Popup confirmationPopup = new Tizen.NUI.UIComponents.Popup();
confirmationPopup.ParentOrigin = ParentOrigin.TopLeft;
confirmationPopup.PivotPoint = PivotPoint.TopLeft;
confirmationPopup.WidthResizePolicy = ResizePolicyType.FitToChildren;
confirmationPopup.HeightResizePolicy = ResizePolicyType.FitToChildren;
confirmationPopup.Position = new Position(530, 306, 0);
confirmationPopup.PopupBackgroundImage = popupBGImage;
return confirmationPopup;
}
/// <summary>
/// Create the view be used to set popup.content.
/// </summary>
/// <returns>
/// The created contentView.
/// </returns>
View CreateContent()
{
View contentView = new View();
contentView.Size2D = new Size2D(860, 486);
contentView.ParentOrigin = ParentOrigin.TopLeft;
contentView.PivotPoint = PivotPoint.TopLeft;
contentView.Position = new Position(0, 0, 0);
TextLabel titleView = new TextLabel("Information");
titleView.FontFamily = "Samsung One 600";
titleView.TextColor = Color.Black;
titleView.ParentOrigin = ParentOrigin.TopLeft;
titleView.PivotPoint = PivotPoint.TopLeft;
titleView.Position = new Position(70, 65, 0);
titleView.Size2D = new Size2D(720, 70);
titleView.MultiLine = false;
//titleView.PointSize = 10;
titleView.PointSize = DeviceCheck.PointSize10;
titleView.HorizontalAlignment = HorizontalAlignment.Center;
ImageView imageView = new ImageView(barImage);
imageView.ParentOrigin = ParentOrigin.TopLeft;
imageView.PivotPoint = PivotPoint.TopLeft;
imageView.Position = new Position(70, 143, 0);
imageView.Size2D = new Size2D(720, 3);
ImageView shadow = new ImageView(shadowImage);
shadow.ParentOrigin = ParentOrigin.TopLeft;
shadow.PivotPoint = PivotPoint.TopLeft;
shadow.Position = new Position(70, 146, 0);
shadow.Size2D = new Size2D(720, 9);
TextLabel contentLabel = new TextLabel("Do you want to erase this file Permanently?");
contentLabel.FontFamily = "Samsung One 400";
contentLabel.TextColor = Color.Black;
contentLabel.ParentOrigin = ParentOrigin.TopLeft;
contentLabel.PivotPoint = PivotPoint.TopLeft;
contentLabel.Position = new Position(70, 204, 0);
contentLabel.Size2D = new Size2D(720, 120);
contentLabel.MultiLine = true;
//contentLabel.PointSize = 8;
contentLabel.PointSize = DeviceCheck.PointSize8;
contentLabel.HorizontalAlignment = HorizontalAlignment.Center;
PushButton okButton = CreateOKButton();
okButton.Position = new Position(120, 316, 0); //300, 80
PushButton cancelButton = CreateCancelButton();
cancelButton.Position = new Position(440, 316, 0); //300, 80
contentView.Add(titleView);
contentView.Add(imageView);
contentView.Add(shadow);
contentView.Add(contentLabel);
contentView.Add(okButton);
contentView.Add(cancelButton);
return contentView;
}
/// <summary>
/// Create the okButton
/// </summary>
/// <returns>
/// The created okButton.
/// </returns>
PushButton CreateOKButton()
{
Button okSample = new Button("OK");
okayButton = okSample.GetPushButton();
okayButton.Name = "OKButton";
// Hide popup.
okayButton.Clicked += (obj, ee) =>
{
_popup.SetDisplayState(Tizen.NUI.UIComponents.Popup.DisplayStateType.Hidden);
return false;
};
// Move focus to cancelButton.
okayButton.KeyEvent += (obj, e) =>
{
if (e.Key.KeyPressedName == "Right" && Key.StateType.Down == e.Key.State)
{
FocusManager.Instance.SetCurrentFocusView(cancelButton);
}
return false;
};
return okayButton;
}
/// <summary>
/// Create the okButton
/// </summary>
/// <returns>
/// The created okButton.
/// </returns>
PushButton CreateCancelButton()
{
Button cancelSample = new Button("Cancel");
cancelButton = cancelSample.GetPushButton();
// Hide popup.
cancelButton.Clicked += (obj, ee) =>
{
_popup.SetDisplayState(Tizen.NUI.UIComponents.Popup.DisplayStateType.Hidden);
return false;
};
// Move focus to okayButton.
cancelButton.KeyEvent += (obj, e) =>
{
if (e.Key.KeyPressedName == "Left" && Key.StateType.Down == e.Key.State)
{
FocusManager.Instance.SetCurrentFocusView(okayButton);
}
return false;
};
return cancelButton;
}
}
}
| 35.076233 | 101 | 0.58425 | [
"Apache-2.0"
] | Jonathan435/Tizen-CSharp-Samples | TV/UIControlSample/UIControlSample/src/Views/Popup.cs | 7,822 | C# |
using Microsoft.AspNetCore.Components;
using ReplyApp.Models;
using System;
using BlazorInputFile;
using System.Linq;
using ReplyApp.Managers;
namespace ReplyApp.Pages.Replys.Components
{
public partial class EditorForm
{
#region Fields
private string parentId = "";
protected int[] parentIds = { 1, 2, 3 };
/// <summary>
/// 첨부 파일 리스트 보관
/// </summary>
private IFileListEntry[] selectedFiles;
#endregion
#region Properties
/// <summary>
/// 모달 다이얼로그를 표시할건지 여부
/// </summary>
public bool IsShow { get; set; } = false;
#endregion
#region Public Methods
/// <summary>
/// 폼 보이기
/// </summary>
public void Show()
{
IsShow = true; // 현재 인라인 모달 폼 보이기
}
/// <summary>
/// 폼 닫기
/// </summary>
public void Hide()
{
IsShow = false; // 현재 인라인 모달 폼 숨기기
}
#endregion
#region Parameters
/// <summary>
/// 폼의 제목 영역
/// </summary>
[Parameter]
public RenderFragment EditorFormTitle { get; set; }
/// <summary>
/// 넘어온 모델 개체
/// </summary>
[Parameter]
public Reply Model { get; set; }
/// <summary>
/// 부모 컴포넌트에게 생성(Create)이 완료되었다고 보고하는 목적으로 부모 컴포넌트에게 알림
/// 학습 목적으로 Action 대리자 사용
/// </summary>
[Parameter]
public Action CreateCallback { get; set; }
/// <summary>
/// 부모 컴포넌트에게 수정(Edit)이 완료되었다고 보고하는 목적으로 부모 컴포넌트에게 알림
/// 학습 목적으로 EventCallback 구조체 사용
/// </summary>
[Parameter]
public EventCallback<bool> EditCallback { get; set; }
[Parameter]
public string ParentKey { get; set; } = "";
#endregion
#region Injectors
/// <summary>
/// 리포지토리 클래스에 대한 참조
/// </summary>
[Inject]
public IReplyRepository RepositoryReference { get; set; }
[Inject]
public IFileStorageManager FileStorageManagerReference { get; set; }
#endregion
#region Lifecycle Methods
protected override void OnParametersSet()
{
// ParentId가 넘어온 값이 있으면... 즉, 0이 아니면 ParentId 드롭다운 리스트 기본값 선택
parentId = Model.ParentId.ToString();
if (parentId == "0")
{
parentId = "";
}
}
#endregion
#region Event Handlers
protected async void CreateOrEditClick()
{
#region 파일 업로드 관련 추가 코드 영역
if (selectedFiles != null && selectedFiles.Length > 0)
{
// 파일 업로드
var file = selectedFiles.FirstOrDefault();
var fileName = "";
int fileSize = 0;
if (file != null)
{
//file.Name = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}{file.Name}";
fileName = file.Name;
fileSize = Convert.ToInt32(file.Size);
//[A] byte[] 형태
//var ms = new MemoryStream();
//await file.Data.CopyToAsync(ms);
//await FileStorageManager.ReplyAsync(ms.ToArray(), file.Name, "", true);
//[B] Stream 형태
//string folderPath = Path.Combine(WebHostEnvironment.WebRootPath, "files");
await FileStorageManagerReference.UploadAsync(file.Data, file.Name, "", true);
Model.FileName = fileName;
Model.FileSize = fileSize;
}
}
#endregion
if (!int.TryParse(parentId, out int newParentId))
{
newParentId = 0;
}
Model.ParentId = newParentId;
Model.ParentKey = Model.ParentKey;
if (Model.Id == 0)
{
// Create
await RepositoryReference.AddAsync(Model);
CreateCallback?.Invoke();
}
else
{
// Edit
await RepositoryReference.EditAsync(Model);
await EditCallback.InvokeAsync(true);
}
//IsShow = false; // this.Hide()
}
protected void HandleSelection(IFileListEntry[] files)
{
this.selectedFiles = files;
}
#endregion
}
}
| 27.938272 | 98 | 0.484534 | [
"MIT"
] | VisualAcademy/RestApi | ReplyApp_Final/ReplyApp/Pages/Replys/Components/EditorForm.razor.cs | 4,966 | C# |
using LiveSplit.Web;
using System;
using System.Xml;
namespace LiveSplit.Model
{
public struct Time
{
public static readonly Time Zero = new Time(TimeSpan.Zero, TimeSpan.Zero);
public TimeSpan? RealTime { get; set; }
public TimeSpan? GameTime { get; set; }
public Time(TimeSpan? realTime = null, TimeSpan? gameTime = null)
: this()
{
RealTime = realTime;
GameTime = gameTime;
}
public Time(Time time)
: this()
{
RealTime = time.RealTime;
GameTime = time.GameTime;
}
public TimeSpan? this[TimingMethod method]
{
get { return method == TimingMethod.RealTime ? RealTime : GameTime; }
set
{
if (method == TimingMethod.RealTime)
RealTime = value;
else
GameTime = value;
}
}
public static Time FromXml(XmlElement element)
{
var newTime = new Time();
TimeSpan x;
if (element.GetElementsByTagName("RealTime").Count > 0)
{
if (TimeSpan.TryParse(element["RealTime"].InnerText, out x))
newTime.RealTime = x;
}
if (element.GetElementsByTagName("GameTime").Count > 0)
{
if (TimeSpan.TryParse(element["GameTime"].InnerText, out x))
newTime.GameTime = x;
}
return newTime;
}
public XmlElement ToXml(XmlDocument document, string name = "Time")
{
var parent = document.CreateElement(name);
if (RealTime != null)
{
var realTime = document.CreateElement("RealTime");
realTime.InnerText = RealTime.ToString();
parent.AppendChild(realTime);
}
if (GameTime != null)
{
var gameTime = document.CreateElement("GameTime");
gameTime.InnerText = GameTime.ToString();
parent.AppendChild(gameTime);
}
return parent;
}
public DynamicJsonObject ToJson()
{
dynamic json = new DynamicJsonObject();
json.realTime = RealTime.ToString();
json.gameTime = GameTime.ToString();
return json;
}
public static Time ParseText(string text)
{
var splits = text.Split('|');
var newTime = new Time();
TimeSpan x;
if (TimeSpan.TryParse(splits[0].TrimEnd(), out x))
newTime.RealTime = x;
else
newTime.RealTime = null;
if (splits.Length > 1)
{
if (TimeSpan.TryParse(splits[1].TrimStart(), out x))
newTime.GameTime = x;
else
newTime.GameTime = null;
}
return newTime;
}
public override string ToString()
{
return RealTime + " | " + GameTime;
}
public static Time operator + (Time a, Time b)
{
return new Time(a.RealTime + b.RealTime, a.GameTime + b.GameTime);
}
public static Time operator -(Time a, Time b)
{
return new Time(a.RealTime - b.RealTime, a.GameTime - b.GameTime);
}
}
}
| 29.491525 | 82 | 0.49023 | [
"MIT"
] | CryZe/LiveSplit | LiveSplit/LiveSplit.Core/Model/Time.cs | 3,482 | C# |
using HeBianGu.General.DataBase.Logger;
using HeBianGu.General.ModuleService;
using HeBianGu.Module.AutoTest.Views;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace HeBianGu.Module.AutoTest
{
// Do :OnDemand = true 按需加载,调用LoadModule时加载
[Module(ModuleName = nameof(AutoTestModule), OnDemand = false)]
public class AutoTestModule : IModule
{
public void OnInitialized(IContainerProvider containerProvider)
{
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
IUnityContainer container = containerRegistry.GetContainer();
IModuleNode root = new ModuleParent(container, "自动测试") { OrderIndex = 0 };
IModuleNode info = new ProcessModuleNode(container, root, "测试流程") { Icon = "\xe6c9" };
info.Functions.Add(new DefaultFunctionNode(containerRegistry, "操作", typeof(ProcessToolBar)));
root.Children.Add(info);
IModuleNode error = new ResultModuleNode(container, root, "测试结果") { Icon = "\xe6c9" };
error.Functions.Add(new DefaultFunctionNode(containerRegistry, "操作", typeof(ResultToolBar)));
root.Children.Add(error);
IModuleNode debug = new CalibrationModuleNode(container, root, "数据校准") { Icon = "\xe6c9" };
debug.Functions.Add(new DefaultFunctionNode(containerRegistry, "操作", typeof(CalibrationBar)));
root.Children.Add(debug);
// Do :注册代理和工具功能
container.RegisterInstance(typeof(IModuleNode), this.GetType().Name, root);
// Do :第一步 注册
containerRegistry.RegisterForNavigation<ProcessView>();
containerRegistry.RegisterForNavigation<ResultView>();
containerRegistry.RegisterForNavigation<CalibrationView>();
//containerRegistry.RegisterForNavigation<FatalLogView>();
//containerRegistry.RegisterForNavigation<WarnLogView>();
//containerRegistry.RegisterForNavigation<ModuleCEditer>();
// Do :注册服务
container.RegisterType<IInfoRespository, InfoRespository>();
container.RegisterType<IErrorRespository, ErrorRespository>();
}
}
}
| 33.614286 | 106 | 0.675733 | [
"MIT"
] | HeBianGu/WPF-Modules | Source/Module/HeBianGu.Module.AutoTest/AutoTestModule.cs | 2,463 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* 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.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
using System;
using System.Collections.Generic;
using System.Text;
using Ca.Infoway.Messagebuilder;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Datatype.Lang.Util;
using Ca.Infoway.Messagebuilder.Datatype.Nullflavor;
using Ca.Infoway.Messagebuilder.Domainvalue;
using Ca.Infoway.Messagebuilder.Error;
using Ca.Infoway.Messagebuilder.Marshalling.HL7;
using Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter;
using Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.R2;
using Ca.Infoway.Messagebuilder.Xml;
namespace Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.R2
{
/// <summary>
/// IVL - Interval (R2)
/// Represents an Interval object as an element:
/// <value>
/// <low value='2'/>
/// <high value='4'/>
/// </value>
/// or:
/// <value>
/// <width unit="d" value="15"/>
/// </value>
/// If an object is null, value is replaced by a nullFlavor.
/// </summary>
/// <remarks>
/// IVL - Interval (R2)
/// Represents an Interval object as an element:
/// <value>
/// <low value='2'/>
/// <high value='4'/>
/// </value>
/// or:
/// <value>
/// <width unit="d" value="15"/>
/// </value>
/// If an object is null, value is replaced by a nullFlavor. So the element would
/// look like this:
/// <element-name nullFlavor="something" />
/// http://www.hl7.org/v3ballot/html/infrastructure/itsxml/datatypes-its-xml.htm#dtimpl-IVL
/// </remarks>
internal abstract class IvlR2PropertyFormatter<T> : AbstractNullFlavorPropertyFormatter<Interval<T>>
{
private IvlValidationUtils ivlValidationUtils = new IvlValidationUtils();
private static readonly string UNITS_OF_MEASURE_DAY = "d";
protected static readonly string UNIT = "unit";
protected static readonly string WIDTH = "width";
protected static readonly string CENTRE = "center";
protected static readonly string HIGH = "high";
protected static readonly string LOW = "low";
protected static readonly string VALUE = "value";
protected override string FormatNonNullValue(FormatContext context, Interval<T> value, int indentLevel)
{
// need to use the alternate format method that has the BareANY object as a parameter
throw new NotSupportedException();
}
protected override string FormatNonNullDataType(FormatContext context, BareANY bareAny, int indentLevel)
{
Interval<T> value = ExtractBareValue(bareAny);
context = ValidateInterval(value, bareAny, context);
StringBuilder buffer = new StringBuilder();
if (value.Representation == Representation.SIMPLE)
{
QTYImpl<T> qty = (QTYImpl<T>)CreateQTY(value.Value, null);
qty.Operator = value.Operator;
buffer.Append(CreateElement(context, context.GetElementName(), qty, null, true, indentLevel));
}
else
{
buffer.Append(CreateElement(context, null, indentLevel, false, true));
AppendIntervalBounds(context, value, buffer, indentLevel + 1);
buffer.Append(CreateElementClosure(context, indentLevel, true));
}
return buffer.ToString();
}
private FormatContext ValidateInterval(Interval<T> value, BareANY bareAny, FormatContext context)
{
bool lowProvided = RepresentationUtil.HasLow(value.Representation) && (value.Low != null || value.LowNullFlavor != null);
bool highProvided = RepresentationUtil.HasHigh(value.Representation) && (value.High != null || value.HighNullFlavor != null
);
bool centerProvided = RepresentationUtil.HasCentre(value.Representation) && (value.Centre != null || value.CentreNullFlavor
!= null);
bool widthProvided = RepresentationUtil.HasWidth(value.Representation) && (value.Width != null && (value.Width.Value != null
|| value.Width.NullFlavor != null));
IList<string> errors = this.ivlValidationUtils.ValidateCorrectElementsProvidedForR2(lowProvided, highProvided, centerProvided
, widthProvided);
RecordAnyErrors(errors, context);
return context;
}
private void RecordAnyErrors(IList<string> errors, FormatContext context)
{
foreach (string error in errors)
{
RecordError(error, context);
}
}
private void AppendIntervalBounds(FormatContext context, Interval<T> value, StringBuilder buffer, int indentLevel)
{
Representation rep = value.Representation;
string low = RepresentationUtil.HasLow(rep) ? CreateElement(context, IvlR2PropertyFormatter<T>.LOW, CreateQTY(value.Low,
value.LowNullFlavor), GetInclusiveValue(value, true), false, indentLevel) : null;
string high = RepresentationUtil.HasHigh(rep) ? CreateElement(context, IvlR2PropertyFormatter<T>.HIGH, CreateQTY(value.High
, value.HighNullFlavor), GetInclusiveValue(value, false), false, indentLevel) : null;
string centre = RepresentationUtil.HasCentre(rep) ? CreateElement(context, IvlR2PropertyFormatter<T>.CENTRE, CreateQTY(value
.Centre, value.CentreNullFlavor), null, false, indentLevel) : null;
string width = RepresentationUtil.HasWidth(rep) ? CreateWidthElement(context, IvlR2PropertyFormatter<T>.WIDTH, value.Width
, indentLevel) : null;
switch (rep)
{
case Representation.LOW_HIGH:
{
buffer.Append(low);
buffer.Append(high);
break;
}
case Representation.CENTRE:
{
buffer.Append(centre);
break;
}
case Representation.HIGH:
{
buffer.Append(high);
break;
}
case Representation.LOW:
{
buffer.Append(low);
break;
}
case Representation.WIDTH:
{
buffer.Append(width);
break;
}
case Representation.LOW_WIDTH:
{
buffer.Append(low);
buffer.Append(width);
break;
}
case Representation.LOW_CENTER:
{
buffer.Append(low);
buffer.Append(centre);
break;
}
case Representation.WIDTH_HIGH:
{
buffer.Append(width);
buffer.Append(high);
break;
}
case Representation.CENTRE_WIDTH:
{
buffer.Append(centre);
buffer.Append(width);
break;
}
case Representation.CENTRE_HIGH:
{
buffer.Append(centre);
buffer.Append(high);
break;
}
default:
{
break;
}
}
}
private Boolean? GetInclusiveValue(Interval<T> value, bool isLow)
{
if (value == null)
{
return null;
}
return isLow ? value.LowInclusive : value.HighInclusive;
}
private QTY<T> CreateQTY(T value, NullFlavor nullFlavor)
{
return new QTYImpl<T>(null, value, nullFlavor, StandardDataType.QTY);
}
protected virtual string GetDateDiffUnits(BareDiff diff)
{
if (diff is DiffWithQuantityAndUnit)
{
Ca.Infoway.Messagebuilder.Domainvalue.UnitsOfMeasureCaseSensitive unit = ((DiffWithQuantityAndUnit)diff).Unit;
return unit != null ? unit.CodeValue : string.Empty;
}
else
{
return IvlR2PropertyFormatter<T>.UNITS_OF_MEASURE_DAY;
}
}
protected virtual string FormatDateDiff(BareDiff diff)
{
if (diff is DiffWithQuantityAndUnit)
{
PhysicalQuantity quantity = ((DiffWithQuantityAndUnit)diff).ValueAsPhysicalQuantity;
return quantity == null ? string.Empty : ObjectUtils.ToString(quantity.Quantity);
}
else
{
PlatformDate date;
if (diff.BareValue is PlatformDate)
{
date = (PlatformDate)diff.BareValue;
}
else
{
date = ((MbDate)diff.BareValue).Value;
}
long l = date.Time / DateUtils.MILLIS_PER_DAY;
return l.ToString();
}
}
protected virtual string CreateTimestampWidthElement(FormatContext context, string name, BareDiff diff, int indentLevel)
{
if (diff != null)
{
IDictionary<string, string> attributes;
if (diff is NullFlavorSupport && ((NullFlavorSupport)diff).HasNullFlavor())
{
NullFlavorSupport nullable = diff;
attributes = ToStringMap(AbstractPropertyFormatter.NULL_FLAVOR_ATTRIBUTE_NAME, nullable.NullFlavor.CodeValue);
}
else
{
attributes = ToStringMap(IvlR2PropertyFormatter<T>.VALUE, FormatDateDiff(diff), IvlR2PropertyFormatter<T>.UNIT, GetDateDiffUnits
(diff));
}
return CreateElement(name, attributes, indentLevel, true, true);
}
return null;
}
protected virtual string CreateWidthElement(FormatContext context, string name, BareDiff diff, int indentLevel)
{
if (IsTimestamp(context))
{
return CreateTimestampWidthElement(context, name, diff, indentLevel);
}
else
{
string type = Hl7DataTypeName.GetParameterizedType(context.Type);
PropertyFormatter formatter = FormatterR2Registry.GetInstance().Get(type);
if (formatter != null)
{
bool isSpecializationType = false;
return formatter.Format(new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(type, isSpecializationType
, Ca.Infoway.Messagebuilder.Xml.ConformanceLevel.MANDATORY, Cardinality.Create("1"), name, context), WrapWithHl7DataType
(type, diff), indentLevel);
}
else
{
throw new ModelToXmlTransformationException("No formatter found for " + type);
}
}
}
private BareANY WrapWithHl7DataType(string hl7DataType, BareDiff diff)
{
try
{
BareANY hl7Value = (BareANY)DataTypeFactory.CreateDataType(hl7DataType, true);
if (diff != null)
{
if (diff.BareValue != null)
{
((BareANYImpl)hl7Value).BareValue = diff.BareValue;
}
else
{
hl7Value.NullFlavor = diff.NullFlavor;
}
}
return hl7Value;
}
catch (Exception e)
{
throw new ModelToXmlTransformationException("Unable to instantiate HL7 data type: " + hl7DataType, e);
}
}
private bool IsTimestamp(FormatContext context)
{
return "TS".Equals(Hl7DataTypeName.Unqualify(Hl7DataTypeName.GetParameterizedType(context.Type)));
}
protected virtual string CreateElement(FormatContext context, string name, QTY<T> value, Boolean? inclusive, bool isSxcm,
int indentLevel)
{
string type = Hl7DataTypeName.GetParameterizedType(context.Type);
if (isSxcm)
{
type = "SXCM<" + type + ">";
}
PropertyFormatter formatter = FormatterR2Registry.GetInstance().Get(type);
if (formatter != null)
{
bool isSpecializationType = false;
FormatContext newContext = new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(type, isSpecializationType
, Ca.Infoway.Messagebuilder.Xml.ConformanceLevel.POPULATED, Cardinality.Create("1"), name, context);
string result = formatter.Format(newContext, value, indentLevel);
if (inclusive != null)
{
// TM - small hack to add in the inclusive attribute (low/high) (operator, simple only, is already formatted by using the SXCM type)
result = result.ReplaceFirst(" value=", " inclusive=\"" + inclusive.ToString().ToLower() + "\" value=");
}
return result;
}
else
{
throw new ModelToXmlTransformationException("No formatter found for " + type);
}
}
private void RecordError(string message, FormatContext context)
{
string propertyPath = context.GetPropertyPath();
context.GetModelToXmlResult().AddHl7Error(new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, message, propertyPath));
}
}
}
| 32.573684 | 138 | 0.683632 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-core/Main/Ca/Infoway/Messagebuilder/Marshalling/HL7/Formatter/R2/IvlR2PropertyFormatter.cs | 12,378 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Cdn.Models;
namespace Azure.ResourceManager.Cdn
{
/// <summary>
/// A Class representing an AfdOriginGroup along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct an <see cref="AfdOriginGroupResource" />
/// from an instance of <see cref="ArmClient" /> using the GetAfdOriginGroupResource method.
/// Otherwise you can get one from its parent resource <see cref="ProfileResource" /> using the GetAfdOriginGroup method.
/// </summary>
public partial class AfdOriginGroupResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="AfdOriginGroupResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string profileName, string originGroupName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _afdOriginGroupClientDiagnostics;
private readonly AfdOriginGroupsRestOperations _afdOriginGroupRestClient;
private readonly AfdOriginGroupData _data;
/// <summary> Initializes a new instance of the <see cref="AfdOriginGroupResource"/> class for mocking. </summary>
protected AfdOriginGroupResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "AfdOriginGroupResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal AfdOriginGroupResource(ArmClient client, AfdOriginGroupData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="AfdOriginGroupResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal AfdOriginGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_afdOriginGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Cdn", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string afdOriginGroupApiVersion);
_afdOriginGroupRestClient = new AfdOriginGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, afdOriginGroupApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Cdn/profiles/originGroups";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual AfdOriginGroupData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets a collection of AfdOriginResources in the AfdOriginGroup. </summary>
/// <returns> An object representing collection of AfdOriginResources and their operations over a AfdOriginResource. </returns>
public virtual AfdOriginCollection GetAfdOrigins()
{
return GetCachedClient(Client => new AfdOriginCollection(Client, Id));
}
/// <summary>
/// Gets an existing origin within an origin group.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}
/// Operation Id: AfdOrigins_Get
/// </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
[ForwardsClientCalls]
public virtual async Task<Response<AfdOriginResource>> GetAfdOriginAsync(string originName, CancellationToken cancellationToken = default)
{
return await GetAfdOrigins().GetAsync(originName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets an existing origin within an origin group.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}
/// Operation Id: AfdOrigins_Get
/// </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
[ForwardsClientCalls]
public virtual Response<AfdOriginResource> GetAfdOrigin(string originName, CancellationToken cancellationToken = default)
{
return GetAfdOrigins().Get(originName, cancellationToken);
}
/// <summary>
/// Gets an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<AfdOriginGroupResource>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Get");
scope.Start();
try
{
var response = await _afdOriginGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new AfdOriginGroupResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<AfdOriginGroupResource> Get(CancellationToken cancellationToken = default)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Get");
scope.Start();
try
{
var response = _afdOriginGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new AfdOriginGroupResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Delete");
scope.Start();
try
{
var response = await _afdOriginGroupRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new CdnArmOperation(_afdOriginGroupClientDiagnostics, Pipeline, _afdOriginGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Delete");
scope.Start();
try
{
var response = _afdOriginGroupRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new CdnArmOperation(_afdOriginGroupClientDiagnostics, Pipeline, _afdOriginGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Update
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="patch"> Origin group properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual async Task<ArmOperation<AfdOriginGroupResource>> UpdateAsync(WaitUntil waitUntil, AfdOriginGroupPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Update");
scope.Start();
try
{
var response = await _afdOriginGroupRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, patch, cancellationToken).ConfigureAwait(false);
var operation = new CdnArmOperation<AfdOriginGroupResource>(new AfdOriginGroupOperationSource(Client), _afdOriginGroupClientDiagnostics, Pipeline, _afdOriginGroupRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, patch).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates an existing origin group within a profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}
/// Operation Id: AfdOriginGroups_Update
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="patch"> Origin group properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual ArmOperation<AfdOriginGroupResource> Update(WaitUntil waitUntil, AfdOriginGroupPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.Update");
scope.Start();
try
{
var response = _afdOriginGroupRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, patch, cancellationToken);
var operation = new CdnArmOperation<AfdOriginGroupResource>(new AfdOriginGroupOperationSource(Client), _afdOriginGroupClientDiagnostics, Pipeline, _afdOriginGroupRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, patch).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages
/// Operation Id: AfdOriginGroups_ListResourceUsage
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="CdnUsage" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<CdnUsage> GetResourceUsagesAsync(CancellationToken cancellationToken = default)
{
async Task<Page<CdnUsage>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.GetResourceUsages");
scope.Start();
try
{
var response = await _afdOriginGroupRestClient.ListResourceUsageAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<CdnUsage>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.GetResourceUsages");
scope.Start();
try
{
var response = await _afdOriginGroupRestClient.ListResourceUsageNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/usages
/// Operation Id: AfdOriginGroups_ListResourceUsage
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="CdnUsage" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<CdnUsage> GetResourceUsages(CancellationToken cancellationToken = default)
{
Page<CdnUsage> FirstPageFunc(int? pageSizeHint)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.GetResourceUsages");
scope.Start();
try
{
var response = _afdOriginGroupRestClient.ListResourceUsage(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<CdnUsage> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _afdOriginGroupClientDiagnostics.CreateScope("AfdOriginGroupResource.GetResourceUsages");
scope.Start();
try
{
var response = _afdOriginGroupRestClient.ListResourceUsageNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
}
}
| 60.669355 | 488 | 0.66547 | [
"MIT"
] | jasonsandlin/azure-sdk-for-net | sdk/cdn/Azure.ResourceManager.Cdn/src/Generated/AfdOriginGroupResource.cs | 22,569 | C# |
// <auto-generated />
namespace GreekHealthcareNetwork.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class UpdatetypeofAMKAdatatypeofDoBandSubscriptionEndDate : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(UpdatetypeofAMKAdatatypeofDoBandSubscriptionEndDate));
string IMigrationMetadata.Id
{
get { return "201912232139262_Update type of AMKA, datatype of DoB and SubscriptionEndDate"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 31.866667 | 134 | 0.666318 | [
"MIT"
] | karabasisilias92/greek-healthcare-network | GreekHealthcareNetwork/GreekHealthcareNetwork/Migrations/201912232139262_Update type of AMKA, datatype of DoB and SubscriptionEndDate.Designer.cs | 956 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
[InitializeOnLoad]
public class RecentScenesMenu : EditorWindow
{
[MenuItem("Window/Recent Scenes Menu")]
static void OpenMenu()
{
RecentScenesMenu window = GetWindow<RecentScenesMenu>();
window.position = new Rect(60.0f, 60.0f, windowWidth, windowHeight);
window.resetPosition = false;
window.Show();
}
static List<string> recentScenes = new List<string>();
static readonly int MaxDispScene = 3;
static readonly float windowWidth = 360.0f;
static readonly float windowHeight = 80.0f;
bool resetPosition = false;
static RecentScenesMenu()
{
EditorApplication.hierarchyWindowChanged += OnHierarchyWindowChanged;
}
static void OnHierarchyWindowChanged()
{
UpdateRecentScenesList();
}
static void UpdateRecentScenesList()
{
var currentScenes = new List<string>();
for (int i = 0; i < EditorSceneManager.sceneCount; ++i)
{
var scene = EditorSceneManager.GetSceneAt(i);
currentScenes.Add(scene.path);
}
recentScenes.RemoveAll((x) => currentScenes.Contains(x));
recentScenes.AddRange(currentScenes);
}
private void OnEnable()
{
UpdateRecentScenesList();
}
private void OnGUI()
{
if( !resetPosition && (Event.current != null ))
{
Vector2 mousePosition = Event.current.mousePosition;
position = new Rect(mousePosition.x, mousePosition.y, windowWidth, windowHeight);
resetPosition = true;
}
string nextLevel = null;
for ( int i = 0; (i < MaxDispScene) && (i < recentScenes.Count); ++i )
{
var s = recentScenes[recentScenes.Count - i - 1];
if (GUILayout.Button(string.Concat("Load ", s) ) )
{
nextLevel = s;
}
}
if( !string.IsNullOrEmpty(nextLevel) )
{
EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
EditorSceneManager.OpenScene(nextLevel);
Close();
}
}
}
| 26.482353 | 93 | 0.609951 | [
"MIT"
] | kuriharaan/LoadSceneMenu | Assets/RecentScenesMenu/Editor/RecentScenesMenu.cs | 2,253 | 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 System.Windows.Forms
{
using System;
using System.Diagnostics;
/// <include file='doc\DataGridViewColumnEventArgs.uex' path='docs/doc[@for="DataGridViewColumnEventArgs"]/*' />
public class DataGridViewColumnEventArgs : EventArgs
{
private DataGridViewColumn dataGridViewColumn;
/// <include file='doc\DataGridViewColumnEventArgs.uex' path='docs/doc[@for="DataGridViewColumnEventArgs.DataGridViewColumnEventArgs"]/*' />
public DataGridViewColumnEventArgs(DataGridViewColumn dataGridViewColumn)
{
if (dataGridViewColumn == null)
{
throw new ArgumentNullException(nameof(dataGridViewColumn));
}
Debug.Assert(dataGridViewColumn.Index >= -1);
this.dataGridViewColumn = dataGridViewColumn;
}
/// <include file='doc\DataGridViewColumnEventArgs.uex' path='docs/doc[@for="DataGridViewColumnEventArgs.Column"]/*' />
public DataGridViewColumn Column
{
get
{
return this.dataGridViewColumn;
}
}
}
}
| 36.888889 | 148 | 0.659639 | [
"MIT"
] | Liminiens/winforms | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnEventArgs.cs | 1,328 | C# |
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using System;
using System.Collections.Generic;
using System.Xml;
namespace SnowPlow
{
public class XmlTestCaseReader
{
private ITestCaseDiscoverySink testCaseSink;
public IEnumerable<TestCase> TestCases { get { return _testCases; } }
private List<TestCase> _testCases;
public XmlTestCaseReader(ITestCaseDiscoverySink testCaseSink)
{
this.testCaseSink = testCaseSink;
_testCases = new List<TestCase>();
}
public void Read(string testSource, string content)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
var testNodes = doc.SelectNodes("//testsuite/testcase");
foreach (XmlNode testNode in testNodes)
{
XmlAttribute nameAttribute = testNode.Attributes["name"];
XmlAttribute classnameAttribute = testNode.Attributes["classname"];
XmlAttribute codefile = testNode.Attributes["file"];
XmlAttribute linenumber = testNode.Attributes["linenumber"];
if (nameAttribute != null && !String.IsNullOrWhiteSpace(nameAttribute.Value))
{
string name;
string displayName;
if (classnameAttribute != null && !String.IsNullOrWhiteSpace(classnameAttribute.Value))
{
name = IglooSpecNameFormatter.BuildTestName(classnameAttribute.Value, nameAttribute.Value);
displayName = IglooSpecNameFormatter.BuildDisplayName(classnameAttribute.Value, nameAttribute.Value);
}
else
{
name = IglooSpecNameFormatter.BuildTestName(nameAttribute.Value);
displayName = IglooSpecNameFormatter.BuildDisplayName(nameAttribute.Value);
}
var testCase = new TestCase(name, SnowPlowTestExecutor.ExecutorUri, testSource);
testCase.DisplayName = displayName;
if (codefile != null && !String.IsNullOrWhiteSpace(codefile.Value))
{
testCase.CodeFilePath = codefile.Value;
uint number;
if (linenumber != null && uint.TryParse(linenumber.Value, out number))
{
testCase.LineNumber = (int)number;
}
}
_testCases.Add(testCase);
if (testCaseSink != null) // The sink will be null when test discovery is called as part of test execution.
{
testCaseSink.SendTestCase(testCase);
}
}
}
}
}
}
| 40.64 | 128 | 0.543963 | [
"MIT"
] | othrayte/snowplow | SnowPlow/XmlTestCaseReader.cs | 3,050 | C# |
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace AdventureWorksModel
{
public class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
// Primary Key
HasKey(t => t.CustomerID);
//Ignores
Ignore(t => t.CustomerType);
// Properties
Property(t => t.AccountNumber)
.IsRequired()
.HasMaxLength(10)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Property(t => t.StoreID).IsOptional();
Property(t => t.PersonID).IsOptional();
Property(t => t.SalesTerritoryID).IsOptional();
// Table & Column Mappings
ToTable("Customer", "Sales");
Property(t => t.CustomerID).HasColumnName("CustomerID");
Property(t => t.SalesTerritoryID).HasColumnName("TerritoryID");
Property(t => t.StoreID).HasColumnName("StoreID");
Property(t => t.PersonID).HasColumnName("PersonID");
Property(t => t.AccountNumber).HasColumnName("AccountNumber");
Property(t => t.CustomerRowguid).HasColumnName("rowguid");
Property(t => t.CustomerModifiedDate).HasColumnName("ModifiedDate");
// Relationships
HasOptional(t => t.SalesTerritory).WithMany().HasForeignKey(t => t.SalesTerritoryID);
HasOptional(t => t.Store).WithMany().HasForeignKey(t => t.StoreID);
HasOptional(t => t.Person).WithMany().HasForeignKey(t => t.PersonID);
}
}
}
| 37.837209 | 95 | 0.600492 | [
"Apache-2.0"
] | Giovanni-Russo-Boscoli/NakedObjectsFramework | Samples/AWFunctional/Mapping/CustomerMap.cs | 1,627 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace ABP_CORE_MPA.Migrations
{
public partial class Upgraded_To_Abp_v222 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "AbpUserOrganizationUnits",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "AbpUserOrganizationUnits");
}
}
}
| 28 | 71 | 0.598214 | [
"MIT"
] | staneee/ServiceFabricDemo | ABP/ABP_CORE_MPA.EntityFrameworkCore/Migrations/20170804083601_Upgraded_To_Abp_v2.2.2.cs | 674 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogLib
{
public sealed class NullLogger : ILogger
{
private static NullLogger instance=new NullLogger();
public static NullLogger Instance
{
get { return instance; }
}
private NullLogger()
{
}
public void Dispose()
{
}
public void Log(Log Log)
{
}
public void Log(int ComponentID, string ComponentName, string MethodName, LogLevels Level, string Message)
{
}
public void Log(int ComponentID, string ComponentName, string MethodName, Exception ex)
{
}
public void LogEnter(int ComponentID, string ComponentName, string MethodName)
{
}
public void LogLeave(int ComponentID, string ComponentName, string MethodName)
{
}
}
}
| 16.714286 | 108 | 0.713065 | [
"MIT"
] | dfgs/LogLib | LogLib/NullLogger.cs | 821 | 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 System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Health.Core;
using Microsoft.Health.Core.Features.Context;
using Microsoft.Health.Fhir.Core.Features.Context;
using Microsoft.Health.Fhir.Core.Features.Operations;
using Microsoft.Health.Fhir.Core.Features.Operations.Import;
using Microsoft.Health.Fhir.Core.Features.Operations.Import.Models;
using Microsoft.Health.TaskManagement;
using Newtonsoft.Json;
using NSubstitute;
using Xunit;
namespace Microsoft.Health.Fhir.Core.UnitTests.Features.Operations.Import
{
public class ImportOrchestratorTaskTests
{
[Fact]
public async Task GivenAnOrchestratorTask_WhenProcessingInputFilesMoreThanConcurrentCount_ThenTaskShouldBeCompleted()
{
await VerifyCommonOrchestratorTaskAsync(105, 6);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenProcessingInputFilesEqualsConcurrentCount_ThenTaskShouldBeCompleted()
{
await VerifyCommonOrchestratorTaskAsync(105, 105);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenProcessingInputFilesLessThanConcurrentCount_ThenTaskShouldBeCompleted()
{
await VerifyCommonOrchestratorTaskAsync(11, 105);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenResumeFromFailure_ThenTaskShouldBeCompleted()
{
await VerifyCommonOrchestratorTaskAsync(105, 6, 10);
}
[Fact]
public async Task GivenAnOrchestratorTaskAndWrongEtag_WhenOrchestratorTaskStart_ThenTaskShouldFailedWithDetails()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
ITaskManager taskManager = Substitute.For<ITaskManager>();
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri("http://dummy"), Etag = "dummy" });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
TaskResultData result = await orchestratorTask.ExecuteAsync();
ImportTaskErrorResult resultDetails = JsonConvert.DeserializeObject<ImportTaskErrorResult>(result.ResultData);
Assert.Equal(TaskResult.Fail, result.Result);
Assert.Equal(HttpStatusCode.BadRequest, resultDetails.HttpStatusCode);
Assert.NotEmpty(resultDetails.ErrorMessage);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenIntegrationExceptionThrow_ThenTaskShouldFailedWithDetails()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
ITaskManager taskManager = Substitute.For<ITaskManager>();
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri("http://dummy"), Etag = "dummy" });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns<Task<Dictionary<string, object>>>(_ =>
{
throw new IntegrationDataStoreException("dummy", HttpStatusCode.Unauthorized);
});
sequenceIdGenerator.GetCurrentSequenceId().Returns(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
TaskResultData result = await orchestratorTask.ExecuteAsync();
ImportTaskErrorResult resultDetails = JsonConvert.DeserializeObject<ImportTaskErrorResult>(result.ResultData);
Assert.Equal(TaskResult.Fail, result.Result);
Assert.Equal(HttpStatusCode.Unauthorized, resultDetails.HttpStatusCode);
Assert.NotEmpty(resultDetails.ErrorMessage);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenFailedAtPreprocessStep_ThenRetrableExceptionShouldBeThrowAndContextUpdated()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
t.Status = TaskManagement.TaskStatus.Running;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
fhirDataBulkImportOperation.PreprocessAsync(Arg.Any<CancellationToken>())
.Returns(_ =>
{
throw new InvalidCastException();
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
await Assert.ThrowsAnyAsync<RetriableTaskException>(() => orchestratorTask.ExecuteAsync());
ImportOrchestratorTaskContext context = JsonConvert.DeserializeObject<ImportOrchestratorTaskContext>(latestContext);
Assert.Equal(ImportOrchestratorTaskProgress.InputResourcesValidated, context.Progress);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenFailedAtGenerateSubTasksStep_ThenRetrableExceptionShouldBeThrowAndContextUpdated()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
t.Status = TaskManagement.TaskStatus.Running;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns<long>(_ => throw new InvalidOperationException());
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
await Assert.ThrowsAnyAsync<RetriableTaskException>(() => orchestratorTask.ExecuteAsync());
ImportOrchestratorTaskContext context = JsonConvert.DeserializeObject<ImportOrchestratorTaskContext>(latestContext);
Assert.Equal(ImportOrchestratorTaskProgress.PreprocessCompleted, context.Progress);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenFailedAtMonitorSubTasksStep_ThenRetrableExceptionShouldBeThrowAndContextUpdated()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
throw new InvalidOperationException();
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns<long>(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
await Assert.ThrowsAnyAsync<RetriableTaskException>(() => orchestratorTask.ExecuteAsync());
ImportOrchestratorTaskContext context = JsonConvert.DeserializeObject<ImportOrchestratorTaskContext>(latestContext);
Assert.Equal(ImportOrchestratorTaskProgress.SubTaskRecordsGenerated, context.Progress);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenSubTaskFailed_ThenImportProcessingExceptionShouldBeThrowAndContextUpdated()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
TaskResultData resultData = new TaskResultData();
resultData.Result = TaskResult.Fail;
resultData.ResultData = "error";
t.Result = JsonConvert.SerializeObject(resultData);
t.Status = TaskManagement.TaskStatus.Completed;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns<long>(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
TaskResultData taskResultData = await orchestratorTask.ExecuteAsync();
Assert.Equal(TaskResult.Fail, taskResultData.Result);
ImportOrchestratorTaskContext context = JsonConvert.DeserializeObject<ImportOrchestratorTaskContext>(latestContext);
Assert.Equal(ImportOrchestratorTaskProgress.SubTaskRecordsGenerated, context.Progress);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenFailedAtPostProcessStep_ThenRetrableExceptionShouldBeThrowAndContextUpdated()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
ImportProcessingTaskInputData processingInput = JsonConvert.DeserializeObject<ImportProcessingTaskInputData>(t.InputData);
ImportProcessingTaskResult processingResult = new ImportProcessingTaskResult();
processingResult.ResourceType = processingInput.ResourceType;
processingResult.SucceedCount = 1;
processingResult.FailedCount = 1;
processingResult.ErrorLogLocation = "http://dummy/error";
surrogatedIdRanges.Add((processingInput.BeginSequenceId, processingInput.EndSequenceId));
t.Result = JsonConvert.SerializeObject(new TaskResultData(TaskResult.Success, JsonConvert.SerializeObject(processingResult)));
t.Status = TaskManagement.TaskStatus.Completed;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
fhirDataBulkImportOperation.PostprocessAsync(Arg.Any<CancellationToken>())
.Returns(_ =>
{
throw new InvalidCastException();
});
sequenceIdGenerator.GetCurrentSequenceId().Returns<long>(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
await Assert.ThrowsAnyAsync<RetriableTaskException>(() => orchestratorTask.ExecuteAsync());
ImportOrchestratorTaskContext context = JsonConvert.DeserializeObject<ImportOrchestratorTaskContext>(latestContext);
Assert.Equal(ImportOrchestratorTaskProgress.SubTasksCompleted, context.Progress);
Assert.Equal(1, context.DataProcessingTasks.Count);
}
[Fact]
public async Task GivenAnOrchestratorTask_WhenCancelBefore_ThenCanceledResultShouldBeReturn()
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
ImportProcessingTaskInputData processingInput = JsonConvert.DeserializeObject<ImportProcessingTaskInputData>(t.InputData);
ImportProcessingTaskResult processingResult = new ImportProcessingTaskResult();
processingResult.ResourceType = processingInput.ResourceType;
processingResult.SucceedCount = 1;
processingResult.FailedCount = 1;
processingResult.ErrorLogLocation = "http://dummy/error";
surrogatedIdRanges.Add((processingInput.BeginSequenceId, processingInput.EndSequenceId));
t.Result = JsonConvert.SerializeObject(new TaskResultData(TaskResult.Success, JsonConvert.SerializeObject(processingResult)));
t.Status = TaskManagement.TaskStatus.Completed;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri($"http://dummy") });
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = 1;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
string latestContext = null;
contextUpdater.UpdateContextAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
latestContext = (string)callInfo[0];
return Task.CompletedTask;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns<long>(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
orchestratorTask.Cancel();
TaskResultData taskResult = await orchestratorTask.ExecuteAsync();
Assert.Equal(TaskResult.Canceled, taskResult.Result);
}
private static async Task VerifyCommonOrchestratorTaskAsync(int inputFileCount, int concurrentCount, int resumeFrom = -1)
{
IImportOrchestratorTaskDataStoreOperation fhirDataBulkImportOperation = Substitute.For<IImportOrchestratorTaskDataStoreOperation>();
IContextUpdater contextUpdater = Substitute.For<IContextUpdater>();
RequestContextAccessor<IFhirRequestContext> contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>();
ILoggerFactory loggerFactory = new NullLoggerFactory();
IIntegrationDataStoreClient integrationDataStoreClient = Substitute.For<IIntegrationDataStoreClient>();
ISequenceIdGenerator<long> sequenceIdGenerator = Substitute.For<ISequenceIdGenerator<long>>();
ImportOrchestratorTaskInputData importOrchestratorTaskInputData = new ImportOrchestratorTaskInputData();
ImportOrchestratorTaskContext importOrchestratorTaskContext = new ImportOrchestratorTaskContext();
List<(long begin, long end)> surrogatedIdRanges = new List<(long begin, long end)>();
TestTaskManager taskManager = new TestTaskManager(t =>
{
if (t == null)
{
return null;
}
if (t.Status == TaskManagement.TaskStatus.Completed)
{
return t;
}
ImportProcessingTaskInputData processingInput = JsonConvert.DeserializeObject<ImportProcessingTaskInputData>(t.InputData);
ImportProcessingTaskResult processingResult = new ImportProcessingTaskResult();
processingResult.ResourceType = processingInput.ResourceType;
processingResult.SucceedCount = 1;
processingResult.FailedCount = 1;
processingResult.ErrorLogLocation = "http://dummy/error";
surrogatedIdRanges.Add((processingInput.BeginSequenceId, processingInput.EndSequenceId));
t.Result = JsonConvert.SerializeObject(new TaskResultData(TaskResult.Success, JsonConvert.SerializeObject(processingResult)));
t.Status = TaskManagement.TaskStatus.Completed;
return t;
});
importOrchestratorTaskInputData.TaskId = Guid.NewGuid().ToString("N");
importOrchestratorTaskInputData.TaskCreateTime = Clock.UtcNow;
importOrchestratorTaskInputData.BaseUri = new Uri("http://dummy");
var inputs = new List<InputResource>();
bool resumeMode = resumeFrom >= 0;
for (int i = 0; i < inputFileCount; ++i)
{
string location = $"http://dummy/{i}";
inputs.Add(new InputResource() { Type = "Resource", Url = new Uri(location) });
if (resumeMode)
{
if (i <= resumeFrom)
{
TaskInfo taskInfo = new TaskInfo();
taskInfo.TaskId = Guid.NewGuid().ToString("N");
ImportProcessingTaskResult processingResult = new ImportProcessingTaskResult();
processingResult.ResourceType = "Resource";
processingResult.SucceedCount = 1;
processingResult.FailedCount = 1;
processingResult.ErrorLogLocation = "http://dummy/error";
taskInfo.Result = JsonConvert.SerializeObject(new TaskResultData(TaskResult.Success, JsonConvert.SerializeObject(processingResult)));
taskInfo.Status = TaskManagement.TaskStatus.Completed;
await taskManager.CreateTaskAsync(taskInfo, false, CancellationToken.None);
importOrchestratorTaskContext.DataProcessingTasks[new Uri(location)] = taskInfo;
}
else
{
TaskInfo taskInfo = new TaskInfo();
taskInfo.TaskId = Guid.NewGuid().ToString("N");
ImportProcessingTaskInputData processingInput = new ImportProcessingTaskInputData();
processingInput.BaseUriString = "http://dummy";
processingInput.BeginSequenceId = i;
processingInput.EndSequenceId = i + 1;
processingInput.ResourceType = "Resource";
taskInfo.InputData = JsonConvert.SerializeObject(processingInput);
await taskManager.CreateTaskAsync(taskInfo, false, CancellationToken.None);
importOrchestratorTaskContext.DataProcessingTasks[new Uri(location)] = taskInfo;
}
importOrchestratorTaskContext.Progress = ImportOrchestratorTaskProgress.SubTaskRecordsGenerated;
}
}
importOrchestratorTaskInputData.Input = inputs;
importOrchestratorTaskInputData.InputFormat = "ndjson";
importOrchestratorTaskInputData.InputSource = new Uri("http://dummy");
importOrchestratorTaskInputData.MaxConcurrentProcessingTaskCount = concurrentCount;
importOrchestratorTaskInputData.ProcessingTaskQueueId = "default";
importOrchestratorTaskInputData.RequestUri = new Uri("http://dummy");
integrationDataStoreClient.GetPropertiesAsync(Arg.Any<Uri>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
Dictionary<string, object> properties = new Dictionary<string, object>();
properties[IntegrationDataStoreClientConstants.BlobPropertyETag] = "test";
properties[IntegrationDataStoreClientConstants.BlobPropertyLength] = 1000L;
return properties;
});
sequenceIdGenerator.GetCurrentSequenceId().Returns(_ => 0L);
ImportOrchestratorTask orchestratorTask = new ImportOrchestratorTask(
importOrchestratorTaskInputData,
importOrchestratorTaskContext,
taskManager,
sequenceIdGenerator,
contextUpdater,
contextAccessor,
fhirDataBulkImportOperation,
integrationDataStoreClient,
loggerFactory);
orchestratorTask.PollingFrequencyInSeconds = 0;
TaskResultData result = await orchestratorTask.ExecuteAsync();
ImportTaskResult resultDetails = JsonConvert.DeserializeObject<ImportTaskResult>(result.ResultData);
Assert.Equal(TaskResult.Success, result.Result);
Assert.Equal(inputFileCount, resultDetails.Output.Count);
foreach (ImportOperationOutcome outcome in resultDetails.Output)
{
Assert.Equal(1, outcome.Count);
Assert.NotNull(outcome.InputUrl);
Assert.NotEmpty(outcome.Type);
}
Assert.Equal(inputFileCount, resultDetails.Error.Count);
foreach (ImportFailedOperationOutcome outcome in resultDetails.Error)
{
Assert.Equal(1, outcome.Count);
Assert.NotNull(outcome.InputUrl);
Assert.NotEmpty(outcome.Type);
Assert.NotEmpty(outcome.Url);
}
Assert.NotEmpty(resultDetails.Request);
Assert.Equal(importOrchestratorTaskInputData.TaskCreateTime, resultDetails.TransactionTime);
var orderedSurrogatedIdRanges = surrogatedIdRanges.OrderBy(r => r.begin).ToArray();
Assert.Equal(inputFileCount, orderedSurrogatedIdRanges.Length + resumeFrom + 1);
for (int i = 0; i < orderedSurrogatedIdRanges.Length - 1; ++i)
{
Assert.True(orderedSurrogatedIdRanges[i].end > orderedSurrogatedIdRanges[i].begin);
Assert.True(orderedSurrogatedIdRanges[i].end <= orderedSurrogatedIdRanges[i + 1].begin);
}
}
}
}
| 55.03876 | 157 | 0.654883 | [
"MIT"
] | ECGKit/fhir-server | src/Microsoft.Health.Fhir.Core.UnitTests/Features/Operations/Import/ImportOrchestratorTaskTests.cs | 42,602 | C# |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.XR.MagicLeap;
namespace SandBox.Scripts.HandPointer
{
public interface IHandPointer
{
float PointerRayDistance { get; set; }
bool IsShow { get; }
MLHandTracking.HandKeyPose SelectKeyPose { get; set; }
MLHandTracking.HandKeyPose RayDrawKeyPose { get; set; }
void RegisterOnSelectHandler(UnityAction<(Vector3, GameObject)> handler);
void RegisterOnSelectContinueHandler(UnityAction<(Vector3, GameObject)> handler);
void Show();
void Hide();
}
} | 29.25 | 89 | 0.692308 | [
"MIT"
] | RyusukeMatsumoto7C9-B-2/MagicLeap-SandBox | MagicLeapSandBox/Assets/SandBox/HandPointer/Scripts/IHandPointer.cs | 587 | C# |
using GaragemGestao.Data.Entities;
using GaragemGestao.Helpers;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GaragemGestao.Data
{
public class SeedDb
{
private readonly DataContext _context;
private readonly IUserHelper _userHelper;
private Random _random;
public SeedDb(DataContext context, IUserHelper userHelper)
{
_context = context;
_userHelper = userHelper;
_random = new Random();
}
public UserManager<User> UserManager { get; }
public async Task SeedAsync()
{
await _context.Database.EnsureCreatedAsync();
await _userHelper.CheckRoleAsync("Admin");
await _userHelper.CheckRoleAsync("Client");
if (!_context.Countries.Any())
{
var cities = new List<City>();
cities.Add(new City { Name = "Lisboa" });
cities.Add(new City { Name = "Porto" });
cities.Add(new City { Name = "Coimbra" });
cities.Add(new City { Name = "Faro" });
_context.Countries.Add(new Country
{
Cities = cities,
Name = "Portugal"
});
await _context.SaveChangesAsync();
}
var user = await _userHelper.GetUserByEmailAsync("andrep_developer@outlook.com");
if (user == null)
{
user = new User
{
FirstName = "Andre ",
LastName = "Pires",
Email = "andrep_developer@outlook.com",
UserName = "andrep_developer@outlook.com",
Address = "Rua XXXX",
CityId = _context.Countries.FirstOrDefault().Cities.FirstOrDefault().Id,
City = _context.Countries.FirstOrDefault().Cities.FirstOrDefault()
};
var result = await _userHelper.AddUserAsync(user, "123456");
if (result != IdentityResult.Success)
{
throw new InvalidOperationException("Could not create the user in seeder");
}
var token = await _userHelper.GenerateEmailConfirmationTokenAsync(user);
await _userHelper.ConfirmEmailAsync(user, token);
var isInRole = await _userHelper.IsUserInRoleAsync(user, "Admin");
if (!isInRole)
{
await _userHelper.AddUsertoRoleAsync(user, "Admin");
}
}
if (!_context.Vehicles.Any())
{
this.AddVehicle("Renault Megane", "DT-18-DH", "Renault", "4 Doors", "The French car", user);
this.AddVehicle("Opel Astra", "RJ-10-KF", "Opel", "4 Doors", "Not that small", user);
this.AddVehicle("Fiat 500", "F6-21-GJ", "Fiat", "2 Doors", "Small and portable", user);
this.AddVehicle("Other", "N/A", "N/A", "N/A", "N/A", user);
await _context.SaveChangesAsync();
}
}
private void AddVehicle(string name, string licensePlate, string makerName, string typeName, string details, User user)
{
_context.Vehicles.Add(new Vehicle
{
ModelName = name,
MakerName = makerName,
LicensePlate = licensePlate,
typeName = typeName,
Details = details,
RepairPrice = _random.Next(1000),
User = user
});
}
}
}
| 32.894737 | 127 | 0.522667 | [
"MIT"
] | Andresp2018/GaragemGestao | GaragemGestao/GaragemGestao/Data/SeedDb.cs | 3,752 | C# |
using System.Runtime.InteropServices;
namespace Vulkan
{
[StructLayout(LayoutKind.Sequential)]
public struct VkPhysicalDeviceFloatControlsProperties
{
public VkStructureType SType;
[NativeTypeName("void *")] public nuint PNext;
public VkShaderFloatControlsIndependence DenormBehaviorIndependence;
public VkShaderFloatControlsIndependence RoundingModeIndependence;
[NativeTypeName("Bool32")] public uint ShaderSignedZeroInfNanPreserveFloat16;
[NativeTypeName("Bool32")] public uint ShaderSignedZeroInfNanPreserveFloat32;
[NativeTypeName("Bool32")] public uint ShaderSignedZeroInfNanPreserveFloat64;
[NativeTypeName("Bool32")] public uint ShaderDenormPreserveFloat16;
[NativeTypeName("Bool32")] public uint ShaderDenormPreserveFloat32;
[NativeTypeName("Bool32")] public uint ShaderDenormPreserveFloat64;
[NativeTypeName("Bool32")] public uint ShaderDenormFlushToZeroFloat16;
[NativeTypeName("Bool32")] public uint ShaderDenormFlushToZeroFloat32;
[NativeTypeName("Bool32")] public uint ShaderDenormFlushToZeroFloat64;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRteFloat16;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRteFloat32;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRteFloat64;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRtzFloat16;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRtzFloat32;
[NativeTypeName("Bool32")] public uint ShaderRoundingModeRtzFloat64;
}
}
| 34.468085 | 85 | 0.752469 | [
"BSD-3-Clause"
] | trmcnealy/Vulkan | Vulkan/Structs/VkPhysicalDeviceFloatControlsProperties.cs | 1,620 | C# |
namespace GamePad_Intercepts.Forms
{
partial class OnScreenKeyboardForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.keyboard = new GamePad_Intercepts_Keyboard.WinForms.Keyboard();
this.SuspendLayout();
//
// keyboard
//
this.keyboard.BackColor = System.Drawing.Color.Black;
this.keyboard.Location = new System.Drawing.Point(1, 1);
this.keyboard.Margin = new System.Windows.Forms.Padding(0);
this.keyboard.MaximumSize = new System.Drawing.Size(705, 355);
this.keyboard.MinimumSize = new System.Drawing.Size(705, 355);
this.keyboard.Name = "keyboard";
this.keyboard.Padding = new System.Windows.Forms.Padding(5);
this.keyboard.Size = new System.Drawing.Size(705, 355);
this.keyboard.TabIndex = 2;
//
// OnScreenKeyboardForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(707, 357);
this.Controls.Add(this.keyboard);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OnScreenKeyboardForm";
this.Padding = new System.Windows.Forms.Padding(1);
this.Text = "OnScreenKeyboardForm";
this.TransparencyKey = System.Drawing.Color.Blue;
this.ResumeLayout(false);
}
#endregion
private GamePad_Intercepts_Keyboard.WinForms.Keyboard keyboard;
}
} | 38.382353 | 107 | 0.587356 | [
"Apache-2.0"
] | linoagli/gamepad-intercepts | gamepad-intercepts/GamePad Intercepts/Source/Forms/OnScreenKeyboardForm.Designer.cs | 2,612 | C# |
using System;
using System.ComponentModel;
using EPAS.DataEntity.Entity.Common;
namespace EPAS.DataEntity.Entity.Common
{
/// <summary>
/// Author:CodeFactory
/// Create Date:2019-03-28 09:27:59.3543
/// Description:员工能力矩阵
/// </summary>
public class EmployeeCapabilityMatrix:BaseEntity
{
public EmployeeCapabilityMatrix()
{
}
/// <summary>
/// 表名: "EmployeeCapabilityMatrix"
/// </summary>
/// <summary>
///
/// </summary>
[DisplayName("EmployeeCapabilityMatrixId")]
public String EmployeeCapabilityMatrixId
{
get ;
set ;
}
/// <summary>
///
/// </summary>
[DisplayName("TrainingBarcode")]
public String TrainingBarcode
{
get ;
set ;
}
/// <summary>
/// EmployeeNum
/// </summary>
[DisplayName("员工工号")]
public String EmployeeNum
{
get ;
set ;
}
/// <summary>
/// EmployeeName
/// </summary>
[DisplayName("员工姓名")]
public String EmployeeName
{
get ;
set ;
}
/// <summary>
///
/// </summary>
[DisplayName("MaterialNumberId")]
public String MaterialNumberId
{
get ;
set ;
}
/// <summary>
///
/// </summary>
[DisplayName("MaterialNo")]
public String MaterialNo
{
get ;
set ;
}
/// <summary>
/// MachineId
/// </summary>
[DisplayName("机械ID")]
public String MachineId
{
get ;
set ;
}
/// <summary>
///
/// </summary>
[DisplayName("Training")]
public String Training
{
get ;
set ;
}
/// <summary>
/// TrainingNum
/// </summary>
[DisplayName("员工工号")]
public String TrainingNum
{
get ;
set ;
}
/// <summary>
/// TrainingResult
/// </summary>
[DisplayName("是否培训")]
public int? TrainingResult
{
get ;
set ;
}
/// <summary>
/// TrainingPerson
/// </summary>
[DisplayName("培训员")]
public String TrainingPerson
{
get ;
set ;
}
/// <summary>
/// TrainingDate
/// </summary>
[DisplayName("培训时间")]
public DateTime? TrainingDate
{
get ;
set ;
}
/// <summary>
/// Auditor
/// </summary>
[DisplayName("培训员")]
public String Auditor
{
get ;
set ;
}
/// <summary>
/// AuditorDate
/// </summary>
[DisplayName("培训时间")]
public DateTime? AuditorDate
{
get ;
set ;
}
/// <summary>
///
/// </summary>
[DisplayName("IsAuthorized")]
public int? IsAuthorized
{
get ;
set ;
}
}
}
| 21.088608 | 52 | 0.403962 | [
"MPL-2.0"
] | whw0828/EPASServer | EPASFramework/EPAS.DataEntity/Entity/Common/EmployeeCapabilityMatrix.cs | 3,414 | C# |
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using KcpNatProxy.NetworkConnection;
namespace KcpNatProxy.Client
{
public class KnpClientAuthenticator : IKcpConnectionNegotiationContext
{
private readonly int _mtu;
private readonly byte[] _password;
private int _step;
private int _negotiatedMtu;
private uint _serverId;
private int _sessionId;
private Guid _challenge;
public uint ServerId => _serverId;
public int SessionId => _sessionId;
public KnpClientAuthenticator(int mtu, byte[] password)
{
if (mtu < 512 || mtu > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(mtu));
}
_mtu = mtu;
_password = password;
}
public int? NegotiatedMtu => _negotiatedMtu;
public KcpConnectionNegotiationResult MoveNext(Span<byte> data)
{
if (_step == -1)
{
return KcpConnectionNegotiationResult.Succeeded;
}
switch (_step)
{
case 0:
return WriteConnectRequest(data);
case 2:
return WriteChapResult(data);
}
return KcpConnectionNegotiationResult.ContinuationRequired;
}
private KcpConnectionNegotiationResult WriteConnectRequest(Span<byte> data)
{
Debug.Assert(_step == 0);
_step = 1;
BinaryPrimitives.WriteUInt32BigEndian(data, 0x4B4E5032);
data[4] = 1; // server-connect
data[5] = _password.Length != 0 ? (byte)1 : (byte)0; // 0-none 1-chap 2-session secret
BinaryPrimitives.WriteUInt16BigEndian(data.Slice(6), (ushort)_mtu);
return new KcpConnectionNegotiationResult(8);
}
private KcpConnectionNegotiationResult WriteChapResult(Span<byte> data)
{
Debug.Assert(_step == 2);
_step = 3;
RandomNumberGenerator.Fill(data.Slice(0, 16));
Span<byte> buffer = stackalloc byte[32 + _password.Length];
MemoryMarshal.Write(buffer, ref _challenge);
data.Slice(0, 16).CopyTo(buffer.Slice(16));
_password.AsSpan().CopyTo(buffer.Slice(32));
SHA256.HashData(buffer, data.Slice(16));
return new KcpConnectionNegotiationResult(48, true);
}
public void PutNegotiationData(ReadOnlySpan<byte> data)
{
if (_step < 0)
{
return;
}
switch (_step)
{
case 1:
ReadConnectionResponse(data);
return;
case 3:
_step = -1;
break;
}
_step = -2;
}
private void ReadConnectionResponse(ReadOnlySpan<byte> data)
{
Debug.Assert(_step == 1);
if (data.Length < 12 || data[0] != 2)
{
_step = -2;
return;
}
_negotiatedMtu = Math.Min(_mtu, BinaryPrimitives.ReadUInt16BigEndian(data.Slice(2)));
if (_negotiatedMtu < 512)
{
return;
}
_serverId = MemoryMarshal.Read<uint>(data.Slice(4));
_sessionId = MemoryMarshal.Read<int>(data.Slice(8));
if (data[1] == 0)
{
_step = -1;
return;
}
if (data[1] != 1)
{
_step = -2;
return;
}
if (data.Length < 28)
{
_step = -2;
return;
}
_challenge = MemoryMarshal.Read<Guid>(data.Slice(12));
_step = 2;
}
}
}
| 28.791367 | 98 | 0.511244 | [
"MIT"
] | ShiftyTR/KcpNatProxy | src/KcpNatProxy/Client/KnpClientAuthenticator.cs | 4,004 | 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.Sysdig.Secure.Outputs
{
[OutputType]
public sealed class RuleNetworkTcp
{
/// <summary>
/// Defines if the port matches or not with the provided list. Default is true.
/// </summary>
public readonly bool? Matching;
/// <summary>
/// List of ports to match.
/// </summary>
public readonly ImmutableArray<int> Ports;
[OutputConstructor]
private RuleNetworkTcp(
bool? matching,
ImmutableArray<int> ports)
{
Matching = matching;
Ports = ports;
}
}
}
| 26.138889 | 88 | 0.61424 | [
"ECL-2.0",
"Apache-2.0"
] | Sysdig-Hackathon-Picasso/pulumi-sysdig | sdk/dotnet/Secure/Outputs/RuleNetworkTcp.cs | 941 | C# |
using Stankins.Interfaces;
using System.Diagnostics;
namespace StankinsObjects
{
[DebuggerDisplay("{Name} {Id}")]
public class Table: MetadataRow, ITable
{
}
}
| 15 | 43 | 0.683333 | [
"MIT"
] | Zeroshi/stankins | stankinsv2/solution/StankinsV2/StankinsObjects/Table.cs | 182 | C# |
using System;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Mantle.Identity.Domain;
using Mantle.Identity.Models.ManageViewModels;
using Mantle.Identity.Services;
using Mantle.Web.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Mantle.Identity
{
[Authorize]
public abstract class MantleManageController<TUser> : Controller
where TUser : MantleIdentityUser, new()
{
private readonly UserManager<TUser> userManager;
private readonly SignInManager<TUser> signInManager;
private readonly IEmailSender emailSender;
private readonly ILogger logger;
private readonly UrlEncoder urlEncoder;
private readonly SiteSettings siteSettings;
private const string AuthenicatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
public MantleManageController(
UserManager<TUser> userManager,
SignInManager<TUser> signInManager,
IEmailSender emailSender,
ILogger<MantleManageController<TUser>> logger,
UrlEncoder urlEncoder,
SiteSettings siteSettings)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.emailSender = emailSender;
this.logger = logger;
this.urlEncoder = urlEncoder;
this.siteSettings = siteSettings;
}
[TempData]
public string StatusMessage { get; set; }
[HttpGet]
public virtual async Task<IActionResult> Index()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var model = new IndexViewModel
{
Username = user.UserName,
Email = user.Email,
PhoneNumber = user.PhoneNumber,
IsEmailConfirmed = user.EmailConfirmed,
StatusMessage = StatusMessage
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> Index(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var email = user.Email;
if (model.Email != email)
{
var setEmailResult = await userManager.SetEmailAsync(user, model.Email);
if (!setEmailResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
}
}
var phoneNumber = user.PhoneNumber;
if (model.PhoneNumber != phoneNumber)
{
var setPhoneResult = await userManager.SetPhoneNumberAsync(user, model.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
}
}
StatusMessage = "Your profile has been updated";
return RedirectToAction(nameof(Index));
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> SendVerificationEmail(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink<TUser>(user.Id, code, Request.Scheme);
var email = user.Email;
await emailSender.SendEmailConfirmationAsync(email, callbackUrl);
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToAction(nameof(Index));
}
[HttpGet]
public virtual async Task<IActionResult> ChangePassword()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var hasPassword = await userManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToAction(nameof(SetPassword));
}
var model = new ChangePasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var changePasswordResult = await userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (!changePasswordResult.Succeeded)
{
AddErrors(changePasswordResult);
return View(model);
}
await signInManager.SignInAsync(user, isPersistent: false);
logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToAction(nameof(ChangePassword));
}
[HttpGet]
public virtual async Task<IActionResult> SetPassword()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var hasPassword = await userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToAction(nameof(ChangePassword));
}
var model = new SetPasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var addPasswordResult = await userManager.AddPasswordAsync(user, model.NewPassword);
if (!addPasswordResult.Succeeded)
{
AddErrors(addPasswordResult);
return View(model);
}
await signInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "Your password has been set.";
return RedirectToAction(nameof(SetPassword));
}
[HttpGet]
public virtual async Task<IActionResult> ExternalLogins()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var model = new ExternalLoginsViewModel { CurrentLogins = await userManager.GetLoginsAsync(user) };
model.OtherLogins = (await signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
model.ShowRemoveButton = await userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;
model.StatusMessage = StatusMessage;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> LinkLogin(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action(nameof(LinkLoginCallback));
var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
[HttpGet]
public virtual async Task<IActionResult> LinkLoginCallback()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var info = await signInManager.GetExternalLoginInfoAsync(user.Id);
if (info == null)
{
throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
}
var result = await userManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = "The external login was added.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model)
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var result = await userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{user.Id}'.");
}
await signInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "The external login was removed.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpGet]
public virtual async Task<IActionResult> TwoFactorAuthentication()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var model = new TwoFactorAuthenticationViewModel
{
HasAuthenticator = await userManager.GetAuthenticatorKeyAsync(user) != null,
Is2faEnabled = user.TwoFactorEnabled,
RecoveryCodesLeft = await userManager.CountRecoveryCodesAsync(user),
};
return View(model);
}
[HttpGet]
public virtual async Task<IActionResult> Disable2faWarning()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
return View(nameof(Disable2fa));
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> Disable2fa()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var disable2faResult = await userManager.SetTwoFactorEnabledAsync(user, false);
if (!disable2faResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id);
return RedirectToAction(nameof(TwoFactorAuthentication));
}
[HttpGet]
public virtual async Task<IActionResult> EnableAuthenticator()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
var unformattedKey = await userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await userManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await userManager.GetAuthenticatorKeyAsync(user);
}
var model = new EnableAuthenticatorViewModel
{
SharedKey = FormatKey(unformattedKey),
AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey)
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
// Strip spaces and hypens
var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
var is2faTokenValid = await userManager.VerifyTwoFactorTokenAsync(
user, userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
if (!is2faTokenValid)
{
ModelState.AddModelError("model.Code", "Verification code is invalid.");
return View(model);
}
await userManager.SetTwoFactorEnabledAsync(user, true);
logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
return RedirectToAction(nameof(GenerateRecoveryCodes));
}
[HttpGet]
public virtual IActionResult ResetAuthenticatorWarning()
{
return View(nameof(ResetAuthenticator));
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> ResetAuthenticator()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
await userManager.SetTwoFactorEnabledAsync(user, false);
await userManager.ResetAuthenticatorKeyAsync(user);
logger.LogInformation("User with id '{UserId}' has reset their authentication app key.", user.Id);
return RedirectToAction(nameof(EnableAuthenticator));
}
[HttpGet]
public virtual async Task<IActionResult> GenerateRecoveryCodes()
{
var user = await userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
}
var recoveryCodes = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
var model = new GenerateRecoveryCodesViewModel { RecoveryCodes = recoveryCodes.ToArray() };
logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id);
return View(model);
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private string FormatKey(string unformattedKey)
{
var result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition));
}
return result.ToString().ToLowerInvariant();
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
return string.Format(
AuthenicatorUriFormat,
urlEncoder.Encode(siteSettings.SiteName),
urlEncoder.Encode(email),
unformattedKey);
}
#endregion Helpers
}
} | 37.142012 | 144 | 0.58871 | [
"MIT"
] | gordon-matt/MantleCMS | Mantle.Identity/MantleManageController.cs | 18,833 | C# |
using System.Collections.Generic;
namespace Catalog.Contracts
{
public class GetCatalogItemsQuery
{
public int Skip { get; set; }
public int Limit { get; set; } = 10;
public bool IncludeCharges { get; set; } = true;
public bool IncludeCustomFields { get; set; } = true;
}
public class GetCatalogItemsQueryResponse
{
public IEnumerable<CatalogItemDto> Items { get; set; } = null!;
public int Total { get; set; }
}
public class GetCatalogItemByIdQuery
{
public string Id { get; set; } = null!;
public bool IncludeCharges { get; set; } = true;
}
public class GetCatalogItemsByIdQuery
{
public IEnumerable<string> Ids { get; set; } = null!;
}
public class GetCatalogItemsByIdQueryResponse
{
public IEnumerable<CatalogItemDto> Items { get; set; } = null!;
}
} | 24.179487 | 72 | 0.589608 | [
"MIT"
] | marinasundstrom/PointOfSale | Catalog/Catalog.Contracts/Queries.cs | 945 | 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 appmesh-2019-01-25.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.AppMesh.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AppMesh.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListenerTimeout Object
/// </summary>
public class ListenerTimeoutUnmarshaller : IUnmarshaller<ListenerTimeout, XmlUnmarshallerContext>, IUnmarshaller<ListenerTimeout, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ListenerTimeout IUnmarshaller<ListenerTimeout, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ListenerTimeout Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ListenerTimeout unmarshalledObject = new ListenerTimeout();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("grpc", targetDepth))
{
var unmarshaller = GrpcTimeoutUnmarshaller.Instance;
unmarshalledObject.Grpc = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("http", targetDepth))
{
var unmarshaller = HttpTimeoutUnmarshaller.Instance;
unmarshalledObject.Http = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("http2", targetDepth))
{
var unmarshaller = HttpTimeoutUnmarshaller.Instance;
unmarshalledObject.Http2 = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tcp", targetDepth))
{
var unmarshaller = TcpTimeoutUnmarshaller.Instance;
unmarshalledObject.Tcp = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ListenerTimeoutUnmarshaller _instance = new ListenerTimeoutUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListenerTimeoutUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.709091 | 159 | 0.594106 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AppMesh/Generated/Model/Internal/MarshallTransformations/ListenerTimeoutUnmarshaller.cs | 4,038 | C# |
using CloudMusic.Models.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CloudMusic.CustomForms
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PlayListViewCell : ViewCell
{
public PlayListViewCell()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
// you can also put cachedImage.Source = null; here to prevent showing old images occasionally
image.Source = null;
var item = BindingContext as Playlist;
if (item == null)
{
return;
}
image.Source = item.coverImgUrl;
base.OnBindingContextChanged();
}
}
} | 24.555556 | 106 | 0.622172 | [
"MIT"
] | 851265601/Xamarin-CloudMusic | CloudMusic/CustomForms/PlayListViewCell.xaml.cs | 886 | C# |
using System;
using System.ComponentModel;
namespace osfDesigner
{
// Один из вариантов показать в сетке свойств расширяемое свойство.
// Так можно вывести русские названия свойств. Тип раскрываемого свойства должен соответствовать унаследованному классу, если
// их нужно будет редактировать тут же в раскытом списке. На расскытые свойства возможно нужно будет повесить свой редактор.
// Вызывается в конвертере примерно так:
////public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
////{
//// //MySelectionRange MySelectionRange1 = new MySelectionRange((SelectionRange)value);
//// //PropertyDescriptorCollection originalCollection = TypeDescriptor.GetProperties(MySelectionRange1, attributes);
//// //PropertyDescriptorCollection originalCollection = TypeDescriptor.GetProperties(value, attributes);
//// PropertyDescriptorCollection originalCollection = TypeDescriptor.GetProperties(typeof(MySelectionRange), attributes);
//// PropertyDescriptor[] pds = new PropertyDescriptor[originalCollection.Count];
//// originalCollection.CopyTo(pds, 0);
//// PropertyDescriptorCollection newCollection = new PropertyDescriptorCollection(pds);
//// for (int i = 0; i < originalCollection.Count; i++)
//// {
//// PropertyDescriptor pd = originalCollection[i];
//// List<Attribute> la = new List<Attribute>();
//// foreach (Attribute attribute in pd.Attributes)
//// {
//// la.Add(attribute);
//// }
//// MyPropertyDescriptor cp = new MyPropertyDescriptor(pd, la.ToArray());
//// newCollection.RemoveAt(i);
//// newCollection.Insert(i, cp);
//// }
//// return newCollection;
////}
public class MyPropertyDescriptor : PropertyDescriptor
{
private PropertyDescriptor _innerPropertyDescriptor;
private bool _ronly;
public MyPropertyDescriptor(PropertyDescriptor inner, Attribute[] attrs) : base(GetDisplayName(inner), attrs)
{
_innerPropertyDescriptor = inner;
_ronly = inner.IsReadOnly;
}
public static string GetDisplayName(PropertyDescriptor inner)
{
if (inner.Name == "Start")
{
return "Начало";
}
else if (inner.Name == "End")
{
return "Конец";
}
else if (inner.Name == "Width")
{
return "Ширина";
}
else if (inner.Name == "Height")
{
return "Высота";
}
else if (inner.Name == "X")
{
return "Икс";
}
else if (inner.Name == "Y")
{
return "Игрек";
}
else
{
return inner.Name;
}
}
public override object GetValue(object component)
{
return _innerPropertyDescriptor.GetValue(component);
}
public override bool SupportsChangeEvents
{
get { return true; }
}
public override Type PropertyType
{
get { return _innerPropertyDescriptor.PropertyType; }
}
public override void ResetValue(object component)
{
// Не имеет значения.
}
public override void SetValue(object component, object value)
{
_innerPropertyDescriptor = (MyPropertyDescriptor)value;
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get { return _innerPropertyDescriptor.PropertyType; }
}
public override bool IsReadOnly
{
get
{
return true;
}
}
}
}
| 32.546875 | 136 | 0.573452 | [
"MPL-2.0"
] | Nivanchenko/OneScriptFormsDesigner | OneScriptFormsDesigner/OneScriptFormsDesigner/MyPropertyDescriptor.cs | 4,510 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StorageEngine.Interfaces
{
interface IProduceable
{
void ProduceEnergy(int rpm);
}
}
| 16.642857 | 36 | 0.733906 | [
"MIT"
] | stanislavstoyanov99/Storage-Engine-App | StorageEngine/StorageEngine/Interfaces/IProduceable.cs | 235 | C# |
namespace Exception_handling
{
using System;
public class SimpleMathExam : Exam
{
private const int MinProblemsCount = 0;
private const int MaxProblemsCount = 10;
private const string BadResultsComment = "Bad result: nothing done.";
private const string AverageResultsComment = "Average result: almost nothing done.";
private const string GoodResultsComment = "Good result: almost everything's done correctly.";
private const string ExcelentResultsComment = "Excellent result: everything's done correctly.";
private const int BadGradeMaxProblems = 2;
private const int AverageGradeMaxProblems = 5;
private const int GoodGradeMaxProblems = 8;
private int problemsSolved;
public SimpleMathExam(int problemsSolved)
{
this.ProblemsSolved = problemsSolved;
}
public int ProblemsSolved
{
get
{
return this.problemsSolved;
}
private set
{
if (value < MinProblemsCount)
{
this.problemsSolved = MinProblemsCount;
}
else if (value > MaxProblemsCount)
{
this.problemsSolved = MaxProblemsCount;
}
else
{
this.problemsSolved = value;
}
}
}
public override ExamResult Check()
{
string comment;
if (this.ProblemsSolved <= BadGradeMaxProblems)
{
comment = BadResultsComment;
}
else if (this.ProblemsSolved <= AverageGradeMaxProblems)
{
comment = AverageResultsComment;
}
else if (this.ProblemsSolved <= GoodGradeMaxProblems)
{
comment = GoodResultsComment;
}
else
{
comment = ExcelentResultsComment;
}
return new ExamResult(this.ProblemsSolved, MinProblemsCount, MaxProblemsCount, comment);
}
}
}
| 30.597222 | 103 | 0.534271 | [
"MIT"
] | GeorgiPetrovGH/TelerikAcademy | 08.High-Quality-Code/Defensive Programming and Exceptions/Assertions_Exceptions/Exception_handling/SimpleMathExam.cs | 2,205 | 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.Latest
{
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-nextgen:network:getVirtualNetworkGatewayVpnclientIpsecParameters'.")]
public static class GetVirtualNetworkGatewayVpnclientIpsecParameters
{
/// <summary>
/// An IPSec parameters for a virtual network gateway P2S connection.
/// Latest API Version: 2020-08-01.
/// </summary>
public static Task<GetVirtualNetworkGatewayVpnclientIpsecParametersResult> InvokeAsync(GetVirtualNetworkGatewayVpnclientIpsecParametersArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetVirtualNetworkGatewayVpnclientIpsecParametersResult>("azure-nextgen:network/latest:getVirtualNetworkGatewayVpnclientIpsecParameters", args ?? new GetVirtualNetworkGatewayVpnclientIpsecParametersArgs(), options.WithVersion());
}
public sealed class GetVirtualNetworkGatewayVpnclientIpsecParametersArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The virtual network gateway name.
/// </summary>
[Input("virtualNetworkGatewayName", required: true)]
public string VirtualNetworkGatewayName { get; set; } = null!;
public GetVirtualNetworkGatewayVpnclientIpsecParametersArgs()
{
}
}
[OutputType]
public sealed class GetVirtualNetworkGatewayVpnclientIpsecParametersResult
{
/// <summary>
/// The DH Group used in IKE Phase 1 for initial SA.
/// </summary>
public readonly string DhGroup;
/// <summary>
/// The IKE encryption algorithm (IKE phase 2).
/// </summary>
public readonly string IkeEncryption;
/// <summary>
/// The IKE integrity algorithm (IKE phase 2).
/// </summary>
public readonly string IkeIntegrity;
/// <summary>
/// The IPSec encryption algorithm (IKE phase 1).
/// </summary>
public readonly string IpsecEncryption;
/// <summary>
/// The IPSec integrity algorithm (IKE phase 1).
/// </summary>
public readonly string IpsecIntegrity;
/// <summary>
/// The Pfs Group used in IKE Phase 2 for new child SA.
/// </summary>
public readonly string PfsGroup;
/// <summary>
/// The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for P2S client..
/// </summary>
public readonly int SaDataSizeKilobytes;
/// <summary>
/// The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for P2S client.
/// </summary>
public readonly int SaLifeTimeSeconds;
[OutputConstructor]
private GetVirtualNetworkGatewayVpnclientIpsecParametersResult(
string dhGroup,
string ikeEncryption,
string ikeIntegrity,
string ipsecEncryption,
string ipsecIntegrity,
string pfsGroup,
int saDataSizeKilobytes,
int saLifeTimeSeconds)
{
DhGroup = dhGroup;
IkeEncryption = ikeEncryption;
IkeIntegrity = ikeIntegrity;
IpsecEncryption = ipsecEncryption;
IpsecIntegrity = ipsecIntegrity;
PfsGroup = pfsGroup;
SaDataSizeKilobytes = saDataSizeKilobytes;
SaLifeTimeSeconds = saLifeTimeSeconds;
}
}
}
| 37.110092 | 282 | 0.649197 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/Latest/GetVirtualNetworkGatewayVpnclientIpsecParameters.cs | 4,045 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageDealerManage : MonoBehaviour
{
[SerializeField] public int damage = 100;
public int GetDamage()
{
return damage;
}
public void Hit()
{
Destroy(gameObject);
}
}
| 16.105263 | 47 | 0.656863 | [
"Apache-2.0"
] | artem-goncharov/ag-oforcsandmagic | Assets/Scripts/DamageDealerManage.cs | 308 | C# |
using UnityEngine;
using System.Collections;
public class NormalShot : EnemyShot {
[SerializeField] private float speed = 2f; // The speed at which I travel.
private Vector3 direction; // The direction in which I travel.
new void Start ()
{
base.Start();
// Get the direction towards the player.
Vector3 targetPosition = GameObject.FindGameObjectWithTag("Player").transform.position;
targetPosition = new Vector3(targetPosition.x, transform.position.y, targetPosition.z);
direction = targetPosition - transform.position;
direction.Normalize();
}
new void Update ()
{
base.Update();
// Move in my precalculated direction.
transform.position = transform.position + direction * speed * Time.deltaTime;
}
}
| 26.833333 | 95 | 0.674534 | [
"MIT"
] | denniscarr/dfc291_CodeLab1_final | Static/Assets/Prefabs/Enemy Shot/Normal Shot/NormalShot.cs | 807 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeCommit.Model
{
/// <summary>
/// USE_NEW_CONTENT was specified, but no replacement content has been provided.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class ReplacementContentRequiredException : AmazonCodeCommitException
{
/// <summary>
/// Constructs a new ReplacementContentRequiredException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ReplacementContentRequiredException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ReplacementContentRequiredException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ReplacementContentRequiredException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ReplacementContentRequiredException
/// </summary>
/// <param name="innerException"></param>
public ReplacementContentRequiredException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ReplacementContentRequiredException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReplacementContentRequiredException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ReplacementContentRequiredException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReplacementContentRequiredException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ReplacementContentRequiredException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ReplacementContentRequiredException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 48.483871 | 178 | 0.688789 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/ReplacementContentRequiredException.cs | 6,012 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701
{
using static Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Extensions;
/// <summary>Update VM resource collection.</summary>
public partial class VMCollectionUpdate :
Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701.IVMCollectionUpdate,
Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701.IVMCollectionUpdateInternal
{
/// <summary>Backing field for <see cref="OperationName" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Elastic.Support.OperationName? _operationName;
/// <summary>Operation to be performed for given VM.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Elastic.Origin(Microsoft.Azure.PowerShell.Cmdlets.Elastic.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Elastic.Support.OperationName? OperationName { get => this._operationName; set => this._operationName = value; }
/// <summary>Backing field for <see cref="VMResourceId" /> property.</summary>
private string _vMResourceId;
/// <summary>ARM id of the VM resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Elastic.Origin(Microsoft.Azure.PowerShell.Cmdlets.Elastic.PropertyOrigin.Owned)]
public string VMResourceId { get => this._vMResourceId; set => this._vMResourceId = value; }
/// <summary>Creates an new <see cref="VMCollectionUpdate" /> instance.</summary>
public VMCollectionUpdate()
{
}
}
/// Update VM resource collection.
public partial interface IVMCollectionUpdate :
Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.IJsonSerializable
{
/// <summary>Operation to be performed for given VM.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Operation to be performed for given VM.",
SerializedName = @"operationName",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Elastic.Support.OperationName) })]
Microsoft.Azure.PowerShell.Cmdlets.Elastic.Support.OperationName? OperationName { get; set; }
/// <summary>ARM id of the VM resource.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"ARM id of the VM resource.",
SerializedName = @"vmResourceId",
PossibleTypes = new [] { typeof(string) })]
string VMResourceId { get; set; }
}
/// Update VM resource collection.
internal partial interface IVMCollectionUpdateInternal
{
/// <summary>Operation to be performed for given VM.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Elastic.Support.OperationName? OperationName { get; set; }
/// <summary>ARM id of the VM resource.</summary>
string VMResourceId { get; set; }
}
} | 49.661765 | 163 | 0.689073 | [
"MIT"
] | Agazoth/azure-powershell | src/Elastic/generated/api/Models/Api20200701/VMCollectionUpdate.cs | 3,310 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
#pragma warning disable CS8618
[JsiiByValue(fqn: "aws.S3BucketReplicationConfiguration")]
public class S3BucketReplicationConfiguration : aws.IS3BucketReplicationConfiguration
{
[JsiiProperty(name: "role", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string Role
{
get;
set;
}
/// <summary>rules block.</summary>
[JsiiProperty(name: "rules", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.S3BucketReplicationConfigurationRules\"},\"kind\":\"array\"}}", isOverride: true)]
public aws.IS3BucketReplicationConfigurationRules[] Rules
{
get;
set;
}
}
}
| 29.285714 | 178 | 0.620732 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/S3BucketReplicationConfiguration.cs | 820 | C# |
using ExtCore.Data.Entities.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
namespace EduxSoft.Base.Data.Entities
{
public class SectionInfo :IEntity
{
public SectionInfo()
{
Classes = new HashSet<ClassInfo>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public bool IsPrimary { get; set; }
public bool IsSecondary { get; set; }
public DateTime Created { get; set; }
public ICollection<ClassInfo> Classes { get; set; }
}
}
| 26.826087 | 59 | 0.612642 | [
"MIT"
] | cedriclange/EduxSoft | EduxSoft.Base.Data.Entities/SectionInfo.cs | 619 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Chinook.Domain.Converters;
using Chinook.Domain.Entities;
using Newtonsoft.Json;
namespace Chinook.Domain.ApiModels
{
public class ArtistApiModel : IConvertModel<ArtistApiModel, Artist>
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ArtistId { get; set; }
public string Name { get; set; }
[NotMapped]
[JsonIgnore]
public IList<AlbumApiModel> Albums { get; set; }
public Artist Convert() => new Artist
{
ArtistId = ArtistId,
Name = Name
};
}
} | 25.655172 | 71 | 0.657258 | [
"MIT"
] | cwoodruff/ChinookASPNETCoreAPINTier | ChinookASPNETCoreAPINTier/Chinook.Domain/ApiModels/ArtistApiModel.cs | 746 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;
namespace MassTransit.JiraServicedeskConnector
{
sealed class PrefixContractResolver : DefaultContractResolver
{
readonly DefaultContractResolver _contractResolver;
public PrefixContractResolver(DefaultContractResolver contractResolver) => _contractResolver = contractResolver;
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var jsonProperty = base.CreateProperty(member, memberSerialization);
var prefixAttribute = member.GetCustomAttribute<PrefixAttribute>();
if(prefixAttribute != null)
jsonProperty.PropertyName = $"{prefixAttribute.Prefix}{jsonProperty.PropertyName}";
return jsonProperty;
}
protected override string ResolvePropertyName(string propertyName) => _contractResolver.GetResolvedPropertyName(propertyName);
}
}
| 35.964286 | 134 | 0.746773 | [
"Apache-2.0"
] | ushenkodmitry/MassTransitContrib | src/JIRA-SERVICEDESK-CONNECTOR/MassTransit.JiraServicedeskConnector/JiraServicedeskConnector/PrefixContractResolver.cs | 1,009 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.