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.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Access device end point that can have multiple contacts.
/// Port numbers are only used by devices with static line ordering.
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""c0d21ef9ba207c335d8347e5172fce1d:218""}]")]
public class AccessDeviceMultipleContactEndpointRead20
{
private BroadWorksConnector.Ocip.Models.AccessDevice _accessDevice;
[XmlElement(ElementName = "accessDevice", IsNullable = false, Namespace = "")]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
public BroadWorksConnector.Ocip.Models.AccessDevice AccessDevice
{
get => _accessDevice;
set
{
AccessDeviceSpecified = true;
_accessDevice = value;
}
}
[XmlIgnore]
protected bool AccessDeviceSpecified { get; set; }
private string _linePort;
[XmlElement(ElementName = "linePort", IsNullable = false, Namespace = "")]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
[MinLength(1)]
[MaxLength(161)]
public string LinePort
{
get => _linePort;
set
{
LinePortSpecified = true;
_linePort = value;
}
}
[XmlIgnore]
protected bool LinePortSpecified { get; set; }
private List<string> _contact = new List<string>();
[XmlElement(ElementName = "contact", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
[MinLength(1)]
[MaxLength(1020)]
public List<string> Contact
{
get => _contact;
set
{
ContactSpecified = true;
_contact = value;
}
}
[XmlIgnore]
protected bool ContactSpecified { get; set; }
private bool _staticRegistrationCapable;
[XmlElement(ElementName = "staticRegistrationCapable", IsNullable = false, Namespace = "")]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
public bool StaticRegistrationCapable
{
get => _staticRegistrationCapable;
set
{
StaticRegistrationCapableSpecified = true;
_staticRegistrationCapable = value;
}
}
[XmlIgnore]
protected bool StaticRegistrationCapableSpecified { get; set; }
private bool _useDomain;
[XmlElement(ElementName = "useDomain", IsNullable = false, Namespace = "")]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
public bool UseDomain
{
get => _useDomain;
set
{
UseDomainSpecified = true;
_useDomain = value;
}
}
[XmlIgnore]
protected bool UseDomainSpecified { get; set; }
private int _portNumber;
[XmlElement(ElementName = "portNumber", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
[MinInclusive(1)]
[MaxInclusive(1024)]
public int PortNumber
{
get => _portNumber;
set
{
PortNumberSpecified = true;
_portNumber = value;
}
}
[XmlIgnore]
protected bool PortNumberSpecified { get; set; }
private bool _supportVisualDeviceManagement;
[XmlElement(ElementName = "supportVisualDeviceManagement", IsNullable = false, Namespace = "")]
[Group(@"c0d21ef9ba207c335d8347e5172fce1d:218")]
public bool SupportVisualDeviceManagement
{
get => _supportVisualDeviceManagement;
set
{
SupportVisualDeviceManagementSpecified = true;
_supportVisualDeviceManagement = value;
}
}
[XmlIgnore]
protected bool SupportVisualDeviceManagementSpecified { get; set; }
}
}
| 29.590604 | 129 | 0.577909 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/AccessDeviceMultipleContactEndpointRead20.cs | 4,409 | C# |
namespace UnityEngine.U2D
{
/// <summary>
/// The Pixel Perfect Camera component ensures your pixel art remains crisp and clear at different resolutions, and stable in motion.
/// </summary>
[DisallowMultipleComponent]
[AddComponentMenu("Rendering/Pixel Perfect Camera")]
[RequireComponent(typeof(Camera))]
public class PixelPerfectCamera : MonoBehaviour, IPixelPerfectCamera
{
/// <summary>
/// Match this value to to the Pixels Per Unit values of all Sprites within the Scene.
/// </summary>
public int assetsPPU { get { return m_AssetsPPU; } set { m_AssetsPPU = value > 0 ? value : 1; } }
/// <summary>
/// The original horizontal resolution your Assets are designed for.
/// </summary>
public int refResolutionX { get { return m_RefResolutionX; } set { m_RefResolutionX = value > 0 ? value : 1; } }
/// <summary>
/// Original vertical resolution your Assets are designed for.
/// </summary>
public int refResolutionY { get { return m_RefResolutionY; } set { m_RefResolutionY = value > 0 ? value : 1; } }
/// <summary>
/// Set to true to have the Scene rendered to a temporary texture set as close as possible to the Reference Resolution,
/// while maintaining the full screen aspect ratio. This temporary texture is then upscaled to fit the full screen.
/// </summary>
public bool upscaleRT { get { return m_UpscaleRT; } set { m_UpscaleRT = value; } }
/// <summary>
/// Set to true to prevent subpixel movement and make Sprites appear to move in pixel-by-pixel increments.
/// Only applicable when upscaleRT is false.
/// </summary>
public bool pixelSnapping { get { return m_PixelSnapping; } set { m_PixelSnapping = value; } }
/// <summary>
/// Set to true to crop the viewport with black bars to match refResolutionX in the horizontal direction.
/// </summary>
public bool cropFrameX { get { return m_CropFrameX; } set { m_CropFrameX = value; } }
/// <summary>
/// Set to true to crop the viewport with black bars to match refResolutionY in the vertical direction.
/// </summary>
public bool cropFrameY { get { return m_CropFrameY; } set { m_CropFrameY = value; } }
/// <summary>
/// Set to true to expand the viewport to fit the screen resolution while maintaining the viewport's aspect ratio.
/// Only applicable when both cropFrameX and cropFrameY are true.
/// </summary>
public bool stretchFill { get { return m_StretchFill; } set { m_StretchFill = value; } }
/// <summary>
/// Ratio of the rendered Sprites compared to their original size (readonly).
/// </summary>
public int pixelRatio { get { return m_Internal.zoom; } }
/// <summary>
/// Round a arbitrary position to an integer pixel position. Works in world space.
/// </summary>
/// <param name="position"> The position you want to round.</param>
/// <returns>
/// The rounded pixel position.
/// Depending on the values of upscaleRT and pixelSnapping, it could be a screen pixel position or an art pixel position.
/// </returns>
public Vector3 RoundToPixel(Vector3 position)
{
float unitsPerPixel = m_Internal.unitsPerPixel;
if (unitsPerPixel == 0.0f)
return position;
Vector3 result;
result.x = Mathf.Round(position.x / unitsPerPixel) * unitsPerPixel;
result.y = Mathf.Round(position.y / unitsPerPixel) * unitsPerPixel;
result.z = Mathf.Round(position.z / unitsPerPixel) * unitsPerPixel;
return result;
}
[SerializeField]
private int m_AssetsPPU = 100;
[SerializeField]
private int m_RefResolutionX = 320;
[SerializeField]
private int m_RefResolutionY = 180;
[SerializeField]
private bool m_UpscaleRT = false;
[SerializeField]
private bool m_PixelSnapping = false;
[SerializeField]
private bool m_CropFrameX = false;
[SerializeField]
private bool m_CropFrameY = false;
[SerializeField]
private bool m_StretchFill = false;
private Camera m_Camera;
private PixelPerfectCameraInternal m_Internal;
// Snap camera position to pixels using Camera.worldToCameraMatrix.
private void PixelSnap()
{
Vector3 cameraPosition = m_Camera.transform.position;
Vector3 roundedCameraPosition = RoundToPixel(cameraPosition);
Vector3 offset = roundedCameraPosition - cameraPosition;
offset.z = -offset.z;
Matrix4x4 offsetMatrix = Matrix4x4.TRS(-offset, Quaternion.identity, new Vector3(1.0f, 1.0f, -1.0f));
m_Camera.worldToCameraMatrix = offsetMatrix * m_Camera.transform.worldToLocalMatrix;
}
private void Awake()
{
m_Camera = GetComponent<Camera>();
m_Internal = new PixelPerfectCameraInternal(this);
m_Internal.originalOrthoSize = m_Camera.orthographicSize;
m_Internal.hasPostProcessLayer = GetComponent("PostProcessLayer") != null; // query the component by name to avoid hard dependency
if (m_Camera.targetTexture != null)
Debug.LogWarning("Render to texture is not supported by Pixel Perfect Camera.", m_Camera);
}
private void LateUpdate()
{
m_Internal.CalculateCameraProperties(Screen.width, Screen.height);
// To be effective immediately this frame, forceIntoRenderTexture should be set before any camera rendering callback.
// An exception of this is when the editor is paused, where we call LateUpdate() manually in OnPreCall().
// In this special case, you'll see one frame of glitch when toggling renderUpscaling on and off.
m_Camera.forceIntoRenderTexture = m_Internal.hasPostProcessLayer || m_Internal.useOffscreenRT;
}
private void OnPreCull()
{
#if UNITY_EDITOR
// LateUpdate() is not called while the editor is paused, but OnPreCull() is.
// So call LateUpdate() manually here.
if (UnityEditor.EditorApplication.isPaused)
LateUpdate();
#endif
PixelSnap();
if (m_Internal.pixelRect != Rect.zero)
m_Camera.pixelRect = m_Internal.pixelRect;
else
m_Camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
m_Camera.orthographicSize = m_Internal.orthoSize;
}
private void OnPreRender()
{
// Clear the screen to black so that we can see black bars.
// Need to do it before anything is drawn if we're rendering directly to the screen.
if (m_Internal.cropFrameXOrY && !m_Camera.forceIntoRenderTexture && !m_Camera.allowMSAA)
GL.Clear(false, true, Color.black);
Experimental.U2D.PixelPerfectRendering.pixelSnapSpacing = m_Internal.unitsPerPixel;
}
private void OnPostRender()
{
Experimental.U2D.PixelPerfectRendering.pixelSnapSpacing = 0.0f;
// Clear the screen to black so that we can see black bars.
// If a temporary offscreen RT is used, we do the clear after we're done with that RT to avoid an unnecessary RT switch.
if (m_Camera.activeTexture != null)
{
Graphics.SetRenderTarget(null as RenderTexture);
GL.Viewport(new Rect(0.0f, 0.0f, Screen.width, Screen.height));
GL.Clear(false, true, Color.black);
}
if (!m_Internal.useOffscreenRT)
return;
RenderTexture activeRT = m_Camera.activeTexture;
if (activeRT != null)
activeRT.filterMode = m_Internal.useStretchFill ? FilterMode.Bilinear : FilterMode.Point;
m_Camera.pixelRect = m_Internal.CalculatePostRenderPixelRect(m_Camera.aspect, Screen.width, Screen.height);
}
#if UNITY_EDITOR
private void OnEnable()
{
if (!UnityEditor.EditorApplication.isPlaying)
UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeChanged;
}
#endif
public void OnDisable()
{
m_Camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
m_Camera.orthographicSize = m_Internal.originalOrthoSize;
m_Camera.forceIntoRenderTexture = m_Internal.hasPostProcessLayer;
m_Camera.ResetAspect();
m_Camera.ResetWorldToCameraMatrix();
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying)
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged;
#endif
}
// Show on-screen warning about invalid render resolutions.
private void OnGUI()
{
if (!Debug.isDebugBuild && !Application.isEditor)
return;
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying && !runInEditMode)
return;
#endif
Color oldColor = GUI.color;
GUI.color = Color.red;
Vector2Int renderResolution = Vector2Int.zero;
renderResolution.x = m_Internal.useOffscreenRT ? m_Internal.offscreenRTWidth : m_Camera.pixelWidth;
renderResolution.y = m_Internal.useOffscreenRT ? m_Internal.offscreenRTHeight : m_Camera.pixelHeight;
if (renderResolution.x % 2 != 0 || renderResolution.y % 2 != 0)
{
string warning = string.Format("Rendering at an odd-numbered resolution ({0} * {1}). Pixel Perfect Camera may not work properly in this situation.", renderResolution.x, renderResolution.y);
GUILayout.Box(warning);
}
if (Screen.width < refResolutionX || Screen.height < refResolutionY)
{
GUILayout.Box("Screen resolution is smaller than the reference resolution. Image may appear stretched or cropped.");
}
GUI.color = oldColor;
}
#if UNITY_EDITOR
private void OnPlayModeChanged(UnityEditor.PlayModeStateChange state)
{
// Stop running in edit mode when entering play mode.
if (state == UnityEditor.PlayModeStateChange.ExitingEditMode)
{
runInEditMode = false;
OnDisable();
}
}
#endif
}
}
| 40.908046 | 205 | 0.624333 | [
"BSD-2-Clause"
] | KrauseKurt/LD44 | Library/PackageCache/com.unity.2d.pixel-perfect@1.0.1-preview/Runtime/PixelPerfectCamera.cs | 10,677 | C# |
using Netnr.Blog.Data;
namespace Netnr.Blog.Web.Areas.Gist.Controllers
{
[Area("Gist")]
public class RawController : Controller
{
public ContextBase db;
public RawController(ContextBase cb)
{
db = cb;
}
/// <summary>
/// 原始数据
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
string result = string.Empty;
string filename = string.Empty;
string id = RouteData.Values["id"]?.ToString();
if (!string.IsNullOrWhiteSpace(id))
{
var mo = db.Gist.FirstOrDefault(x => x.GistCode == id && x.GistStatus == 1 && x.GistOpen == 1);
if (mo != null)
{
result = mo.GistContent;
filename = mo.GistFilename;
}
}
if (RouteData.Values["sid"]?.ToString() == "download")
{
return File(Encoding.Default.GetBytes(result), "text/plain", filename);
}
else
{
return Content(result);
}
}
}
} | 26.355556 | 111 | 0.458685 | [
"MIT"
] | netnr/np | src/Netnr.P/Netnr.Blog.Web/Areas/Gist/Controllers/RawController.cs | 1,196 | C# |
public static class Constants
{
public static class FunctionNames
{
public const string CosmosDbChangeFeedListener = "changefeed-listener";
}
} | 23.285714 | 79 | 0.717791 | [
"MIT"
] | alexanderwjrussell/stacks-dotnet-cqrs-events | src/functions/func-cosmosdb-worker/xxAMIDOxx.xxSTACKSxx.Worker/Constants.cs | 163 | C# |
// References:
// https://gist.github.com/tomkail/ba4136e6aa990f4dc94e0d39ec6a058c
// Developed by Tom Kail at Inkle
// Released under the MIT Licence as held at https://opensource.org/licenses/MIT
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace ScriptableData.Editor
{
[CustomPropertyDrawer(typeof(ScriptableObject), true)]
public class ExtendedScriptableObjectDrawer : PropertyDrawer
{
// Permamently exclude classes from being affected by the drawer.
private static readonly string[] ignoredFullClassNames = new string[] { "TMPro.TMP_FontAsset" };
private static readonly GUIContent buttonContent = EditorGUIUtility.IconContent("d_ScriptableObject On Icon");
private const int buttonWidth = 16;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float totalHeight = EditorGUIUtility.singleLineHeight;
SerializedObject serializedObject = null;
if (property.objectReferenceValue is ScriptableObject scriptableObject)
{
serializedObject = new SerializedObject(scriptableObject);
}
if (serializedObject == null || !serializedObject.HasVisableSubProperties() || fieldInfo.HasAttribute<NonExtendableAttribute>())
{
return totalHeight;
}
if (property.isExpanded)
{
// Iterate over all the values and draw them.
SerializedProperty p = serializedObject.GetIterator();
if (p.NextVisible(true))
{
do
{
// Skip drawing the class file.
if (EditorUtils.IsIgnoredProperty(p))
{
continue;
}
float height = EditorGUI.GetPropertyHeight(p, null, true) + EditorGUIUtility.standardVerticalSpacing;
totalHeight += height;
}
while (p.NextVisible(false));
}
// Add a tiny bit of height if open for the background
totalHeight += EditorGUIUtility.standardVerticalSpacing;
}
return totalHeight;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
Type fieldType = EditorUtils.GetFieldType(fieldInfo);
// Draw with default drawer.
if (fieldType == null || HasIgnoredClassName(fieldType) || fieldInfo.HasAttribute<NonExtendableAttribute>())
{
EditorGUI.PropertyField(position, property, label);
EditorGUI.EndProperty();
return;
}
Rect foldoutRect = new Rect(position.x, position.y, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight);
Rect indentedPosition = EditorGUI.IndentedRect(position);
float indentOffset = indentedPosition.x - position.x;
Rect propertyRect = new Rect(position.x + (EditorGUIUtility.labelWidth - indentOffset + 2), position.y, position.width - (EditorGUIUtility.labelWidth - indentOffset + 2), EditorGUIUtility.singleLineHeight);
SerializedObject serializedObject = null;
if(property.objectReferenceValue is ScriptableObject scriptableObject)
{
serializedObject = new SerializedObject(scriptableObject);
}
// Check for sub properties and if the property can be expanded.
if (serializedObject != null && serializedObject.HasVisableSubProperties())
{
property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, new GUIContent(property.displayName), true);
if (property.isExpanded)
{
// Draw sub properties.
serializedObject.Draw(position);
}
}
else
{
EditorGUI.LabelField(foldoutRect, new GUIContent(property.displayName));
if (property.objectReferenceValue == null)
{
propertyRect.width -= buttonWidth;
// Draw create button.
Rect buttonRect = new Rect(position.x + position.width - buttonWidth, position.y + 1, buttonWidth, EditorGUIUtility.singleLineHeight);
DrawScriptableObjectCreateButton(buttonRect, property, fieldType);
}
}
EditorGUI.BeginChangeCheck();
// Draw object field.
EditorGUI.PropertyField(propertyRect, property, GUIContent.none, false);
if (EditorGUI.EndChangeCheck())
{
property.serializedObject.ApplyModifiedProperties();
}
property.serializedObject.ApplyModifiedProperties();
EditorGUI.EndProperty();
}
private static void DrawScriptableObjectCreateButton(Rect position, SerializedProperty property, Type type)
{
if (GUI.Button(position, buttonContent, EditorStyles.iconButton))
{
GenericMenu typeChooser = new GenericMenu();
IEnumerable<Type> types = type.Assembly.GetTypes().Where(t => type.IsAssignableFrom(t));
foreach (Type t in types)
{
if (t.IsAbstract)
{
continue;
}
typeChooser.AddItem(new GUIContent(t.Name), false, (o) => {
property.objectReferenceValue = EditorUtils.CreateAssetWithSavePrompt(o as Type, EditorUtils.GetSelectedAssetPath(property));
property.serializedObject.ApplyModifiedProperties();
}, t);
}
typeChooser.ShowAsContext();
}
}
private static bool HasIgnoredClassName(Type type)
{
return ignoredFullClassNames.Contains(type.FullName);
}
}
} | 32.625806 | 209 | 0.733834 | [
"MIT"
] | maxartz15/ScriptableData | Editor/Drawers/ExtendedScriptableObjectDrawer.cs | 5,059 | C# |
using System.Collections.Generic;
namespace RoverSupertramp
{
class Invoker
{
private Coordinate _plateauSize;
private Rover _rover = new Rover();
private List<Command> _commands = new List<Command>();
/// <summary>
///
/// </summary>
/// <param name="position"></param>
public void SetStartPoint(Position position)
{
this._rover.Position = position;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Position GetCurrentRoverPosition()
{
return _rover.Position;
}
/// <summary>
///
/// </summary>
/// <param name="plateauSize"></param>
public void SetPlateauSize( Coordinate plateauSize)
{
this._plateauSize = plateauSize;
}
/// <summary>
///
/// </summary>
/// <param name="movement"></param>
public void ExecuteCommand(IMovement movement)
{
Command command = new RoverCommand(_rover, movement);
command.Execute();
this._commands.Add(command);
}
/// <summary>
///
/// </summary>
/// <param name="movements"></param>
public void ExecuteCommand(IEnumerable<IMovement> movements)
{
foreach (var movement in movements)
{
this.ExecuteCommand(movement);
}
}
}
}
| 25.206349 | 69 | 0.478589 | [
"MIT"
] | beratiyilik/RoverSupertramp | RoverSupertramp/Invoker.cs | 1,590 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/valid-tic-tac-toe-state/
/// Submission: https://leetcode.com/submissions/detail/400212633/
/// </summary>
internal class P0794
{
public class Solution
{
public bool ValidTicTacToe(string[] board)
{
var xs = board.SelectMany(x => x.ToCharArray()).Count(x => x == 'X');
var os = board.SelectMany(x => x.ToCharArray()).Count(x => x == 'O');
var valid = (xs == os) || (xs - os == 1);
if (!valid)
return false;
return !(VictoryFor(board, 'X') && VictoryFor(board, 'O'));
}
private bool VictoryFor(string[] board, char v)
{
var anyRow = board.Any(x => x.All(ch => ch == v));
if (anyRow)
return true;
var anyCol = Enumerable.Range(0, 3).Any(x => board[0][x] == v && board[1][x] == v && board[2][x] == v);
if (anyCol)
return true;
return (board[0][0] == v && board[1][1] == v && board[2][2] == v) ||
(board[2][0] == v && board[1][1] == v && board[0][2] == v);
}
}
}
}
| 29.068182 | 112 | 0.508991 | [
"MIT"
] | viacheslave/leetcode-naive | c#/Problems/P0794.cs | 1,279 | C# |
using System;
using Terraria;
using Terraria.Achievements;
namespace Terraria.GameContent.Achievements
{
public class CustomFloatCondition : AchievementCondition
{
private float _value;
private float _maxValue;
public float Value
{
get
{
return this._value;
}
set
{
float single = Utils.Clamp<float>(value, 0f, this._maxValue);
if (this._tracker != null)
{
((ConditionFloatTracker)this._tracker).SetValue(single, true);
}
this._value = single;
if (this._value == this._maxValue)
{
this.Complete();
}
}
}
private CustomFloatCondition(string name, float maxValue) : base(name)
{
this._maxValue = maxValue;
this._value = 0f;
}
public override void Clear()
{
this._value = 0f;
base.Clear();
}
public static AchievementCondition Create(string name, float maxValue)
{
return new CustomFloatCondition(name, maxValue);
}
protected override IAchievementTracker CreateAchievementTracker()
{
return new ConditionFloatTracker(this._maxValue);
}
}
} | 19.946429 | 73 | 0.64906 | [
"MIT"
] | BloodARG/tModLoaderTShock | TShock-general-devel/TerrariaServerAPI/Terraria/GameContent/Achievements/CustomFloatCondition.cs | 1,062 | C# |
using Microsoft.ServiceFabric.Data;
using System;
using System.Fabric;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Threading.Tasks;
using Trinity.Diagnostics;
using Trinity.DynamicCluster.Consensus;
using Trinity.DynamicCluster.Persistency;
using Trinity.Utilities;
namespace Trinity.ServiceFabric.Infrastructure.Interfaces
{
class ServiceFabricBackupManager : IBackupManager
{
private CancellationToken m_cancel;
private Task m_init;
private GraphEngineStatefulServiceRuntime m_svc;
private SemaphoreSlim m_sem;
//SF does not request backups
public event EventHandler RequestPartitionBackup = delegate{ };
public event EventHandler RequestPartitionRestore = delegate{ };
public void Dispose() { m_sem.Dispose(); }
public void Start(CancellationToken cancellationToken)
{
m_sem = new SemaphoreSlim(0);
m_cancel = cancellationToken;
m_init = InitAsync();
}
private async Task InitAsync()
{
while ((m_svc = GraphEngineStatefulServiceRuntime.Instance) == null)
{
await Task.Delay(1000, m_cancel);
}
m_svc.RequestRestore += OnServiceFabricRequestRestore;
}
private void OnServiceFabricRequestRestore(object sender, RestoreEventArgs e)
{
RequestPartitionRestore(sender, e);
}
public async Task Backup(IPersistentUploader uploader, EventArgs _)
{
await m_init;
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Creating ServiceFabric backup data.");
var dsc = new BackupDescription(async (bi, ct) =>
{
var fname = Path.Combine(TrinityConfig.StorageRoot, Path.GetRandomFileName());
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Compressing ServiceFabric backup data.");
ZipFile.CreateFromDirectory(bi.Directory, fname);
using(var f = File.OpenRead(fname))
{
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Uploading ServiceFabric backup data.");
await uploader.UploadMetadataAsync(MetadataKey, f);
}
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Backed up ServiceFabric backup data.");
return true;
});
await m_svc.Backup(dsc);
}
public async Task Restore(IPersistentDownloader downloader, EventArgs eventArgs)
{
await m_init;
if (eventArgs == EventArgs.Empty)
{
// !Note, we disable the event handler before we trigger an active restore, otherwise
// the active restore event will notify the backup controller, while in fact the restore
// command is issued from the controller, and SF backup manager should do it passively.
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: initiating a new restore operation.");
m_svc.RequestRestore -= OnServiceFabricRequestRestore;
await m_svc.FabricClient.TestManager.StartPartitionDataLossAsync(Guid.NewGuid(), PartitionSelector.PartitionIdOf(m_svc.Context.ServiceName, m_svc.Context.PartitionId), DataLossMode.PartialDataLoss);
await m_sem.WaitAsync();
m_svc.RequestRestore += OnServiceFabricRequestRestore;
return;
}
if (!(eventArgs is RestoreEventArgs rstArgs))
{
throw new NotSupportedException();
}
try
{
var ctx = rstArgs.m_rctx;
var dir = Path.Combine(TrinityConfig.StorageRoot, Path.GetRandomFileName());
var dsc = new RestoreDescription(dir);
var fname = Path.Combine(TrinityConfig.StorageRoot, Path.GetRandomFileName());
using (var file = File.OpenWrite(fname))
{
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Downloading ServiceFabric backup data.");
await downloader.DownloadMetadataAsync(MetadataKey, file);
}
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Decompressing ServiceFabric backup data.");
FileUtility.CompletePath(dir, create_nonexistent: true);
ZipFile.ExtractToDirectory(fname, dir);
File.Delete(fname);
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Restoring ServiceFabric backup data.");
await ctx.RestoreAsync(dsc);
Directory.Delete(dir, recursive: true);
Log.WriteLine($"{nameof(ServiceFabricBackupManager)}: Restored ServiceFabric backup data.");
rstArgs.Complete();
}
catch (Exception ex)
{
rstArgs.Complete(ex);
throw;
}
m_sem.Release();
}
private string MetadataKey => $"P{m_svc.PartitionId}_SFBackup.zip";
}
}
| 43.291667 | 214 | 0.614822 | [
"MIT"
] | Bhaskers-Blu-Org2/GraphEngine | src/Modules/GraphEngine.ServiceFabric/Trinity.ServiceFabric.Infrastructure/Interfaces/ServiceFabricBackupManager.cs | 5,197 | C# |
//-----------------------------------------------------------------------------
// FILE: DisconnectRequest.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Neon.Cadence;
using Neon.Common;
// $todo(jefflill): Investigate adding metrics details.
namespace Neon.Cadence.Internal
{
/// <summary>
/// <b>client --> proxy:</b> Requests that the proxy disconnect from a Cadence cluster.
/// </summary>
[InternalProxyMessage(InternalMessageTypes.DisconnectRequest)]
internal class DisconnectRequest : ProxyRequest
{
/// <summary>
/// Default constructor.
/// </summary>
public DisconnectRequest()
{
Type = InternalMessageTypes.DisconnectRequest;
}
/// <inheritdoc/>
public override InternalMessageTypes ReplyType => InternalMessageTypes.DisconnectReply;
/// <inheritdoc/>
internal override ProxyMessage Clone()
{
var clone = new DisconnectRequest();
CopyTo(clone);
return clone;
}
/// <inheritdoc/>
protected override void CopyTo(ProxyMessage target)
{
base.CopyTo(target);
}
}
}
| 30.190476 | 95 | 0.634069 | [
"Apache-2.0"
] | nforgeio/neonKUBE | Lib/Neon.Cadence/Internal/ClientMessages/DisconnectRequest.cs | 1,904 | C# |
using System.Linq;
using System;
using System.Collections.Generics;
namespace Programs
{
public class MyQueue {
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void Push(int x) {
}
/** Removes the element from in front of queue and returns that element. */
public int Pop() {
}
/** Get the front element. */
public int Peek() {
}
/** Returns whether the queue is empty. */
public bool Empty() {
}
}
public static class Program {
public static void Main() {
System.Console.WriteLine("Hello world");
}
}
} | 19.860465 | 83 | 0.468384 | [
"MIT"
] | shobhitmishra/CodingProblems | LeetCode/problem232.cs | 854 | C# |
using FIMSpace.FEditor;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace FIMSpace.FTail
{
public partial class FTailAnimator2_Editor
{
// RESOURCES ----------------------------------------
public static Texture2D _TexTailAnimIcon { get { if (__texTailAnimIcon != null) return __texTailAnimIcon; __texTailAnimIcon = Resources.Load<Texture2D>("Tail Animator/Tail Animator Icon Small"); return __texTailAnimIcon; } }
private static Texture2D __texTailAnimIcon = null;
public static Texture2D _TexWavingIcon { get { if (__texWaving != null) return __texWaving; __texWaving = Resources.Load<Texture2D>("Tail Animator/WavingIcon"); return __texWaving; } }
private static Texture2D __texWaving = null;
public static Texture2D _TexPartialBlendIcon { get { if (__texPartBlendIcon != null) return __texPartBlendIcon; __texPartBlendIcon = Resources.Load<Texture2D>("Tail Animator/PartialBlendIcon"); return __texPartBlendIcon; } }
private static Texture2D __texPartBlendIcon = null;
public static Texture2D _TexIKIcon { get { if (__texIKIcon != null) return __texIKIcon; __texIKIcon = Resources.Load<Texture2D>("Tail Animator/IKIcon"); return __texIKIcon; } }
private static Texture2D __texIKIcon = null;
public static Texture2D _TexDeflIcon { get { if (__texDeflIcon != null) return __texDeflIcon; __texDeflIcon = Resources.Load<Texture2D>("Tail Animator/Deflection"); return __texDeflIcon; } }
private static Texture2D __texDeflIcon = null;
private static Texture curveIcon { get { if (_curveIcon == null) _curveIcon = FGUI_Resources.Tex_Curve; /*EditorGUIUtility.IconContent("AudioLowPassFilter Icon").image;*/ return _curveIcon; } }
private static Texture _curveIcon;
private static Texture _TexWindIcon { get { if (_windIcon == null) _windIcon = Resources.Load<Texture2D>("Tail Animator/Wind"); return _windIcon; } }
private static Texture _windIcon;
private static UnityEngine.Object _manualFile;
private static GUIStyle smallStyle { get { if (_smallStyle == null) _smallStyle = new GUIStyle(EditorStyles.miniLabel) { fontStyle = FontStyle.Italic }; return _smallStyle; } }
private static GUIStyle _smallStyle;
// HELPER VARIABLES ----------------------------------------
private TailAnimator2 Get { get { if (_get == null) _get = target as TailAnimator2; return _get; } }
private TailAnimator2 _get;
private string topWarning = "";
private float topWarningAlpha = 0f;
static bool drawDefaultInspector = false;
//private Color limitsC = new Color(1f, 1f, 1f, 0.88f);
private Color c;
private Color bc;
private Color defaultValC = new Color(1f, 1f, 1f, 0.825f);
public List<SkinnedMeshRenderer> skins;
SkinnedMeshRenderer largestSkin;
Animator animator;
Animation animation;
/// <summary>
/// Trying to deep find skinned mesh renderer
/// </summary>
private void FindComponents()
{
if (skins == null) skins = new List<SkinnedMeshRenderer>();
foreach (var t in Get.transform.GetComponentsInChildren<Transform>())
{
SkinnedMeshRenderer s = t.GetComponent<SkinnedMeshRenderer>(); if (s) skins.Add(s);
if (!animator) animator = t.GetComponent<Animator>();
if (!animator) if (!animation) animation = t.GetComponent<Animation>();
}
if ((skins != null && largestSkin != null) && (animator != null || animation != null)) return;
if (Get.transform != Get.transform)
{
foreach (var t in Get.transform.GetComponentsInChildren<Transform>())
{
SkinnedMeshRenderer s = t.GetComponent<SkinnedMeshRenderer>(); if (!skins.Contains(s)) if (s) skins.Add(s);
if (!animator) animator = t.GetComponent<Animator>();
if (!animator) if (!animation) animation = t.GetComponent<Animation>();
}
}
// Searching in parent
if (skins.Count == 0)
{
Transform lastParent = Get.transform;
while (lastParent != null)
{
if (lastParent.parent == null) break;
lastParent = lastParent.parent;
}
foreach (var t in lastParent.GetComponentsInChildren<Transform>())
{
SkinnedMeshRenderer s = t.GetComponent<SkinnedMeshRenderer>(); if (!skins.Contains(s)) if (s) skins.Add(s);
if (!animator) animator = t.GetComponent<Animator>();
if (!animator) if (!animation) animation = t.GetComponent<Animation>();
}
}
if (skins.Count > 1)
{
largestSkin = skins[0];
for (int i = 1; i < skins.Count; i++)
if (skins[i].bones.Length > largestSkin.bones.Length)
largestSkin = skins[i];
}
else
if (skins.Count > 0) largestSkin = skins[0];
}
/// <summary>
/// Checking if transform is child of choosed root bone parent transform
/// </summary>
bool IsChildOf(Transform child, Transform rootParent)
{
Transform tParent = child;
while (tParent != null && tParent != rootParent)
{
tParent = tParent.parent;
}
if (tParent == null) return false; else return true;
}
/// <summary>
/// Checking if transform is child of choosed root bone parent transform
/// </summary>
Transform GetLastChild(Transform rootParent)
{
Transform tChild = rootParent;
while (tChild.childCount > 0) tChild = tChild.GetChild(0);
return tChild;
}
/// <summary>
/// Getting editor selected objects with tail animators to apply changes to multiple tail animator objects
/// </summary>
private List<TailAnimator2> GetSelectedTailAnimators()
{
List<TailAnimator2> anims = new List<TailAnimator2>();
for (int i = 0; i < Selection.gameObjects.Length; i++)
{
TailAnimator2 t = Selection.gameObjects[i].GetComponent<TailAnimator2>();
if (t) if (!anims.Contains(t)) anims.Add(t);
}
lastSelected = anims;
return anims;
}
List<TailAnimator2> lastSelected;
}
}
| 42.993631 | 232 | 0.59437 | [
"MIT"
] | omerasikoglu/Capstone-Runner | Assets/Tools/FImpossible Creations/Editor/Tail Animator/TailAnimator.Editor.Helpers.cs | 6,752 | C# |
// --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
using System.IO;
using System.Threading.Tasks;
using Microsoft.Oryx.BuildScriptGenerator.Common;
using Microsoft.Oryx.BuildScriptGenerator.Php;
using Microsoft.Oryx.Tests.Common;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Oryx.Integration.Tests
{
[Trait("category", "php")]
public class PhpDynamicInstallationTest : PhpEndToEndTestsBase
{
public PhpDynamicInstallationTest(ITestOutputHelper output, TestTempDirTestFixture fixture)
: base(output, fixture)
{
}
[Theory]
[InlineData("8.0")]
[InlineData("7.4")]
[InlineData("7.3")]
[InlineData("7.2")]
[InlineData("7.0")]
[InlineData("5.6")]
public async Task CanBuildAndRunApp(string phpVersion)
{
// Arrange
var exifImageTypePng = "3";
var appName = "exif-example";
var hostDir = Path.Combine(_hostSamplesDir, "php", appName);
var volume = DockerVolume.CreateMirror(hostDir);
var appDir = volume.ContainerDir;
var appOutputDirVolume = CreateAppOutputDirVolume();
var appOutputDir = appOutputDirVolume.ContainerDir;
var buildScript = new ShellScriptBuilder()
.AddDefaultTestEnvironmentVariables()
.AddCommand(
$"oryx build {appDir} -i /tmp/int -o {appOutputDir} " +
$"--platform {PhpConstants.PlatformName} --platform-version {phpVersion}")
.ToString();
var runScript = new ShellScriptBuilder()
.AddCommand($"oryx create-script -appPath {appOutputDir} -output {RunScriptPath}")
.AddCommand(RunScriptPath)
.ToString();
// Act & Assert
await EndToEndTestHelper.BuildRunAndAssertAppAsync(
appName,
_output,
new[] { volume, appOutputDirVolume },
_imageHelper.GetGitHubActionsBuildImage(),
"/bin/sh", new[] { "-c", buildScript },
_imageHelper.GetRuntimeImage("php", phpVersion),
ContainerPort,
"/bin/sh", new[] { "-c", runScript },
async (hostPort) =>
{
string exifOutput = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/");
// The test app: `echo exif_imagetype('64x64.png')`
Assert.Equal(exifImageTypePng, exifOutput);
});
}
}
} | 41.514286 | 107 | 0.527529 | [
"MIT"
] | JasonFreeberg/Oryx | tests/Oryx.Integration.Tests/Php/PhpDynamicInstallationTest.cs | 2,839 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using AlertToCare.Models;
namespace AlertToCare.DatabaseOperations
{
public class PatientDbOps: DbOps
{
public PatientDbOps(string filePath) : base(filePath) { }
public object AddPatientToDb(PatientModel newPatient)
{
DbConnection.Open();
using var command = DbConnection.CreateCommand();
try
{
command.CommandText =
@"INSERT INTO Patients(Pid, Name, Age, Gender, Email, PhoneNumber, Address, IcuID, BedID )" +
"VALUES (@Pid, @Name, @Age, @Gender, @Email, @PhoneNumber, @Address, @IcuID, @BedId);";
command.Parameters.AddWithValue(@"Pid", newPatient.PId);
command.Parameters.AddWithValue(@"Name", newPatient.Name);
command.Parameters.AddWithValue(@"Age", newPatient.Age);
command.Parameters.AddWithValue(@"Gender", newPatient.Gender);
command.Parameters.AddWithValue(@"Email", newPatient.Email);
command.Parameters.AddWithValue(@"PhoneNumber", newPatient.PhoneNumber);
command.Parameters.AddWithValue(@"Address", newPatient.Address);
command.Parameters.AddWithValue(@"IcuID", newPatient.IcuId);
command.Parameters.AddWithValue(@"BedId", newPatient.BedId);
command.Prepare();
command.ExecuteNonQuery();
return HttpStatusCode.OK;
}
catch (Exception e)
{
Console.WriteLine(e);
return HttpStatusCode.InternalServerError;
}
finally
{
CloseDb();
}
}
public object DeletePatientFromDatabase(string pid)
{
DbConnection.Open();
using var command = DbConnection.CreateCommand();
try
{
command.CommandText = $"DELETE from Patients where pid = '{pid}';";
command.Prepare();
command.ExecuteNonQuery();
return HttpStatusCode.OK;
}
catch (Exception e)
{
Console.WriteLine(e);
return HttpStatusCode.InternalServerError;
}
finally
{
CloseDb();
}
}
public Dictionary<string, PatientModel> GetAllPatientsFromDb()
{
DbConnection.Open();
var allPatients = new Dictionary<string, PatientModel>();
using var command = DbConnection.CreateCommand();
try
{
command.CommandText = "Select * from Patients";
command.Prepare();
command.ExecuteNonQuery();
var result = command.ExecuteReader();
while (result.Read())
{
var patient = new PatientModel
{
PId = result.GetString(0),
Name = result.GetString(1),
Age = result.GetInt32(2),
Gender = result.GetString(3),
Email = result.GetString(4),
PhoneNumber = result.GetString(5),
Address = result.GetString(6),
IcuId = result.GetString(7),
BedId = result.GetInt32(8)
};
allPatients.Add(patient.PId, patient);
}
return allPatients;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
finally
{
CloseDb();
}
}
}
}
| 33.86087 | 113 | 0.491525 | [
"MIT"
] | Engin-Boot/alert-to-care-s21b7 | AlertToCare/DatabaseOperations/PatientDbOps.cs | 3,896 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace LeakBlocker
{
internal static class EntryPoint
{
private static volatile bool loaded;
private sealed class SplashScreen : Form
{
private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x00080000;
return cp;
}
}
public SplashScreen()
{
FormBorderStyle = FormBorderStyle.None;
BackgroundImage = LeakBlocker.AdminView.Resources.Logo;
AutoScaleMode = AutoScaleMode.None;
ClientSize = new Size(256, 256);
ShowIcon = false;
StartPosition = FormStartPosition.CenterScreen;
TopMost = true;
ShowInTaskbar = false;
timer.Interval = 100;
timer.Tick += delegate(object sender, EventArgs e)
{
if (loaded)
{
timer.Enabled = false;
Close();
}
};
timer.Start();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
timer.Enabled = false;
timer.Dispose();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DrawForm();
if (loaded)
Close();
}
protected override void OnPaint(PaintEventArgs e)
{
DrawForm();
}
private void DrawForm()
{
IntPtr screenDeviceContext = GetDC(IntPtr.Zero);
IntPtr memoryDeviceContext = CreateCompatibleDC(screenDeviceContext);
IntPtr bitmapHandle = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
using (var bitmap = new Bitmap(BackgroundImage))
{
bitmapHandle = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = SelectObject(memoryDeviceContext, bitmapHandle);
Size size = bitmap.Size;
Point pointSource = Point.Empty;
var topPosition = new Point(Left, Top);
var blend = new BLENDFUNCTION
{
SourceConstantAlpha = 255,
AlphaFormat = 1
};
UpdateLayeredWindow(Handle, screenDeviceContext, ref topPosition, ref size, memoryDeviceContext, ref pointSource, 0, ref blend, 2);
}
ReleaseDC(IntPtr.Zero, screenDeviceContext);
if (bitmapHandle != IntPtr.Zero)
{
SelectObject(memoryDeviceContext, oldBitmap);
DeleteObject(bitmapHandle);
}
DeleteDC(memoryDeviceContext);
}
catch (Exception)
{
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct BLENDFUNCTION
{
internal byte BlendOp;
internal byte BlendFlags;
internal byte SourceConstantAlpha;
internal byte AlphaFormat;
}
[DllImport("user32.dll")]
private static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
}
[STAThread]
internal static int Main(string[] parameters)
{
var thread = new Thread((ThreadStart)delegate
{
using (var form = new SplashScreen())
{
Application.Run(form);
}
});
thread.IsBackground = true;
return Program.Start(parameters, thread);
}
}
}
| 32.22561 | 208 | 0.495364 | [
"MIT"
] | imanushin/leak-blocker | Projects/LeakBlocker.AdminView/EntryPoint.cs | 5,287 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/mmeapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public partial struct MIXERCONTROLDETAILS_UNSIGNED
{
[NativeTypeName("DWORD")]
public uint dwValue;
}
}
| 31.529412 | 145 | 0.73694 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/mmeapi/MIXERCONTROLDETAILS_UNSIGNED.cs | 538 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Identity.UI.UIFrameworkAttribute("Bootstrap4")]
[assembly: Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryContentRootAttribute("CooperSystem.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "C:\\Users\\mrdoo\\Documents\\CooperSystem\\CooperSystem.Aplication", "CooperSystem.Application.csproj", "0")]
[assembly: Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryContentRootAttribute("CooperSystem.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "C:\\Users\\mrdoo\\Documents\\CooperSystem\\CooperSystem.Domain", "CooperSystem.Domain.csproj", "0")]
[assembly: Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryContentRootAttribute("CooperSystem.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=nul" +
"l", "C:\\Users\\mrdoo\\Documents\\CooperSystem\\CooperSystem.Infrastructure", "CooperSystem.Infrastructure.csproj", "0")]
[assembly: Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryContentRootAttribute("CooperSystem.WebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "C:\\Users\\mrdoo\\Documents\\CooperSystem\\CooperSystem.WebApi", "CooperSystem.WebApi.csproj", "0")]
[assembly: System.Reflection.AssemblyCompanyAttribute("CooperSystem.UnitTests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CooperSystem.UnitTests")]
[assembly: System.Reflection.AssemblyTitleAttribute("CooperSystem.UnitTests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Gerado pela classe WriteCodeFragment do MSBuild.
| 74.766667 | 279 | 0.740526 | [
"MIT"
] | danielm2512/CooperSystem | CooperSystem.UnitTests/obj/Debug/net5.0/CooperSystem.UnitTests.AssemblyInfo.cs | 2,252 | C# |
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using ExchangeSharp.OKGroup;
namespace ExchangeSharp
{
public sealed partial class ExchangeOKExAPI : OKGroupCommon
{
public override string BaseUrl { get; set; } = "https://www.okex.com/api/v1";
public override string BaseUrlV2 { get; set; } = "https://www.okex.com/v2/spot";
public override string BaseUrlV3 { get; set; } = "https://www.okex.com/api";
public override string BaseUrlWebSocket { get; set; } = "wss://real.okex.com:10442/ws/v3";
protected override bool isFuturesAndSwapEnabled { get; } = true;
}
public partial class ExchangeName { public const string OKEx = "OKEx"; }
} | 63.814815 | 460 | 0.763784 | [
"MIT"
] | edalmasso/ExchangeSharp | ExchangeSharp/API/Exchanges/OKGroup/ExchangeOKExAPI.cs | 1,725 | C# |
#region License
// The PostgreSQL License
//
// Copyright (C) 2017 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Npgsql.FrontendMessages
{
class TerminateMessage : SimpleFrontendMessage
{
const byte Code = (byte)'X';
internal static readonly TerminateMessage Instance = new TerminateMessage();
TerminateMessage() { }
internal override int Length => 1 + 4;
internal override void WriteFully(WriteBuffer buf)
{
buf.WriteByte(Code);
buf.WriteInt32(4);
}
public override string ToString() => "[Terminate]";
}
}
| 34.14 | 84 | 0.727592 | [
"MIT"
] | muhammet-kandemir-95/MA.Dal.Dao | MA.Dao.Generate.VSIX/MA.Dao.Generate.VSIX.App/Other Databases/Npgsql/FrontendMessages/TerminateMessage.cs | 1,709 | C# |
using UnityEngine;
using UnityEditor;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Collections.Generic;
[CustomEditor(typeof(YarnImporter))]
public class YarnImporterEditor : UnityEditor.AssetImporters.ScriptedImporterEditor {
int selectedLanguageIndex;
int selectedNewTranslationLanguageIndex;
// We use a custom type to refer to cultures, because certain cultures
// that we want to support don't exist in the .NET database (like Māori)
Culture[] cultureInfo;
SerializedProperty baseLanguageProp;
public override void OnEnable() {
base.OnEnable();
cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(c => c.Name != "")
.Select(c => new Culture { Name = c.Name, DisplayName = c.DisplayName })
.Append(new Culture { Name = "mi", DisplayName = "Maori" })
.OrderBy(c => c.DisplayName)
.ToArray();
baseLanguageProp = serializedObject.FindProperty("baseLanguageID");
if (string.IsNullOrEmpty(baseLanguageProp.stringValue)) {
selectedLanguageIndex = cultureInfo.
Select((culture, index) => new { culture, index })
.FirstOrDefault(element => element.culture.Name == CultureInfo.CurrentCulture.Name)
.index;
} else {
selectedLanguageIndex = cultureInfo.Select((culture, index) => new { culture, index })
.FirstOrDefault(pair => pair.culture.Name == baseLanguageProp.stringValue)
.index;
}
selectedNewTranslationLanguageIndex = selectedLanguageIndex;
}
public override void OnDisable() {
base.OnDisable();
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.Space();
YarnImporter yarnImporter = (target as YarnImporter);
var cultures = cultureInfo.Select(c => $"{c.DisplayName}");
// Array of translations that have been added to this asset + base language
var culturesAvailableOnAsset = yarnImporter.localizations.
Select(element => element.languageName).
Append(cultureInfo[selectedLanguageIndex].Name).
OrderBy(element => element).
ToArray();
selectedLanguageIndex = EditorGUILayout.Popup("Base Language", selectedLanguageIndex, cultures.ToArray());
baseLanguageProp.stringValue = cultureInfo[selectedLanguageIndex].Name;
if (yarnImporter.isSuccesfullyCompiled == false) {
EditorGUILayout.HelpBox(yarnImporter.compilationErrorMessage, MessageType.Error);
return;
}
EditorGUILayout.Space();
var canCreateLocalisation = yarnImporter.StringsAvailable == true && yarnImporter.AnyImplicitStringIDs == false;
using (new EditorGUI.DisabledScope(!canCreateLocalisation))
using (new EditorGUILayout.HorizontalScope()) {
selectedNewTranslationLanguageIndex = EditorGUILayout.Popup(selectedNewTranslationLanguageIndex, cultures.ToArray());
if (GUILayout.Button("Create New Localisation", EditorStyles.miniButton)) {
var stringsTableText = AssetDatabase
.LoadAllAssetsAtPath(yarnImporter.assetPath)
.OfType<TextAsset>()
.FirstOrDefault()?
.text ?? "";
var selectedCulture = cultureInfo[selectedNewTranslationLanguageIndex];
var assetDirectory = Path.GetDirectoryName(yarnImporter.assetPath);
var newStringsTablePath = $"{assetDirectory}/{Path.GetFileNameWithoutExtension(yarnImporter.assetPath)} ({selectedCulture.Name}).csv";
newStringsTablePath = AssetDatabase.GenerateUniqueAssetPath(newStringsTablePath);
var writer = File.CreateText(newStringsTablePath);
writer.Write(stringsTableText);
writer.Close();
AssetDatabase.ImportAsset(newStringsTablePath);
var asset = AssetDatabase.LoadAssetAtPath<TextAsset>(newStringsTablePath);
EditorGUIUtility.PingObject(asset);
// Automatically add newly created translation csv file to yarn program
var localizationsIndex = System.Array.FindIndex(yarnImporter.localizations, element => element.languageName == selectedCulture.Name);
var localizationSerializedProperty = serializedObject.FindProperty("localizations");
if (localizationsIndex != -1) {
localizationSerializedProperty.GetArrayElementAtIndex(localizationsIndex).FindPropertyRelative("text").objectReferenceValue = asset;
} else {
localizationSerializedProperty.InsertArrayElementAtIndex(localizationSerializedProperty.arraySize);
localizationSerializedProperty.GetArrayElementAtIndex(localizationSerializedProperty.arraySize-1).FindPropertyRelative("text").objectReferenceValue = asset;
localizationSerializedProperty.GetArrayElementAtIndex(localizationSerializedProperty.arraySize-1).FindPropertyRelative("languageName").stringValue = selectedCulture.Name;
}
}
}
if (yarnImporter.StringsAvailable == false) {
EditorGUILayout.HelpBox("This file doesn't contain any localisable lines or options.", MessageType.Info);
}
if (yarnImporter.AnyImplicitStringIDs) {
EditorGUILayout.HelpBox("Add #line: tags to all lines and options to enable creating new localisations. Either add them manually, or click Add Line Tags to automatically add tags. Note that this will modify your files on disk, and cannot be undone.", MessageType.Info);
if (GUILayout.Button("Add Line Tags")) {
AddLineTagsToFile(yarnImporter.assetPath);
}
}
// Only update localizations if line tags exist and localizations exist
else if (yarnImporter .localizations.Length > 0)
{
if (GUILayout.Button("Update Localizations"))
{
UpdateLocalizations(AssetDatabase
.LoadAllAssetsAtPath(yarnImporter.assetPath)
.OfType<TextAsset>()
.FirstOrDefault()?
.text ?? "");
}
}
// Localization list
EditorGUILayout.PropertyField(serializedObject.FindProperty("localizations"), true);
var success = serializedObject.ApplyModifiedProperties();
#if UNITY_2018
if (success) {
EditorUtility.SetDirty(target);
AssetDatabase.WriteImportSettingsIfDirty(AssetDatabase.GetAssetPath(target));
}
#endif
#if UNITY_2019_1_OR_NEWER
ApplyRevertGUI();
#endif
}
private void AddLineTagsToFile(string assetPath) {
// First, gather all existing line tags, so that we don't
// accidentally overwrite an existing one. Do this by finding _all_
// YarnPrograms, and by extension their importers, and get the
// string tags that they found.
var allLineTags = Resources.FindObjectsOfTypeAll<YarnProgram>() // get all yarn programs that have been imported
.Select(asset => AssetDatabase.GetAssetOrScenePath(asset)) // get the path on disk
.Select(path => AssetImporter.GetAtPath(path)) // get the asset importer for that path
.OfType<YarnImporter>() // ensure that they're all YarnImporters
.SelectMany(importer => importer.stringIDs)
.ToList(); // get all string IDs, flattened into one list
var contents = File.ReadAllText(assetPath);
var taggedVersion = Yarn.Compiler.Utility.AddTagsToLines(contents, allLineTags);
File.WriteAllText(assetPath, taggedVersion);
AssetDatabase.ImportAsset(assetPath);
}
void UpdateLocalizations(string newBaseCsv)
{
// Goes through each localization string table csv file and merges it with the new base string table
YarnImporter yarnImporter = (target as YarnImporter);
for (int i = 0; i < yarnImporter.localizations.Length; i++)
{
// Feeds the merge function with the old localized string table, the new base string table and the current file name in case it has changed.
string merged = MergeStringTables(yarnImporter.localizations[i].text.text, newBaseCsv, Path.GetFileNameWithoutExtension(yarnImporter.assetPath));
// Save the merged csv to file (copied from the "Create New Localisation" button).
var assetDirectory = Path.GetDirectoryName(yarnImporter.assetPath);
string language = yarnImporter.localizations[i].languageName;
var newStringsTablePath = $"{assetDirectory}/{Path.GetFileNameWithoutExtension(yarnImporter.assetPath)} ({language}).csv";
newStringsTablePath = AssetDatabase.GenerateUniqueAssetPath(newStringsTablePath);
var writer = File.CreateText(newStringsTablePath);
writer.Write(merged);
writer.Close();
AssetDatabase.ImportAsset(newStringsTablePath);
var asset = AssetDatabase.LoadAssetAtPath<TextAsset>(newStringsTablePath);
EditorGUIUtility.PingObject(asset);
}
}
string MergeStringTables(string oldLocalizedCsv, string newBaseCsv, string outputFileName)
{
// Use the CsvHelper to convert the two csvs to lists so they are easy to work with
List<CsvEntry> oldEntries = new List<CsvEntry>();
List<CsvEntry> newEntries = new List<CsvEntry>();
using (var oldReader = new StringReader(oldLocalizedCsv))
using (var newReader = new StringReader(newBaseCsv))
{
CsvHelper.CsvReader oldParser = new CsvHelper.CsvReader(oldReader, new CsvHelper.Configuration.Configuration(CultureInfo.InvariantCulture));
CsvHelper.CsvReader newParser = new CsvHelper.CsvReader(newReader, new CsvHelper.Configuration.Configuration(CultureInfo.InvariantCulture));
oldParser.Read();
newParser.Read();
oldParser.ReadHeader();
newParser.ReadHeader();
while (oldParser.Read())
{
oldEntries.Add(
new CsvEntry
{
id = oldParser.GetField("id"),
text = oldParser.GetField("text"),
file = oldParser.GetField("file"),
node = oldParser.GetField("node"),
lineNumber = oldParser.GetField<int>("lineNumber"),
}
);
}
while (newParser.Read())
{
newEntries.Add(
new CsvEntry
{
id = newParser.GetField("id"),
text = newParser.GetField("text"),
file = newParser.GetField("file"),
node = newParser.GetField("node"),
lineNumber = newParser.GetField<int>("lineNumber"),
}
);
}
}
// This is where we merge the two string tables. Here's what's happening:
// Use CsvParser to parse new base string table and old localized string table
// The strategy is to use the fact that the two string tables look alike to optimize.
// The algorithm goes through the string tables side by side. Imagine two fingers running
// through the entries. At each line there are four different scenarios that we test for:
// scenario 1: The lines match (matching tags)
// scenario 2: The line in the new string table exists in the old string table but has been moved from somewhere else
// scenario 3: The line in the new string table is completely new (no line tags in old string table match it)
// scenario 4: The line in the old string table has been deleted (no line tags in new string table match it)
//Go line by line:
//1.If line tags are the same: add old localized with new line number and node. Increase index of both. (s1: matching lines)
//2.Else if line tags are different:
// a. Search forward in the old string table for that line tag
// i. if we find it: add old localized with new line number and node. Remove from old. Increase new index. (s2: old line moved)
// ii. If we don't find it: Search forward in new string table for that line tag
// I. if we find it: add the one new line we are on. Increase new index. (s3: line is new)
// II. if we don't find it: ignore line. Increase old index. (s4: line has been deleted)
int oldIndex = 0;
int newIndex = 0;
List<CsvEntry> mergedEntries = new List<CsvEntry>();
// Mark new lines as new so they are easy to spot
string newlineMarker = " (((NEW LINE)))";
while (true)
{
// If no more entries in old: add the rest of the new entries and break
if (oldEntries.Count <= oldIndex)
{
for (int i = newIndex; i < newEntries.Count; i++)
{
CsvEntry entry = newEntries[i];
entry.text += newlineMarker;
mergedEntries.Add(entry);
}
break;
}
// If no more entries in new: all additional old entries must have been deleted so break
if (newEntries.Count <= newIndex)
{
break;
}
//1. If line tags are the same: add old localized with new line number. Increase index of both.
if (oldEntries[oldIndex].id == newEntries[newIndex].id)
{
CsvEntry entry = oldEntries[oldIndex];
entry.lineNumber = newEntries[newIndex].lineNumber;
entry.node = newEntries[newIndex].node;
mergedEntries.Add(entry);
oldIndex++;
newIndex++;
continue;
}
//2. Else if line tags are different:
else
{
// a. Search forward in the old string table for that line tag
bool didFindInOld = false;
for (int i = oldIndex + 1; i < oldEntries.Count; i++)
{
// i. if we find it: add old localized with new line number. Remove from old. Increase index of new. (old line moved)
if (oldEntries[i].id == newEntries[newIndex].id)
{
CsvEntry entry = oldEntries[i];
entry.lineNumber = newEntries[newIndex].lineNumber;
entry.node = newEntries[newIndex].node;
mergedEntries.Add(entry);
oldEntries.RemoveAt(i);
didFindInOld = true;
newIndex++;
break;
}
}
if (didFindInOld)
{
continue;
}
// ii.If we don't find it: Search forward in new string table for that line tag
bool didFindInNew = false;
for (int i = newIndex + 1; i < newEntries.Count; i++)
{
// I. if we find it: add the one new line we are on. Increase index of new. (line is new)
if (oldEntries[oldIndex].id == newEntries[i].id)
{
CsvEntry entry = newEntries[newIndex];
entry.text += newlineMarker;
mergedEntries.Add(entry);
newIndex++;
didFindInNew = true;
break;
}
}
// II. if we don't find it: ignore line. Increase index of old. (line has been deleted)
if (!didFindInNew)
{
oldIndex++;
}
}
}
// Entries are not necessarily added in the correct order and have to be sorted
mergedEntries.Sort((a, b) => a.lineNumber.CompareTo(b.lineNumber));
// Create new Csv file
using (var memoryStream = new MemoryStream())
using (var textWriter = new StreamWriter(memoryStream))
{
// Generate the localised .csv file
var csv = new CsvHelper.CsvWriter(textWriter, new CsvHelper.Configuration.Configuration(CultureInfo.InvariantCulture));
var lines = mergedEntries.Select(x => new
{
id = x.id,
text = x.text,
file = outputFileName,
node = x.node,
lineNumber = x.lineNumber
});
csv.WriteRecords(lines);
textWriter.Flush();
memoryStream.Position = 0;
using (var reader = new StreamReader(memoryStream))
{
return reader.ReadToEnd();
}
}
}
struct CsvEntry
{
public string id;
public string text;
public string file;
public string node;
public int lineNumber;
}
} | 43.74813 | 281 | 0.596192 | [
"CC0-1.0"
] | CommanderKeef/Space-Voyager-Odyssey-Stories-Ep.-I | Assets/YarnSpinner/Editor/YarnImporterEditor.cs | 17,544 | C# |
using Godot;
public class Bee : Muff
{
[Export] protected int chance = 0;
[Export] protected Color bulletModulate = default(Color);
[Export] protected float shootTimer = 0;
public override void _Ready()
{
base._Ready();
GetNode<Timer>("ShootTimer").WaitTime = shootTimer;
GDArea.Bullets.RegisterEmitter(this, "BeeBullet",
(p, i) =>
{
p.Translate(new Vector2(12 + (i > 0 ? 5 : -5), 24));
p.Modulate = bulletModulate;
p.GetNode<AnimatedSprite>("AnimatedSprite").FlipH = i > 0;
p.VelocityMMF2 = 30;
p.DirectionMMF2 = (i < 0 ? 19 : 27) + random.Next(3);
});
}
private void _on_ShootTimer_timeout()
{
if (random.Next(chance) != 0) { return; }
GetNode<RawAudioPlayer2D>("ShotPlayer").Play();
GDArea.Bullets.Emit(this, direction < 0 ? -1 : 1);
}
}
| 30.451613 | 74 | 0.545551 | [
"MIT"
] | youkaicountry/yknytt | knytt/objects/banks/bank2/Bee.cs | 944 | C# |
using UnityEngine;
namespace TotalAI
{
[CreateAssetMenu(fileName = "RandomTF", menuName = "Total AI/Target Factors/Random", order = 0)]
public class RandomTF : TargetFactor
{
public override float Evaluate(Agent agent, Entity entity, Mapping mapping, bool forInventory)
{
return minMaxCurve.EvalRandomIgnoreMinMax();
}
}
}
| 26.928571 | 102 | 0.668435 | [
"MIT"
] | TotalAI/TotalAI | TotalAI/Scripts/ScriptableObjects/TargetFactors/RandomTF.cs | 379 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class NodeValidators
{
#region Verifiers
internal static void PointerNameVerification(ExpressionSyntax nameTree, string name)
{
Assert.IsType(typeof(PointerTypeSyntax), nameTree);
var pointerName = nameTree as PointerTypeSyntax;
Assert.Equal(pointerName.ElementType.ToString(), name);
}
internal static void PredefinedNameVerification(ExpressionSyntax nameTree, string typeName)
{
Assert.IsType(typeof(PredefinedTypeSyntax), nameTree);
var predefName = nameTree as PredefinedTypeSyntax;
Assert.Equal(predefName.ToString(), typeName);
}
internal static void ArrayNameVerification(ExpressionSyntax nameTree, string arrayName, int numRanks)
{
Assert.IsType(typeof(ArrayTypeSyntax), nameTree);
var arrayType = nameTree as ArrayTypeSyntax;
Assert.Equal(arrayType.ElementType.ToString(), arrayName);
Assert.Equal(arrayType.RankSpecifiers.Count(), numRanks);
}
internal static void AliassedNameVerification(ExpressionSyntax nameTree, string alias, string name)
{
// Verification of the change
Assert.IsType(typeof(AliasQualifiedNameSyntax), nameTree);
var aliasName = nameTree as AliasQualifiedNameSyntax;
Assert.Equal(aliasName.Alias.ToString(), alias);
Assert.Equal(aliasName.Name.ToString(), name);
}
internal static void DottedNameVerification(ExpressionSyntax nameTree, string left, string right)
{
// Verification of the change
Assert.IsType(typeof(QualifiedNameSyntax), nameTree);
var dottedName = nameTree as QualifiedNameSyntax;
Assert.Equal(dottedName.Left.ToString(), left);
Assert.Equal(dottedName.Right.ToString(), right);
}
internal static void GenericNameVerification(ExpressionSyntax nameTree, string name, params string[] typeNames)
{
// Verification of the change
Assert.IsType(typeof(GenericNameSyntax), nameTree);
var genericName = nameTree as GenericNameSyntax;
Assert.Equal(genericName.Identifier.ToString(), name);
Assert.Equal(genericName.TypeArgumentList.Arguments.Count, typeNames.Count());
int i = 0;
foreach (string str in typeNames)
{
Assert.Equal(genericName.TypeArgumentList.Arguments[i].ToString(), str);
i++;
}
}
internal static void BasicNameVerification(ExpressionSyntax nameTree, string name)
{
// Verification of the change
Assert.IsType(typeof(IdentifierNameSyntax), nameTree);
var genericName = nameTree as IdentifierNameSyntax;
Assert.Equal(genericName.ToString(), name);
}
#endregion
}
} | 42.556962 | 184 | 0.661808 | [
"Apache-2.0"
] | codemonkey85/roslyn | Src/Compilers/CSharp/Test/Syntax/IncrementalParsing/NodeValidators.cs | 3,364 | C# |
using Microsoft.AspNetCore.Mvc;
namespace PierresTreatAndFlavor.Controllers
{
public class Homecontroller : Controller
{
[HttpGet("/")]
public ActionResult Index()
{
return View();
}
}
} | 16.538462 | 43 | 0.665116 | [
"MIT"
] | keidsiri/PierresTreatAndFlavor | PierresTreatAndFlavor/Controllers/HomeController.cs | 215 | C# |
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/
//
// 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 Castle.DynamicProxy.Tests
{
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class CustomAttributesTestCase : BasePEVerifyTestCase
{
[Test]
public void Should_Proxy_type_having_complicated_arguments()
{
// http://support.castleproject.org/projects/DYNPROXY/issues/view/DYNPROXY-ISSUE-108
var proxy = generator.CreateClassProxy(typeof(Classes.ClassWith_Smart_Attribute));
var properties = proxy.GetType().GetProperties();
Assert.IsNotEmpty(properties);
Assert.DoesNotThrow(() => properties[0].GetCustomAttributes(false));
}
}
}
| 38.323529 | 96 | 0.709133 | [
"Apache-2.0"
] | belav/Core | src/Castle.Core.Tests/DynamicProxy.Tests/CustomAttributesTestCase.cs | 1,303 | C# |
using System.Linq;
using Mapster;
namespace Kasp.ObjectMapper.Mapster;
public class Mapster : IObjectMapper<Mapster>, IObjectMapper {
public TDestination MapTo<TDestination>(object source) => source.Adapt<TDestination>();
public TDestination MapTo<TSource, TDestination>(TSource source, TDestination destination) => source.Adapt(destination);
public IQueryable<TDestination> MapTo<TDestination>(IQueryable source) => source.ProjectToType<TDestination>();
}
| 35.692308 | 121 | 0.801724 | [
"MIT"
] | mo3in/Kasp | src/Kasp.ObjectMapper.Mapster/Mapster.cs | 464 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace TTC2019.BinaryDecision.Metamodels.TruthTables.TT
{
/// <summary>
/// The public interface for Row
/// </summary>
[DefaultImplementationTypeAttribute(typeof(Row))]
[XmlDefaultImplementationTypeAttribute(typeof(Row))]
[ModelRepresentationClassAttribute("https://www.transformation-tool-contest.eu/2019/tt#//Row")]
public interface IRow : IModelElement, ILocatedElement
{
/// <summary>
/// The owner property
/// </summary>
[BrowsableAttribute(false)]
[XmlElementNameAttribute("owner")]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[XmlAttributeAttribute(true)]
[XmlOppositeAttribute("rows")]
ITruthTable Owner
{
get;
set;
}
/// <summary>
/// The cells property
/// </summary>
[LowerBoundAttribute(1)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)]
[BrowsableAttribute(false)]
[XmlElementNameAttribute("cells")]
[XmlAttributeAttribute(false)]
[ContainmentAttribute()]
[XmlOppositeAttribute("owner")]
[ConstantAttribute()]
IOrderedSetExpression<ICell> Cells
{
get;
}
/// <summary>
/// Gets fired before the Owner property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> OwnerChanging;
/// <summary>
/// Gets fired when the Owner property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> OwnerChanged;
}
}
| 31.244186 | 99 | 0.628582 | [
"MIT"
] | Benjaminrivard/ttc2019-tt2bdd | solutions/NMF/Metamodels/TruthTables/IRow.cs | 2,689 | C# |
namespace IDisposableAnalyzers.NetCoreTests.IDISP005ReturnTypeShouldBeIDisposableTests
{
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
public static class Valid
{
private static readonly DiagnosticAnalyzer Analyzer = new ReturnValueAnalyzer();
private static readonly DiagnosticDescriptor Descriptor = Descriptors.IDISP005ReturnTypeShouldBeIDisposable;
[Test]
public static void LocalDisposeAsync()
{
var code = @"
namespace N
{
using System;
using System.IO;
public class C
{
public IAsyncDisposable M() => File.OpenRead(string.Empty);
}
}";
RoslynAssert.Valid(Analyzer, Descriptor, code);
}
}
}
| 25.125 | 116 | 0.68408 | [
"MIT"
] | AraHaan/IDisposableAnalyzers | IDisposableAnalyzers.NetCoreTests/IDISP005ReturnTypeShouldBeIDisposableTests/Valid.cs | 806 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HouseBuilderWithSyntax.cs" company="bbv Software Services AG">
// Copyright (c) 2014 - 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
// Defines the HouseBuilderWithSyntax type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CleanCode.Testing.Sample.Builder
{
using System.Drawing;
using CleanCode.Testing.Sample.SameImplementation;
public class HouseBuilderWithSyntax : ICreateHouseSyntax, IWithFrontDoorSyntax, IWithWindowSyntax, IBuildHouseSyntax
{
private const int LengthInMeters = 30;
private const int WidthInMeters = 12;
private const double DefaultDoorHeightInMeters = 2.1d;
private const double DefaultDoorWidthInMeters = 1.2d;
private const double DefaultFloorHeightInMeters = 2.4d;
private const double DefaultRoofSizeInSquareMeters = LengthInMeters * WidthInMeters;
private readonly House house;
private Floor newestFloor;
private Room newestRoom;
private HouseBuilderWithSyntax()
{
this.house = new House(WidthInMeters, LengthInMeters)
{
Roof = new Roof { Color = Color.Red, Size = DefaultRoofSizeInSquareMeters },
FacadeColor = Color.Gray,
FrontDoor = new FrontDoor
{
Color = Color.Gray,
Width = DefaultDoorWidthInMeters,
Height = DefaultDoorHeightInMeters
}
};
}
public static IWithFrontDoorSyntax Create()
{
return new HouseBuilderWithSyntax();
}
public IWithFrontDoorSyntax CreateHouse()
{
return new HouseBuilderWithSyntax();
}
public IWithFloorSyntax WithFrontDoorOfColor(Color frontDoorColor)
{
this.house.FrontDoor.Color = frontDoorColor;
return this;
}
public IWithRoomSyntax AddFloor()
{
int nextFloorLevel = this.house.Floors.Count;
var newFloor = new Floor(nextFloorLevel, DefaultFloorHeightInMeters);
this.house.AddFloor(newFloor);
this.newestFloor = newFloor;
return this;
}
public IWithWindowSyntax AddRoom()
{
var newRoom = new Room();
this.newestFloor.AddRoom(newRoom);
this.newestRoom = newRoom;
return this;
}
public IWithWindowSyntax WithRoom(Room room)
{
this.newestFloor.AddRoom(room);
return this;
}
public IBuildHouseSyntax WithRoomHavingWindowsQuantityOf(int numberOfWindowsInRoom)
{
var newRoom = new Room();
for (int i = 0; i < numberOfWindowsInRoom; i++)
{
newRoom.AddWindow(new Window());
}
this.newestFloor.AddRoom(newRoom);
return this;
}
public IBuildHouseSyntax AddWindowWithBorderColor(Color borderColor)
{
var window = new Window { BorderColor = borderColor };
this.newestRoom.AddWindow(window);
return this;
}
public IBuildHouseSyntax WithWindow(Window window)
{
this.newestRoom.AddWindow(window);
return this;
}
public House Build()
{
return this.house;
}
}
} | 30.164286 | 120 | 0.570211 | [
"Apache-2.0"
] | bbvch-academy/CleanCode.Academy | source/Testing.Sample/5 Builder with Syntax Sample/Builder/HouseBuilderWithSyntax.cs | 4,225 | C# |
using System;
using System.Linq;
using System.Reactive.Linq;
using ReactiveProperty;
namespace ReactiveViewModels
{
public partial class ReactiveTestViewModel : IReactiveProperty
{
private const string _answer = "Answer to the Ultimate Question of Life, the Universe, and Everything";
private const string _button = @"Push ""Update Text"" to update";
[ReactiveProperty(PropertyName = "Text")]
private string _textField = _button;
[ReactiveProperty(PropertyName = "Count")]
private int _countField = 40;
public ReactiveTestViewModel()
{
AddToDisposeBag(Changed
.Where(p => p == "Count")
.Select(_ => _countField)
.Subscribe(c =>
{
if (c == 42)
{
_textField = _answer;
}
else
{
_textField = _button;
}
}));
}
}
} | 28.621622 | 111 | 0.502361 | [
"MIT"
] | b-straub/BlazorSourceGeneratorTests | ReactiveViewModels/ReactiveTestViewModel.cs | 1,061 | C# |
using Entitas;
namespace FineGameDesign.Entitas
{
public sealed class PetriGameSystems : Feature
{
public PetriGameSystems(Contexts contexts)
{
Add(new TransmissionSystem(contexts));
}
}
}
| 18.307692 | 50 | 0.638655 | [
"MIT"
] | ethankennerly/digestion-defense | DigestionDefense/Assets/Sources/Logic/Features/PetriGameSystems.cs | 238 | C# |
using System;
using System.IO;
using Functional.Maybe;
using JetBrains.Annotations;
namespace Tauron.Temp
{
[PublicAPI]
public sealed class TempStorage : TempDic
{
private static TempStorage? _default;
public TempStorage()
: this(Path.GetRandomFileName, Path.GetTempPath(), false)
{
}
public TempStorage(Func<string> nameProvider, string basePath, bool deleteBasePath)
: base(basePath, Maybe<ITempDic>.Nothing, nameProvider, deleteBasePath)
{
WireUp();
}
public static TempStorage Default => _default ??= new TempStorage();
public static TempStorage CleanAndCreate(string path)
{
path.ClearDirectory();
return new TempStorage(Path.GetRandomFileName, path, true);
}
private void WireUp()
=> AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
private void OnProcessExit(object? sender, EventArgs e)
{
try
{
Dispose();
}
catch
{
//Ignored Due to Process Exit
}
}
protected override void DisposeCore(bool disposing)
{
if (_default == this)
_default = null;
base.DisposeCore(disposing);
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
}
}
} | 26.2 | 91 | 0.565579 | [
"MIT"
] | augustoproiete-bot/Project-Manager-Akka | Tauron.Application.Common/Temp/TempStorage.cs | 1,443 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rn.Mailer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rn.Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d5259147-abeb-4b87-8486-66ccb3156772")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.361111 | 85 | 0.729906 | [
"Apache-2.0"
] | rncode/Rn.Mailer | src/Rn.Mailer/Properties/AssemblyInfo.cs | 1,384 | C# |
/*
* FactSet Estimates Report Builder
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.FactSetEstimatesReportBuilder.Client.OpenAPIDateConverter;
namespace FactSet.SDK.FactSetEstimatesReportBuilder.Model
{
/// <summary>
/// ErrorObject
/// </summary>
[DataContract(Name = "ErrorObject")]
public partial class ErrorObject : IEquatable<ErrorObject>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ErrorObject" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="code">code.</param>
/// <param name="title">title.</param>
/// <param name="links">links.</param>
/// <param name="detail">detail.</param>
/// <param name="source">source.</param>
public ErrorObject(string id = default(string), string code = default(string), string title = default(string), ErrorObjectLinks links = default(ErrorObjectLinks), string detail = default(string), ErrorObjectSource source = default(ErrorObjectSource))
{
this.Id = id;
this.Code = code;
this.Title = title;
this.Links = links;
this.Detail = detail;
this.Source = source;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Code
/// </summary>
[DataMember(Name = "code", EmitDefaultValue = false)]
public string Code { get; set; }
/// <summary>
/// Gets or Sets Title
/// </summary>
[DataMember(Name = "title", EmitDefaultValue = false)]
public string Title { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name = "links", EmitDefaultValue = false)]
public ErrorObjectLinks Links { get; set; }
/// <summary>
/// Gets or Sets Detail
/// </summary>
[DataMember(Name = "detail", EmitDefaultValue = false)]
public string Detail { get; set; }
/// <summary>
/// Gets or Sets Source
/// </summary>
[DataMember(Name = "source", EmitDefaultValue = false)]
public ErrorObjectSource Source { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class ErrorObject {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Title: ").Append(Title).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" Detail: ").Append(Detail).Append("\n");
sb.Append(" Source: ").Append(Source).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ErrorObject);
}
/// <summary>
/// Returns true if ErrorObject instances are equal
/// </summary>
/// <param name="input">Instance of ErrorObject to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ErrorObject input)
{
if (input == null)
{
return false;
}
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Code == input.Code ||
(this.Code != null &&
this.Code.Equals(input.Code))
) &&
(
this.Title == input.Title ||
(this.Title != null &&
this.Title.Equals(input.Title))
) &&
(
this.Links == input.Links ||
(this.Links != null &&
this.Links.Equals(input.Links))
) &&
(
this.Detail == input.Detail ||
(this.Detail != null &&
this.Detail.Equals(input.Detail))
) &&
(
this.Source == input.Source ||
(this.Source != null &&
this.Source.Equals(input.Source))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
{
hashCode = (hashCode * 59) + this.Id.GetHashCode();
}
if (this.Code != null)
{
hashCode = (hashCode * 59) + this.Code.GetHashCode();
}
if (this.Title != null)
{
hashCode = (hashCode * 59) + this.Title.GetHashCode();
}
if (this.Links != null)
{
hashCode = (hashCode * 59) + this.Links.GetHashCode();
}
if (this.Detail != null)
{
hashCode = (hashCode * 59) + this.Detail.GetHashCode();
}
if (this.Source != null)
{
hashCode = (hashCode * 59) + this.Source.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 34.383562 | 258 | 0.507703 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/FactSetEstimatesReportBuilder/v1/src/FactSet.SDK.FactSetEstimatesReportBuilder/Model/ErrorObject.cs | 7,530 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.RDS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.RDS.Model.Internal.MarshallTransformations
{
/// <summary>
/// Describe D B Subnet Groups Request Marshaller
/// </summary>
public class DescribeDBSubnetGroupsRequestMarshaller : IMarshaller<IRequest, DescribeDBSubnetGroupsRequest>
{
public IRequest Marshall(DescribeDBSubnetGroupsRequest describeDBSubnetGroupsRequest)
{
IRequest request = new DefaultRequest(describeDBSubnetGroupsRequest, "AmazonRDS");
request.Parameters.Add("Action", "DescribeDBSubnetGroups");
request.Parameters.Add("Version", "2013-09-09");
if (describeDBSubnetGroupsRequest != null && describeDBSubnetGroupsRequest.IsSetDBSubnetGroupName())
{
request.Parameters.Add("DBSubnetGroupName", StringUtils.FromString(describeDBSubnetGroupsRequest.DBSubnetGroupName));
}
if (describeDBSubnetGroupsRequest != null)
{
List<Filter> filtersList = describeDBSubnetGroupsRequest.Filters;
int filtersListIndex = 1;
foreach (Filter filtersListValue in filtersList)
{
if (filtersListValue != null && filtersListValue.IsSetFilterName())
{
request.Parameters.Add("Filters.member." + filtersListIndex + ".FilterName", StringUtils.FromString(filtersListValue.FilterName));
}
if (filtersListValue != null)
{
List<string> filterValueList = filtersListValue.FilterValue;
int filterValueListIndex = 1;
foreach (string filterValueListValue in filterValueList)
{
request.Parameters.Add("Filters.member." + filtersListIndex + ".FilterValue.member." + filterValueListIndex, StringUtils.FromString(filterValueListValue));
filterValueListIndex++;
}
}
filtersListIndex++;
}
}
if (describeDBSubnetGroupsRequest != null && describeDBSubnetGroupsRequest.IsSetMaxRecords())
{
request.Parameters.Add("MaxRecords", StringUtils.FromInt(describeDBSubnetGroupsRequest.MaxRecords));
}
if (describeDBSubnetGroupsRequest != null && describeDBSubnetGroupsRequest.IsSetMarker())
{
request.Parameters.Add("Marker", StringUtils.FromString(describeDBSubnetGroupsRequest.Marker));
}
return request;
}
}
}
| 43.320988 | 183 | 0.634654 | [
"Apache-2.0"
] | jdluzen/aws-sdk-net-android | AWSSDK/Amazon.RDS/Model/Internal/MarshallTransformations/DescribeDBSubnetGroupsRequestMarshaller.cs | 3,509 | C# |
namespace NaCl.Core
{
using System;
using System.Security.Cryptography;
using Base;
using Internal;
/// <summary>
/// A stream cipher based on https://download.libsodium.org/doc/advanced/xchacha20.html and https://tools.ietf.org/html/draft-arciszewski-xchacha-02.
///
/// This cipher is meant to be used to construct an AEAD with Poly1305.
/// </summary>
/// <seealso cref="NaCl.Core.Base.ChaCha20Base" />
public class XChaCha20 : ChaCha20Base
{
public const int NONCE_SIZE_IN_BYTES = 24;
/// <summary>
/// Initializes a new instance of the <see cref="XChaCha20"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="initialCounter">The initial counter.</param>
public XChaCha20(ReadOnlyMemory<byte> key, int initialCounter) : base(key, initialCounter) { }
/// <inheritdoc />
protected override void SetInitialState(Span<uint> state, ReadOnlySpan<byte> nonce, int counter)
{
if (nonce.IsEmpty || nonce.Length != NonceSizeInBytes)
throw new CryptographicException(FormatNonceLengthExceptionMessage(GetType().Name, nonce.Length, NonceSizeInBytes));
// The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574.
SetSigma(state);
// The next eight words (4-11) are taken from the 256-bit key in little-endian order, in 4-byte chunks; and the first 16 bytes of the 24-byte nonce to obtain the subKey.
Span<byte> subKey = stackalloc byte[KEY_SIZE_IN_BYTES];
HChaCha20(subKey, nonce);
SetKey(state, subKey);
// Word 12 is a block counter.
state[12] = (uint)counter;
// Word 13 is a prefix of 4 null bytes, since RFC 8439 specifies a 12-byte nonce.
state[13] = 0;
// Words 14-15 are the remaining 8-byte nonce (used in HChaCha20). Ref: https://tools.ietf.org/html/draft-arciszewski-xchacha-01#section-2.3.
state[14] = ArrayUtils.LoadUInt32LittleEndian(nonce, 16);
state[15] = ArrayUtils.LoadUInt32LittleEndian(nonce, 20);
}
/// <summary>
/// The size of the nonce in bytes.
/// </summary>
/// <returns>System.Int32.</returns>
public override int NonceSizeInBytes => NONCE_SIZE_IN_BYTES;
}
}
| 42.62069 | 182 | 0.614887 | [
"MIT"
] | idaviddesmet/NaCl.Core | src/NaCl.Core/XChaCha20.cs | 2,474 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Airline.FleetInfoBot.Web.Helper
{
public class Constants
{
public const string ShowAirCraftDetails = "Show me aircraft details";
public const string Rebook = "Rebook the passenger";
public const string Assignaircraft = "Assign the new aircraft";
public const string MarkGrounded = "MarkGrounded";
public const string Available = "Available";
}
} | 30.875 | 77 | 0.710526 | [
"MIT"
] | Bhaskers-Blu-Org2/msteams-sample-line-of-business-apps-csharp | Airline/FleetInfoBot/Helper/Constants.cs | 496 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/appnotify.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
public static unsafe partial class Windows
{
[DllImport("twinapi.appcore.dll", ExactSpelling = true)]
[return: NativeTypeName("ULONG")]
public static extern uint RegisterAppStateChangeNotification([NativeTypeName("PAPPSTATE_CHANGE_ROUTINE")] delegate* unmanaged<byte, void*, void> Routine, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("PAPPSTATE_REGISTRATION *")] IntPtr* Registration);
[DllImport("twinapi.appcore.dll", ExactSpelling = true)]
public static extern void UnregisterAppStateChangeNotification([NativeTypeName("PAPPSTATE_REGISTRATION")] IntPtr Registration);
[DllImport("twinapi.appcore.dll", ExactSpelling = true)]
[return: NativeTypeName("ULONG")]
public static extern uint RegisterAppConstrainedChangeNotification([NativeTypeName("PAPPCONSTRAIN_CHANGE_ROUTINE")] delegate* unmanaged<byte, void*, void> Routine, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("PAPPCONSTRAIN_REGISTRATION *")] IntPtr* Registration);
[DllImport("twinapi.appcore.dll", ExactSpelling = true)]
public static extern void UnregisterAppConstrainedChangeNotification([NativeTypeName("PAPPCONSTRAIN_REGISTRATION")] IntPtr Registration);
}
}
| 57.678571 | 284 | 0.757895 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/appnotify/Windows.cs | 1,617 | C# |
using System.Text;
using Bing.Utils.Extensions;
namespace Bing.Domains.Repositories
{
/// <summary>
/// 分页参数
/// </summary>
public class Pager : IPager
{
#region 构造函数
/// <summary>
/// 初始化一个<see cref="Pager"/>类型的实例
/// </summary>
public Pager() : this(1)
{
}
/// <summary>
/// 初始化一个<see cref="Pager"/>类型的实例
/// </summary>
/// <param name="page">页索引</param>
/// <param name="pageSize">每页显示行数,默认20</param>
/// <param name="order">排序条件</param>
public Pager(int page, int pageSize, string order) : this(page, pageSize, 0, order)
{
}
/// <summary>
/// 初始化一个<see cref="Pager"/>类型的实例
/// </summary>
/// <param name="page">页索引</param>
/// <param name="pageSize">每页显示行数,默认20</param>
/// <param name="totalCount">总行数</param>
/// <param name="order">排序条件</param>
public Pager(int page, int pageSize = 20, int totalCount = 0, string order = "")
{
Page = page;
PageSize = pageSize;
TotalCount = totalCount;
Order = order;
}
#endregion
/// <summary>
/// 页索引,级第几页,从1开始
/// </summary>
private int _pageIndex;
/// <summary>
/// 描述
/// </summary>
private StringBuilder _description;
/// <summary>
/// 页索引,即第几页,从1开始
/// </summary>
public int Page
{
get
{
if (_pageIndex <= 0)
_pageIndex = 1;
return _pageIndex;
}
set => _pageIndex = value;
}
/// <summary>
/// 每页显示行数
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// 总行数
/// </summary>
public int TotalCount { get; set; }
/// <summary>
/// 排序条件
/// </summary>
public string Order { get; set; }
/// <summary>
/// 获取总页数
/// </summary>
public int GetPageCount()
{
if ((TotalCount % PageSize) == 0)
return TotalCount / PageSize;
return (TotalCount / PageSize) + 1;
}
/// <summary>
/// 获取跳过的行数
/// </summary>
public int GetSkipCount() => PageSize * (Page - 1);
/// <summary>
/// 获取起始行数
/// </summary>
public int GetStartNumber() => (Page - 1) * PageSize + 1;
/// <summary>
/// 获取结束行数
/// </summary>
public int GetEndNumber() => Page * PageSize;
/// <summary>
/// 重写 生成字符串
/// </summary>
public override string ToString()
{
_description = new StringBuilder();
AddDescriptions();
return _description.ToString().TrimEnd().TrimEnd(',');
}
/// <summary>
/// 添加描述
/// </summary>
protected virtual void AddDescriptions()
{
AddDescription("Page", Page);
AddDescription("PageSize", PageSize);
AddDescription("Order", Order);
}
/// <summary>
/// 添加描述
/// </summary>
/// <param name="description">描述</param>
protected void AddDescription(string description)
{
if (string.IsNullOrWhiteSpace(description))
return;
_description.Append(description);
}
/// <summary>
/// 添加描述
/// </summary>
/// <typeparam name="TValue">值类型</typeparam>
/// <param name="name">属性名</param>
/// <param name="value">属性值</param>
protected void AddDescription<TValue>(string name, TValue value)
{
if (string.IsNullOrWhiteSpace(value.SafeString()))
return;
_description.AppendFormat("{0}:{1},", name, value);
}
}
}
| 25.341772 | 91 | 0.461538 | [
"MIT"
] | Alean-singleDog/Bing.NetCore | src/Bing/Domains/Repositories/Pager.cs | 4,338 | C# |
using System;
using System.Collections.Generic;
using GloomChars.GameData.Interfaces;
namespace GloomChars.GameData.Models
{
public class PerkBuilder
{
private Perk _perk { get; set; }
public PerkBuilder(string id, int qty)
{
_perk = new Perk(id, qty);
}
public static PerkBuilder Create(string id, int qty)
{
return new PerkBuilder(id, qty);
}
public PerkBuilder AddCard(int numCards, CardAction cardAction, int? actionAmnt, int dmg, bool draw)
{
var card = new ModifierCard(dmg, cardAction, actionAmnt, draw, false);
var perkAction = new AddCard { NumCards = numCards, Card = card };
_perk.Actions.Add(perkAction);
return this;
}
public PerkBuilder AddCard(int numCards, CardAction cardAction, int dmg, bool draw) =>
this.AddCard(numCards, cardAction, null, dmg, draw);
public PerkBuilder RemoveCard(int numCards, CardAction cardAction, int? actionAmnt, int dmg, bool draw)
{
var card = new ModifierCard(dmg, cardAction, actionAmnt, draw, false);
var perkAction = new RemoveCard { NumCards = numCards, Card = card };
_perk.Actions.Add(perkAction);
return this;
}
public PerkBuilder RemoveCard(int numCards, CardAction cardAction, int dmg, bool draw) =>
this.RemoveCard(numCards, cardAction, null, dmg, draw);
public PerkBuilder IgnoreItems()
{
var perkAction = new IgnoreItemEffects();
_perk.Actions.Add(perkAction);
return this;
}
public PerkBuilder IgnoreScenario()
{
var perkAction = new IgnoreScenarioEffects();
_perk.Actions.Add(perkAction);
return this;
}
public Perk Build()
{
return _perk;
}
}
}
| 29.149254 | 111 | 0.592422 | [
"Unlicense"
] | Yend0r/gloomhaven-api-csharp | src/GloomChars.GameData/Services/PerkBuilder.cs | 1,955 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GbxRemoteNet.Structs {
public class ForcedMods {
public bool Override;
public ForcedMods[] Mods;
}
}
| 19.461538 | 33 | 0.719368 | [
"Apache-2.0"
] | reaby/GbxRemote.Net | GbxRemote.Net/Structs/ForcedMods.cs | 255 | C# |
namespace Reportr.Filtering
{
using System.ComponentModel;
/// <summary>
/// Defines input types for parameter values
/// </summary>
public enum ParameterInputType
{
[Description("Text")]
Text = 0,
[Description("Whole Number")]
WholeNumber = 1,
[Description("Decimal Number")]
DecimalNumber = 2,
[Description("Boolean")]
Boolean = 4,
[Description("Date")]
Date = 8,
[Description("Time")]
Time = 16,
[Description("Color")]
Color = 32,
[Description("Single Select Lookup")]
SingleSelectLookup = 64,
[Description("Multi Select Lookup")]
MultiSelectLookup = 128
}
}
| 19.578947 | 48 | 0.545699 | [
"MIT"
] | JTOne123/Reportr | src/Reportr/Filtering/ParameterInputType.cs | 746 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyHpBar : MonoBehaviour {
private Slider hpSlider;
private Enemy enemy;
private int maxHp;
// Use this for initialization
void Start () {
enemy = transform.parent.parent.GetComponent<Enemy>();
hpSlider = GetComponent<Slider>();
maxHp = enemy.getMaxHp();
}
// Update is called once per frame
void Update () {
if (hpSlider.value > (enemy.getCurrentHp() * hpSlider.maxValue) / maxHp )
hpSlider.value -= 10;
if (hpSlider.value < (enemy.getCurrentHp() * hpSlider.maxValue) / maxHp)
hpSlider.value += 10;
}
}
| 25 | 81 | 0.64 | [
"MIT"
] | satokibi/houti_dungeon | Assets/Scripts/Enemy/EnemyHpBar.cs | 727 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ForgedOnce.TsLanguageServices.FullSyntaxTree.AstBuilder
{
public static partial class StCatchClauseExtensions
{
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause WithVariableDeclaration(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause subject, Func<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StVariableDeclaration, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StVariableDeclaration> variableDeclarationBuilder)
{
subject.variableDeclaration = variableDeclarationBuilder(new ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StVariableDeclaration());
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause WithBlock(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause subject, Func<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StBlock, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StBlock> blockBuilder)
{
subject.block = blockBuilder(new ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StBlock());
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause WithFlags(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause subject, ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel.NodeFlags flags)
{
subject.flags = flags;
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause WithDecorator(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause subject, Func<ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator> decoratorBuilder)
{
subject.decorators.Add(decoratorBuilder(new ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StDecorator()));
return subject;
}
public static ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause WithModifier(this ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.StCatchClause subject, ForgedOnce.TsLanguageServices.FullSyntaxTree.AstModel.IStModifier modifier)
{
subject.modifiers.Add(modifier);
return subject;
}
}
} | 64.897436 | 383 | 0.780719 | [
"MIT"
] | YevgenNabokov/ForgedOnce.TSLanguageServices | ForgedOnce.TsLanguageServices.FullSyntaxTree/AstBuilder/Generated/StCatchClauseExtensions.cs | 2,531 | C# |
using Informapp.InformSystem.WebApi.Models.Http;
using Informapp.InformSystem.WebApi.Models.Requests;
using Informapp.InformSystem.WebApi.Models.Responses;
using Informapp.InformSystem.WebApi.Models.Version1.Constants;
using Informapp.InformSystem.WebApi.Models.Version1.Errors;
using System.Net;
using System.Runtime.Serialization;
namespace Informapp.InformSystem.WebApi.Models.Version1.EndPoints.Tests.Methods.GetMethod
{
/// <summary>
/// Get method request
/// </summary>
[DataContract(Namespace = Version1Constants.Namespace)]
[HttpMethod(HttpMethod.Get)]
[Path(MethodV1Constants.GetRoute)]
[Response(HttpStatusCode.BadRequest, typeof(BadRequestV1Response))]
[Response(HttpStatusCode.Forbidden, typeof(ForbiddenV1Response))]
[Response(HttpStatusCode.InternalServerError, typeof(InternalServerErrorV1Response))]
[Response(HttpStatusCode.Unauthorized, typeof(UnauthorizedV1Response))]
public class GetMethodV1Request : BaseRequest,
IRequest<GetMethodV1Response>
{
}
}
| 38.333333 | 89 | 0.78744 | [
"MIT"
] | InformappNL/informapp-api-dotnet-client | src/WebApi.Models/Version1/EndPoints/Tests/Methods/GetMethod/GetMethodV1Request.cs | 1,037 | C# |
using System;
using System.Collections.Generic;
namespace Faforever.Qai.Core.Models
{
public class FetchPlayerStatsResult
{
public string Name { get; set; } = default!;
public string Id { get; set; } = default!;
public GameStatistics? LadderStats { get; set; } = null;
public GameStatistics? GlobalStats { get; set; } = null;
public FAFClan? Clan { get; set; } = null;
public List<string> OldNames { get; set; } = new List<string>();
public ReplayData? ReplayData { get; set; } = null;
}
public struct GameStatistics
{
public short Ranking { get; set; }
public decimal Rating { get; set; }
public short GamesPlayed { get; set; }
}
public class FAFClan
{
public string? Name { get; set; }
public int? Size { get; set; }
public string? URL { get; set; }
public DateTime? CreatedDate { get; set; }
public string? Description { get; set; }
public string? Tag { get; set; }
public long? Id { get; set; }
}
public struct ReplayData
{
public int? Team { get; set; }
public int? Score { get; set; }
public string? Faction { get; set; }
}
} | 30.317073 | 72 | 0.576026 | [
"MIT"
] | Crotalus/faf-qai | src/Faforever.Qai.Core/Models/FetchPlayerStatsResult.cs | 1,243 | C# |
[BLToolkitGenerated]
public sealed class TestClass : CounterAspectTest.TestClass
{
private static CallMethodInfo _methodInfo;
private static IInterceptor _interceptor;
public override void TestMethod()
{
if (_methodInfo == null)
{
_methodInfo = new CallMethodInfo((MethodInfo)MethodBase.GetCurrentMethod());
}
InterceptCallInfo info = new InterceptCallInfo();
try
{
info.Object = this;
info.CallMethodInfo = _methodInfo;
info.InterceptResult = InterceptResult.Continue;
info.InterceptType = InterceptType.BeforeCall;
if (_interceptor == null)
{
_interceptor = new CounterAspect();
_interceptor.Init(_methodInfo, null);
}
// 'BeforeCall' creates or gets a counter for the method and
// registers the current call.
// See the [link][file]Aspects/CounterAspect.cs[/file]CounterAspect.BeforeCall[/link] method for details.
//
_interceptor.Intercept(info);
if (info.InterceptResult != InterceptResult.Return)
{
// Target method call.
//
base.TestMethod();
}
}
catch (Exception exception)
{
info.Exception = exception;
info.InterceptResult = InterceptResult.Continue;
info.InterceptType = InterceptType.OnCatch;
// 'OnCatch' is required to count calls with exceptions.
//
_interceptor.Intercept(info);
if (info.InterceptResult != InterceptResult.Return)
{
throw;
}
}
finally
{
info.InterceptResult = InterceptResult.Continue;
info.InterceptType = InterceptType.OnFinally;
// 'OnFinally' step adds statistic to the method counter.
// See the [link][file]Aspects/CounterAspect.cs[/file]CounterAspect.OnFinally[/link] method for details.
//
_interceptor.Intercept(info);
}
}
}
| 26.362319 | 109 | 0.674546 | [
"MIT"
] | igor-tkachev/bltoolkit | Tools/DocGen/Content/Doc/Aspects/CounterAspect.cs | 1,821 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace wechat_hook
{
public class CommandLineArgumentParser
{
List<CommandLineArgument> _arguments;
public static CommandLineArgumentParser Parse(string[] args)
{
return new CommandLineArgumentParser(args);
}
public CommandLineArgumentParser(string[] args)
{
_arguments = new List<CommandLineArgument>();
for (int i = 0; i < args.Length; i++)
{
_arguments.Add(new CommandLineArgument(_arguments, i, args[i]));
}
}
public CommandLineArgument Get(string argumentName)
{
return _arguments.FirstOrDefault(p => p == argumentName);
}
public bool Has(string argumentName)
{
return _arguments.Count(p => p == argumentName) > 0;
}
}
public class CommandLineArgument
{
List<CommandLineArgument> _arguments;
int _index;
string _argumentText;
public CommandLineArgument Next
{
get
{
if (_index < _arguments.Count - 1)
{
return _arguments[_index + 1];
}
return null;
}
}
public CommandLineArgument Previous
{
get
{
if (_index > 0)
{
return _arguments[_index - 1];
}
return null;
}
}
internal CommandLineArgument(List<CommandLineArgument> args, int index, string argument)
{
_arguments = args;
_index = index;
_argumentText = argument;
}
public CommandLineArgument Take()
{
return Next;
}
public IEnumerable<CommandLineArgument> Take(int count)
{
var list = new List<CommandLineArgument>();
var parent = this;
for (int i = 0; i < count; i++)
{
var next = parent.Next;
if (next == null)
break;
list.Add(next);
parent = next;
}
return list;
}
public static implicit operator string(CommandLineArgument argument)
{
return argument._argumentText;
}
public override string ToString()
{
return _argumentText;
}
}
}
| 23.351351 | 96 | 0.493827 | [
"MIT"
] | Alioth1017/wechat-hook | wechat-hook/CommandLineArgumentParser.cs | 2,594 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using OpenSearch.Net;
namespace Osc
{
public class Snapshot
{
[DataMember(Name ="duration_in_millis")]
public long DurationInMilliseconds { get; internal set; }
[DataMember(Name ="end_time")]
public DateTime EndTime { get; internal set; }
[DataMember(Name ="end_time_in_millis")]
public long EndTimeInMilliseconds { get; internal set; }
[DataMember(Name ="failures")]
public IReadOnlyCollection<SnapshotShardFailure> Failures { get; internal set; }
[DataMember(Name ="indices")]
public IReadOnlyCollection<IndexName> Indices { get; internal set; }
[DataMember(Name ="snapshot")]
public string Name { get; internal set; }
[DataMember(Name ="shards")]
public ShardStatistics Shards { get; internal set; }
[DataMember(Name ="start_time")]
public DateTime StartTime { get; internal set; }
[DataMember(Name ="start_time_in_millis")]
public long StartTimeInMilliseconds { get; internal set; }
[DataMember(Name ="state")]
public string State { get; internal set; }
[DataMember(Name ="metadata")]
public IReadOnlyDictionary<string, object> Metadata { get; internal set; } = EmptyReadOnly<string, object>.Dictionary;
}
}
| 32.802817 | 120 | 0.747102 | [
"Apache-2.0"
] | Bit-Quill/opensearch-net | src/Osc/Modules/SnapshotAndRestore/Snapshot/Snapshot.cs | 2,329 | C# |
using System.Threading.Tasks;
using Unofficial.Owlet.Models.Response;
namespace Unofficial.Owlet.Interfaces
{
/// <summary>
/// Provides access to user-level information of your Owlet account, including authentication tasks.
/// </summary>
public interface IOwletUserApi
{
/// <summary>
/// Perform login event. Login information is persisted for the lifecycle of the <see cref="Unofficial.Owlet.Models.OwletUserSession"/>.
/// </summary>
/// <param name="email">Your Owlet account email</param>
/// <param name="password">Your Owlet account password</param>
/// <returns></returns>
Task<OwletSignInResponse> LoginAsync(string email, string password);
/// <summary>
/// Perform token refresh. Login information is persisted for the lifecycle of the <see cref="Unofficial.Owlet.Models.OwletUserSession"/>.
/// </summary>
/// <param name="refreshToken">From initial login event</param>
/// <returns></returns>
Task<OwletSignInResponse> RefreshLoginAsync(string refreshToken = null);
}
}
| 42.884615 | 146 | 0.667265 | [
"MIT"
] | mitch-b/owlet-api-dotnet | src/Unofficial.Owlet/Interfaces/IOwletUserApi.cs | 1,117 | C# |
// Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using NUnit.Framework;
namespace LfMerge.AutomatedSRTests.Tests
{
[TestFixture]
public class CommentsTests
{
private const string LexemeA =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }";
private const string LexemeB =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] }";
private const string LexemeC =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'C' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'C' } }
} ] }";
private const string LexemeD =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'D' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'D' } }
} ] }";
private const string LexemeE =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'E' } },
'senses' : [ {
'gloss' : { 'en' : { 'value' : 'E' } }
} ] }";
private const string LexemeF =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'F' } },
'senses' : [ {
'gloss' : { 'en' : { 'value' : 'F' } }
} ] }";
private const string LexemeG =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'G' } },
'senses' : [ {
'gloss' : { 'en' : { 'value' : 'G' } }
} ] }";
private const string LexemeH =
// language=json
@"{ 'lexeme': { 'fr' : { 'value' : 'H' } },
'senses' : [ {
'gloss' : { 'en' : { 'value' : 'H' } }
} ] }";
private const string CommentsA_D =
// language=json
@"{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
} }]},
{ 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
} }]},
{ 'class' : 'question',
'ref' : 'C',
'messages': [
{'message' : {
'status': '',
'value': 'Comment about new word C'
} }]},
{ 'class' : 'question',
'ref' : 'D',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word D'
} }]},
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'Comment on A, FW first'
} }]},
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on A, LF second'
} }]}";
private const string CommentE =
// language=json
@"{ 'class' : 'question',
'ref' : 'E',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on E'
} },
{ 'message': {
'status': 'open',
'value': 'LF reply on E'
} },
{ 'message': {
'status': 'open',
'value': 'FW reply on E'
} }
] }";
private const string CommentF =
// language=json
@"{ 'class' : 'question',
'ref' : 'F',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'LF comment on F',
}}, { 'message': {
'status': 'resolved'
}}, { 'message': {
'status': 'open'
}}] }";
private const string CommentG =
// language=json
@"{ 'class' : 'question',
'ref' : 'G',
'messages': [
{ 'message' : {
'status': '',
'value': 'FW comment on G'
}}, { 'message': {
'status': '',
'value': 'FW reply on G'
}}, { 'message': {
'status': 'resolved'
}}
]}";
private LanguageDepotHelper _FieldWorks;
private MongoHelper _LanguageForge;
private WebworkHelper _webwork;
[TestFixtureSetUp]
public void FixtureSetup()
{
TestHelper.SetupFixture("comments-data", "test-comment-sr");
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
TestHelper.TearDownFixture();
}
[SetUp]
public void Setup()
{
TestHelper.InitializeTestEnvironment(out _FieldWorks, out _LanguageForge, out _webwork);
}
[TearDown]
public void TearDown()
{
TestHelper.ShutdownTestEnvironment(_FieldWorks, _LanguageForge, _webwork);
}
/// <summary>
/// TEST 1: FW deletes B while LF adds a comment on B.
///
/// What should happen: B gets deleted (and comment remains but won't be shown in UI).
/// </summary>
[Test]
public void Test01_FwDeletesEntryWhileLfAddsComment([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 3);
_FieldWorks.ApplyReversePatch(dbVersion.ToString(), 3, "FW deletes B");
_webwork.ApplyPatches(dbVersion, 3);
_LanguageForge.RestoreDatabase(dbVersion, 4);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 2: LF deletes A while FW adds a comment on A.
///
/// What should happen: A remains, with a comment on it.
/// </summary>
[Test]
public void Test02_LfDeletesEntryWhileFwAddsComment([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 4);
_webwork.ApplyPatches(dbVersion, 3);
_LanguageForge.RestoreDatabase(dbVersion, 2);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
}}
]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 3/5: FW adds comment on A, LF adds comment on A at the same time. FW does S/R
/// first, then LF does.
///
/// What should happen: Both comments appear.
/// </summary>
/// <remarks>Can we test scenario 5 separately?</remarks>
[Test]
public void Test03_FwAndLfAddCommentOnA_FwSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 11);
_webwork.ApplyPatches(dbVersion, 10);
_LanguageForge.RestoreDatabase(dbVersion, 11);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}, { 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'C',
'messages': [
{'message' : {
'status': '',
'value': 'Comment about new word C'
}}]
}, { 'class' : 'question',
'ref' : 'D',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word D'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on A, LF second'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'Comment on A, FW first'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 4/6: FW adds comment on A, LF adds comment on A at the same time. LF does S/R
/// first, then FW does (and finally LF again).
///
/// What should happen: Both comments appear.
/// </summary>
/// <remarks><p>Can we test scenario 6 separately?</p>
/// <p>Since we don't test S/R of FW here, we start out with the state that LD/FW is in
/// after FW did the S/R, i.e. LD contains both comments, but LF hasn't pulled the
/// changes from FW yet.</p></remarks>
[Test]
public void Test04_FwAndLfAddCommentOnA_LfSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 11);
// apply patch 13 without 11
_webwork.ApplySinglePatch(dbVersion, 13, false);
_webwork.RemoveNodeFromFile("Lexicon.fwstub.ChorusNotes",
"/notes/annotation[message='Comment on A, FW first']",
"Patch 13 without 11 (Add comment on A, LF second)");
_FieldWorks.ApplyPatches(dbVersion, 11);
_FieldWorks.MergeWith(_webwork);
_LanguageForge.RestoreDatabase(dbVersion, 12);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}, { 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'C',
'messages': [
{'message' : {
'status': '',
'value': 'Comment about new word C'
}}]
}, { 'class' : 'question',
'ref' : 'D',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word D'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on A, LF second'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'Comment on A, FW first'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 7: FW adds comment on A, LF adds comment on B. FW does S/R first, then LF does.
///
/// What should happen: Both comments appear.
/// </summary>
[Test]
public void Test07_FwAddsCommentOnA_LfAddsCommentOnB_FwSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 4);
_webwork.ApplyPatches(dbVersion, 3);
_LanguageForge.RestoreDatabase(dbVersion, 4);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 8: FW adds comment on A, LF adds comment on B. LF does S/R first, then FW does
/// (and finally LF again).
///
/// What should happen: Both comments appear.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW did the S/R, i.e. LD contains both comments, but LF hasn't pulled the
/// changes from FW yet.</remarks>
[Test]
public void Test08_FwAddsCommentOnA_LfAddsCommentOnB_LfSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 4);
// apply patch 6 without 4
_webwork.ApplySinglePatch(dbVersion, 6, false);
_webwork.RemoveNodeFromFile("Lexicon.fwstub.ChorusNotes",
"/notes/annotation[message='FW comment on word A']",
"Patch 6 without 4 (Add comment on B)");
_FieldWorks.ApplyPatches(dbVersion, 4);
_FieldWorks.MergeWith(_webwork);
_LanguageForge.RestoreDatabase(dbVersion, 5);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'B',
'messages': [
{'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'A',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 9a: FW adds comment on E, S/R. LF replies. S/R.
///
/// What should happen: LF and FW should see both comments.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW did the S/R.</remarks>
[Test]
public void Test09a_FwAddsCommentOnE_LfReplies([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 17);
_FieldWorks.ApplyPatches(dbVersion, 17);
_LanguageForge.RestoreDatabase(dbVersion, 18);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// NOTE: although Chorus stores a status on every comment when we have replies,
// only the last status determines the overall status of the comment!
var expected = $"[ {{ 'notes': [ {CommentsA_D}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'E',
'messages': [
{'message' : {
'status': '',
'value': 'FW comment on E'
} },
{ 'message': {
'status': 'open',
'value': 'LF reply on E'
} }
] }
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 9b: FW adds comment on E, S/R. LF replies. S/R. FW replies. S/R.
///
/// What should happen: LF and FW should see all three comments.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW did the S/R.</remarks>
[Test]
public void Test09b_FwAddsCommentOnE_LfReplies_FwReplies([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 19);
_LanguageForge.RestoreDatabase(dbVersion, 19);
_FieldWorks.ApplyPatches(dbVersion, 20);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'notes': [ {CommentsA_D}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'E',
'messages': [
{ 'message' : {
'status': '',
'value': 'FW comment on E'
} },
{ 'message': {
'status': 'open',
'value': 'LF reply on E'
} },
{ 'message': {
'status': 'open',
'value': 'FW reply on E'
} }
] }
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 10: LF adds comment on F. S/R. FW marks comment as resolved. S/R.
///
/// What should happen: LF should see new status as resolved.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW made the change and did the S/R.</remarks>
[Test]
public void Test10_LfAddsCommentOnF_FwResolves([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 23);
_LanguageForge.RestoreDatabase(dbVersion, 23);
_FieldWorks.ApplyPatches(dbVersion, 24);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'notes': [ {CommentsA_D}, {CommentE}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'F',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'LF comment on F'
}},
{ 'message': {
'status': 'resolved'
}}
]}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 11: LF adds comment on F. S/R. FW marks comment as resolved. S/R. LF reopens
/// the comment. S/R.
///
/// What should happen: FW should see new status as open.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW made the change and did the S/R.</remarks>
[Test]
public void Test11_LfAddsCommentOnF_FwResolves_LfReopens([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 25);
_LanguageForge.RestoreDatabase(dbVersion, 26);
_FieldWorks.ApplyPatches(dbVersion, 25);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'notes': [ {CommentsA_D}, {CommentE}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'F',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'LF comment on F'
}}, { 'message': {
'status': 'resolved'
}}, { 'message': {
'status': 'open'
}}
] }
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 12: FW adds comment. S/R. FW adds new reply while LF is marking status as
/// resolved; FW does S/R first. LF then does S/R.
///
/// What should happen: LF should see comment as resolved. So should FW.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW made the change and did the S/R.</remarks>
[Test]
public void Test12_FwAddsCommentOnG_FwAddsNewCommentLfResolves_FwSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 29);
_LanguageForge.RestoreDatabase(dbVersion, 30);
_FieldWorks.ApplyPatches(dbVersion, 30);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'notes': [ {CommentsA_D}, {CommentE}, {CommentF}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'G',
'messages': [
{ 'message' : {
'status': '',
'value': 'FW comment on G'
}}, { 'message': {
'status': '',
'value': 'FW reply on G'
}}, { 'message': {
'status': 'resolved'
}}
]}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 14: LF adds comment. S/R. LF adds new comment while FW is marking status as
/// resolved. FW does S/R first. LF then does S/R.
///
/// What should happen: LF should see both comments, status open. So should FW.
/// </summary>
/// <remarks>Since we don't test S/R of FW here, we start out with the state that LD/FW is
/// in after FW made the change and did the S/R.</remarks>
[Test]
public void Test14_LfAddsCommentOnH_LfAddsNewReplyFwResolves_LfSyncsFirst([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_webwork.ApplyPatches(dbVersion, 33);
_LanguageForge.RestoreDatabase(dbVersion, 34);
_FieldWorks.ApplyPatches(dbVersion, 34);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'notes': [ {CommentsA_D}, {CommentE}, {CommentF}, {CommentG}, " +
// language=json
@"{ 'class' : 'question',
'ref' : 'H',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'LF comment on H'
}}, { 'message': {
'status': 'resolved'
}}, { 'message': {
'status': 'open',
'value': 'LF reply on H'
}}
] }
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 21: FW adds an entry C and a comment on C at the same time.
///
/// What should happen: Both the comment and the entry show up.
/// </summary>
[Test]
public void Test21_FwAddsEntryCAndComment([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 7);
_webwork.ApplyPatches(dbVersion, 6);
_LanguageForge.RestoreDatabase(dbVersion, 6);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
// language=json
const string expected = @"[ { 'lexicon': [
{ 'lexeme': { 'fr' : { 'value' : 'B' } },
'senses' : [ {
'definition' : { 'en' : { 'value' : 'B' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'C' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'C' } }
} ] },
{ 'lexeme': { 'fr' : { 'value' : 'A' } },
'senses' : [ {
/* no definition */
'gloss' : { 'en' : { 'value' : 'A' } }
} ] }
]}, { 'notes': [
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{ 'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}, { 'class' : 'question',
'ref' : 'B',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'C',
'messages': [
{ 'message' : {
'status': '',
'value': 'Comment about new word C'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
/// <summary>
/// TEST 22: LF adds an entry D and a comment on D at the same time.
///
/// What should happen: Both the comment and the entry show up.
/// </summary>
[Test]
public void Test22_LfAddsEntryDAndComment([ValueSource(typeof(ModelVersionValue), nameof(ModelVersionValue.GetValues))] int dbVersion)
{
// Setup
_FieldWorks.ApplyPatches(dbVersion, 7);
_webwork.ApplyPatches(dbVersion, 7);
_LanguageForge.RestoreDatabase(dbVersion, 9);
// Exercise
LfMergeHelper.Run($"--project {Settings.DbName} --action=Synchronize");
// Verify
Assert.That(TestHelper.SRState, Is.EqualTo("IDLE"));
var expected = $"[ {{ 'lexicon': [ {LexemeB}, {LexemeC}, {LexemeA}, {LexemeD} ]}}," +
// language=json
@"{ 'notes': [
{ 'class' : 'question',
'ref' : 'A',
'messages': [
{ 'message' : {
'status': '',
'value': 'FW comment on word A'
}}]
}, { 'class' : 'question',
'ref' : 'B',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'Comment on word B'
}}]
}, { 'class' : 'question',
'ref' : 'C',
'messages': [
{ 'message' : {
'status': '',
'value': 'Comment about new word C'
}}]
}, { 'class' : 'question',
'ref' : 'D',
'messages': [
{ 'message' : {
'status': 'open',
'value': 'Comment on word D'
}}]
}
]}]";
VerifyMongo.AssertData(expected);
var expectedXml = JsonToXml.Convert(expected);
VerifyLanguageDepot.AssertFilesContain(expectedXml);
}
}
}
| 27.987526 | 170 | 0.564404 | [
"MIT"
] | TobiasNickelWycliff/lfmerge-autosrtests | LfMerge.AutomatedSRTests/Tests/CommentsTests.cs | 26,924 | C# |
using Apiology.Hal.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Apiology.Hal
{
public class HalModelConfig : IHalModelConfig
{
public string RelativePathBase { get; set; }
public string RequestPathBase { get; set; }
public bool IsRoot { get; set; }
public string Expands { get; set; }
private Dictionary<string, dynamic> _map;
public Dictionary<string, dynamic> ExpandMap
{
get
{
if (_map == null)
{
_map = Expands?.Split(',')?.ToDictionary(i => i, i => null as dynamic);
if (_map == null)
return null;
while (_map.Any(i => i.Key.Contains('.')))
{
var item = _map.FirstOrDefault(i => i.Key.Contains('.'));
_map.Remove(item.Key);
var idx = item.Key.LastIndexOf('.');
string key = item.Key.Substring(0, idx);
string value = item.Key.Substring(idx + 1, item.Key.Length - idx - 1);
if (_map.Any(i => i.Key == key))
{
var target = _map.FirstOrDefault(i => i.Key == key);
(target.Value as Dictionary<string, dynamic>).Add(
value, item.Value as dynamic
);
}
else
{
var dict = new Dictionary<string, dynamic>();
dict.Add(value, item.Value);
_map.Add(key, dict);
}
}
}
return _map;
}
set
{
_map = value;
}
}
public HalModelConfig(HalModelAttribute config)
{
RelativePathBase = config?.RelativePathBase ?? "~/";
}
}
}
| 30.914286 | 94 | 0.422366 | [
"MIT"
] | IsaacSanch/APIology.HAL | src/Apiology.Hal/src/Configuration/HalModelConfig.cs | 2,166 | C# |
namespace MyDownloader.Core.UI
{
partial class Connection
{
/// <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.label1 = new System.Windows.Forms.Label();
this.numRetryDelay = new System.Windows.Forms.NumericUpDown();
this.label6 = new System.Windows.Forms.Label();
this.numMinSegSize = new System.Windows.Forms.NumericUpDown();
this.numMaxRetries = new System.Windows.Forms.NumericUpDown();
this.label3 = new System.Windows.Forms.Label();
this.lblMinSize = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.numMaxSegments = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numRetryDelay)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMinSegSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxRetries)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxSegments)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(-3, 95);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(65, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Retry Delay:";
//
// numRetryDelay
//
this.numRetryDelay.Location = new System.Drawing.Point(0, 112);
this.numRetryDelay.Name = "numRetryDelay";
this.numRetryDelay.Size = new System.Drawing.Size(96, 20);
this.numRetryDelay.TabIndex = 6;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(-3, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(95, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Min Segment Size:";
//
// numMinSegSize
//
this.numMinSegSize.Location = new System.Drawing.Point(0, 17);
this.numMinSegSize.Maximum = new decimal(new int[] {
2147483647,
0,
0,
0});
this.numMinSegSize.Name = "numMinSegSize";
this.numMinSegSize.Size = new System.Drawing.Size(116, 20);
this.numMinSegSize.TabIndex = 1;
this.numMinSegSize.ValueChanged += new System.EventHandler(this.numMinSegSize_ValueChanged);
//
// numMaxRetries
//
this.numMaxRetries.Location = new System.Drawing.Point(0, 160);
this.numMaxRetries.Name = "numMaxRetries";
this.numMaxRetries.Size = new System.Drawing.Size(96, 20);
this.numMaxRetries.TabIndex = 8;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(-3, 143);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(129, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Max Retries (0 for infinite):";
//
// lblMinSize
//
this.lblMinSize.AutoSize = true;
this.lblMinSize.Location = new System.Drawing.Point(122, 19);
this.lblMinSize.Name = "lblMinSize";
this.lblMinSize.Size = new System.Drawing.Size(54, 13);
this.lblMinSize.TabIndex = 2;
this.lblMinSize.Text = "lblMinSize";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(-3, 48);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(80, 13);
this.label5.TabIndex = 3;
this.label5.Text = "Max Segments:";
//
// numMaxSegments
//
this.numMaxSegments.Location = new System.Drawing.Point(0, 65);
this.numMaxSegments.Maximum = new decimal(new int[] {
2147483647,
0,
0,
0});
this.numMaxSegments.Name = "numMaxSegments";
this.numMaxSegments.Size = new System.Drawing.Size(116, 20);
this.numMaxSegments.TabIndex = 4;
//
// Connection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label5);
this.Controls.Add(this.numMaxSegments);
this.Controls.Add(this.numMaxRetries);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Controls.Add(this.lblMinSize);
this.Controls.Add(this.numRetryDelay);
this.Controls.Add(this.label6);
this.Controls.Add(this.numMinSegSize);
this.Name = "Connection";
this.Size = new System.Drawing.Size(363, 282);
((System.ComponentModel.ISupportInitialize)(this.numRetryDelay)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMinSegSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxRetries)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxSegments)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numRetryDelay;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.NumericUpDown numMinSegSize;
private System.Windows.Forms.NumericUpDown numMaxRetries;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lblMinSize;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.NumericUpDown numMaxSegments;
}
}
| 42.48503 | 107 | 0.572516 | [
"MIT"
] | 1alireza32109/NiceHashMiner | src/3rdparty/DownloadManager/MyDownloader.Core/UI/Connection.Designer.cs | 7,095 | C# |
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Options;
using Sentry.Extensibility;
namespace Sentry.Extensions.Logging.Extensions.DependencyInjection;
/// <summary>
/// Extension methods for <see cref="IServiceCollection"/>
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds Sentry's services to the <see cref="IServiceCollection"/>
/// </summary>
/// <param name="services">The services.</param>
public static IServiceCollection AddSentry<TOptions>(this IServiceCollection services)
where TOptions : SentryLoggingOptions, new()
{
services.TryAddSingleton<SentryOptions>(
c => c.GetRequiredService<IOptions<TOptions>>().Value);
services.TryAddTransient<ISentryClient>(c => c.GetRequiredService<IHub>());
services.TryAddTransient(c => c.GetRequiredService<Func<IHub>>()());
services.TryAddSingleton<Func<IHub>>(c =>
{
var options = c.GetRequiredService<IOptions<TOptions>>().Value;
if (options.InitializeSdk)
{
var hub = SentrySdk.InitHub(options);
SentrySdk.UseHub(hub);
}
return () => HubAdapter.Instance;
});
// Custom handler for HttpClientFactory.
// Must be singleton: https://github.com/getsentry/sentry-dotnet/issues/785
services.TryAddSingleton<IHttpMessageHandlerBuilderFilter, SentryHttpMessageHandlerBuilderFilter>();
return services;
}
}
| 34.918367 | 108 | 0.687902 | [
"MIT"
] | TawasalMessenger/sentry-dotnet | src/Sentry.Extensions.Logging/Extensions/DependencyInjection/ServiceCollectionExtensions.cs | 1,711 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using BulletSharp;
using BulletSharp.SoftBody;
using VVVV.Internals.Bullet;
using VVVV.Bullet.Core;
namespace VVVV.Bullet.Core
{
//Just to make it easier to manage than having million of stuff in
//World node. Can also easily switch broadphases
public class BulletSoftWorldContainer : IRigidBulletWorld, ISoftBulletWorld, IConstraintContainer
{
private DefaultCollisionConfiguration collisionConfiguration;
private CollisionDispatcher dispatcher;
private SequentialImpulseConstraintSolver solver;
private BroadphaseInterface overlappingPairCache;
private SoftRigidDynamicsWorld dynamicsWorld;
private SoftBodyWorldInfo worldInfo;
private int softbodyindex;
private int bodyindex;
private int cstindex;
protected bool enabled;
protected float gx, gy, gz;
protected float ts;
protected int iter;
public event RigidBodyDeletedDelegate RigidBodyDeleted;
public event SoftBodyDeletedDelegate SoftBodyDeleted;
public event ConstraintDeletedDelegate ConstraintDeleted;
public event WorldResetDelegate WorldHasReset;
private ObjectLifetimeContainer<RigidBody, BodyCustomData> bodyContainer;
private ObjectLifetimeContainer<SoftBody, SoftBodyCustomData> softBodyContainer;
private ObjectLifetimeContainer<TypedConstraint, ConstraintCustomData> constraintContainer;
public BulletSoftWorldContainer()
{
this.bodyContainer = new ObjectLifetimeContainer<RigidBody, BodyCustomData>(b => (BodyCustomData)b.UserObject);
this.softBodyContainer = new ObjectLifetimeContainer<SoftBody, SoftBodyCustomData>(s => (SoftBodyCustomData)s.UserObject);
this.constraintContainer = new ObjectLifetimeContainer<TypedConstraint, ConstraintCustomData>(c => (ConstraintCustomData)c.UserObject);
}
public Dispatcher Dispatcher
{
get { return this.dispatcher; }
}
#region Rigid Registry
public int GetNewRigidBodyId()
{
this.bodyindex++;
return this.bodyindex;
}
public void Register(RigidBody body)
{
this.World.AddRigidBody(body);
this.bodyContainer.RegisterObject(body);
}
private void RemoveRigidBody(RigidBody body, BodyCustomData cdata)
{
this.dynamicsWorld.DeleteAndDisposeBody(body);
if (this.RigidBodyDeleted != null)
{
this.RigidBodyDeleted(body, cdata.Id);
}
}
public List<RigidBody> RigidBodies
{
get { return this.bodyContainer.ObjectList; }
}
#endregion
#region Soft Registry
public int GetNewSoftBodyId()
{
this.softbodyindex++;
return this.bodyindex;
}
public void Register(SoftBody body)
{
this.dynamicsWorld.AddSoftBody(body);
this.softBodyContainer.RegisterObject(body);
}
private void RemoveSoftBody(SoftBody body, SoftBodyCustomData cdata)
{
this.World.RemoveCollisionObject(body);
body.Dispose();
if (this.SoftBodyDeleted != null)
{
this.SoftBodyDeleted(body, cdata.Id);
}
}
public List<SoftBody> SoftBodies
{
get { return this.softBodyContainer.ObjectList; }
}
#endregion
#region Contraints Registry
public int GetNewConstraintId()
{
this.cstindex++;
return this.cstindex;
}
public void Register(TypedConstraint cst, bool collideconnected)
{
this.World.AddConstraint(cst, !collideconnected);
this.constraintContainer.RegisterObject(cst);
}
public void Register(TypedConstraint cst)
{
this.Register(cst, true);
}
public void RemoveConctraint(TypedConstraint cst, ConstraintCustomData cdata)
{
this.dynamicsWorld.DeleteAndDisposeConstraint(cst);
if (this.ConstraintDeleted != null)
{
this.ConstraintDeleted(cst, cdata.Id);
}
}
public List<TypedConstraint> Constraints
{
get { return this.constraintContainer.ObjectList; }
}
#endregion
#region Creation
private bool created = false;
public bool Created { get { return this.created; } }
public void Create()
{
if (created)
{
this.Destroy();
}
this.bodyindex = 0;
this.cstindex = 0;
this.softbodyindex = 0;
collisionConfiguration = new SoftBodyRigidBodyCollisionConfiguration();
dispatcher = new CollisionDispatcher(collisionConfiguration);
solver = new SequentialImpulseConstraintSolver();
overlappingPairCache = new DbvtBroadphase();
dynamicsWorld = new SoftRigidDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
worldInfo = new SoftBodyWorldInfo();
worldInfo.Gravity = dynamicsWorld.Gravity;
worldInfo.Broadphase = overlappingPairCache;
worldInfo.Dispatcher = dispatcher;
worldInfo.SparseSdf.Initialize();
this.created = true;
if (this.WorldHasReset != null)
{
this.WorldHasReset();
}
}
#endregion
#region Process Deletion
internal void ProcessDelete(double dt)
{
this.bodyContainer.Process(dt, this.RemoveRigidBody);
this.softBodyContainer.Process(dt, this.RemoveSoftBody);
this.constraintContainer.Process(dt, this.RemoveConctraint);
}
#endregion
#region Info
public SoftBodyWorldInfo WorldInfo
{
get { return worldInfo; }
set { worldInfo = value; }
}
public DynamicsWorld World
{
get { return this.dynamicsWorld; }
}
public int ObjectCount
{
get { return this.dynamicsWorld.NumCollisionObjects; }
}
#endregion
#region Gravity/Enabled/Ans Step Stuff
public void SetGravity(float x, float y, float z)
{
this.gx = x;
this.gy = y;
this.gz = z;
this.dynamicsWorld.Gravity = new Vector3(this.gx, this.gy, this.gz);
}
public bool Enabled
{
set { this.enabled = value; }
get { return this.enabled; }
}
public float TimeStep
{
set { this.ts = value; }
}
public int Iterations
{
set { this.iter = value; }
}
public void Step()
{
if (this.enabled)
{
this.dynamicsWorld.StepSimulation(this.ts, this.iter);
}
}
#endregion
#region Destroy
public void Destroy()
{
this.dynamicsWorld.DeleteAndDisposeAllConstraints();
//this.dynamicsWorld.DeleteAndDisposeAllRigidBodies();
for (int i = 0; i < this.dynamicsWorld.NumCollisionObjects; i++)
{
CollisionObject obj = dynamicsWorld.CollisionObjectArray[i];
if (obj is RigidBody)
{
RigidBody body = obj as RigidBody;
dynamicsWorld.DeleteAndDisposeBody(body);
}
else if (obj is SoftBody)
{
SoftBody body = obj as SoftBody;
dynamicsWorld.RemoveSoftBody(body);
body.Dispose();
body.CollisionShape.Dispose();
body.Tag = null;
}
}
dynamicsWorld.Dispose();
solver.Dispose();
overlappingPairCache.Dispose();
dispatcher.Dispose();
collisionConfiguration.Dispose();
this.bodyContainer.Clear();
this.softBodyContainer.Clear();
this.constraintContainer.Clear();
this.created = false;
}
#endregion
}
}
| 26.197232 | 147 | 0.653943 | [
"BSD-3-Clause"
] | laurensrinke/dx11-vvvv | Nodes/VVVV.DX11.Nodes.Bullet/Core/SoftWorldContainer.cs | 7,573 | C# |
using System;
using System.Collections.Generic;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components.UserInterface;
using Robust.Shared.Serialization;
namespace Content.Shared.GameObjects.Components.Access
{
public class SharedIdCardConsoleComponent : Component
{
public override string Name => "IdCardConsole";
public enum UiButton
{
PrivilegedId,
TargetId,
}
[Serializable, NetSerializable]
public class IdButtonPressedMessage : BoundUserInterfaceMessage
{
public readonly UiButton Button;
public IdButtonPressedMessage(UiButton button)
{
Button = button;
}
}
[Serializable, NetSerializable]
public class WriteToTargetIdMessage : BoundUserInterfaceMessage
{
public readonly string FullName;
public readonly string JobTitle;
public readonly List<string> AccessList;
public WriteToTargetIdMessage(string fullName, string jobTitle, List<string> accessList)
{
FullName = fullName;
JobTitle = jobTitle;
AccessList = accessList;
}
}
[Serializable, NetSerializable]
public class IdCardConsoleBoundUserInterfaceState : BoundUserInterfaceState
{
public readonly string PrivilegedIdName;
public readonly bool IsPrivilegedIdPresent;
public readonly bool IsPrivilegedIdAuthorized;
public readonly bool IsTargetIdPresent;
public readonly string TargetIdName;
public readonly string TargetIdFullName;
public readonly string TargetIdJobTitle;
public readonly List<string> TargetIdAccessList;
public IdCardConsoleBoundUserInterfaceState(bool isPrivilegedIdPresent,
bool isPrivilegedIdAuthorized,
bool isTargetIdPresent,
string targetIdFullName,
string targetIdJobTitle,
List<string> targetIdAccessList, string privilegedIdName, string targetIdName)
{
IsPrivilegedIdPresent = isPrivilegedIdPresent;
IsPrivilegedIdAuthorized = isPrivilegedIdAuthorized;
IsTargetIdPresent = isTargetIdPresent;
TargetIdFullName = targetIdFullName;
TargetIdJobTitle = targetIdJobTitle;
TargetIdAccessList = targetIdAccessList;
PrivilegedIdName = privilegedIdName;
TargetIdName = targetIdName;
}
}
[Serializable, NetSerializable]
public enum IdCardConsoleUiKey
{
Key,
}
}
}
| 34.158537 | 100 | 0.625491 | [
"MIT"
] | 4dplanner/space-station-14 | Content.Shared/GameObjects/Components/Access/SharedIdCardConsoleComponent.cs | 2,801 | C# |
using System;
namespace Melanchall.DryWetMidi.Common
{
internal sealed class ParsingResult
{
#region Constants
public static readonly ParsingResult Parsed = new ParsingResult(ParsingStatus.Parsed);
public static readonly ParsingResult EmptyInputString = new ParsingResult(ParsingStatus.EmptyInputString);
public static readonly ParsingResult NotMatched = new ParsingResult(ParsingStatus.NotMatched);
#endregion
#region Fields
private readonly string _error;
#endregion
#region Constructor
private ParsingResult(string error)
: this(ParsingStatus.FormatError, error)
{
}
private ParsingResult(ParsingStatus status)
: this(status, null)
{
}
private ParsingResult(ParsingStatus status, string error)
{
Status = status;
_error = error;
}
#endregion
#region Properties
public ParsingStatus Status { get; }
public Exception Exception
{
get
{
switch (Status)
{
case ParsingStatus.EmptyInputString:
return new ArgumentException("Input string is null or contains white-spaces only.");
case ParsingStatus.NotMatched:
return new FormatException("Input string has invalid format.");
case ParsingStatus.FormatError:
return new FormatException(_error);
}
return null;
}
}
#endregion
#region Methods
public static ParsingResult Error(string error)
{
return new ParsingResult(error);
}
#endregion
}
}
| 24.653333 | 114 | 0.56517 | [
"MIT"
] | Amalgam-Cloud/drywetmidi | DryWetMidi/Common/Parsing/ParsingResult.cs | 1,851 | C# |
using ColossalFramework;
using ColossalFramework.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TrafficManager.Custom.AI;
using TrafficManager.State;
using TrafficManager.Geometry;
using TrafficManager.TrafficLight;
using UnityEngine;
using TrafficManager.Manager;
using TrafficManager.Traffic;
using CSUtil.Commons;
using TrafficManager.Manager.Impl;
using TrafficManager.Geometry.Impl;
using ColossalFramework.UI;
namespace TrafficManager.UI.SubTools {
public class TimedTrafficLightsTool : SubTool {
private readonly GUIStyle _counterStyle = new GUIStyle();
private readonly int[] _hoveredButton = new int[2];
private bool nodeSelectionLocked = false;
private List<ushort> SelectedNodeIds = new List<ushort>();
private bool _cursorInSecondaryPanel;
private Rect _windowRect = TrafficManagerTool.MoveGUI(new Rect(0, 0, 480, 350));
private Rect _windowRect2 = TrafficManagerTool.MoveGUI(new Rect(0, 0, 300, 150));
private bool _timedPanelAdd = false;
private int _timedEditStep = -1;
private ushort _hoveredNode = 0;
private bool _timedShowNumbers = false;
private int _timedViewedStep = -1;
private int _stepMinValue = 1;
private int _stepMaxValue = 1;
private StepChangeMetric _stepMetric = StepChangeMetric.Default;
private float _waitFlowBalance = GlobalConfig.Instance.TimedTrafficLights.FlowToWaitRatio;
private string _stepMinValueStr = "1";
private string _stepMaxValueStr = "1";
private bool timedLightActive = false;
private int currentStep = -1;
private int numSteps = 0;
private bool inTestMode = false;
private ushort nodeIdToCopy = 0;
private HashSet<ushort> currentTimedNodeIds;
private GUIStyle layout = new GUIStyle { normal = { textColor = new Color(1f, 1f, 1f) } };
private GUIStyle layoutRed = new GUIStyle { normal = { textColor = new Color(1f, 0f, 0f) } };
private GUIStyle layoutGreen = new GUIStyle { normal = { textColor = new Color(0f, 1f, 0f) } };
private GUIStyle layoutYellow = new GUIStyle { normal = { textColor = new Color(1f, 1f, 0f) } };
public TimedTrafficLightsTool(TrafficManagerTool mainTool) : base(mainTool) {
currentTimedNodeIds = new HashSet<ushort>();
}
public override bool IsCursorInPanel() {
return base.IsCursorInPanel() || _cursorInSecondaryPanel;
}
private void RefreshCurrentTimedNodeIds(ushort forceNodeId=0) {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
if (forceNodeId == 0) {
currentTimedNodeIds.Clear();
} else {
currentTimedNodeIds.Remove(forceNodeId);
}
for (uint nodeId = (forceNodeId == 0 ? 1u : forceNodeId); nodeId <= (forceNodeId == 0 ? NetManager.MAX_NODE_COUNT - 1 : forceNodeId); ++nodeId) {
if (!Constants.ServiceFactory.NetService.IsNodeValid((ushort)nodeId)) {
continue;
}
if (tlsMan.HasTimedSimulation((ushort)nodeId)) {
currentTimedNodeIds.Add((ushort)nodeId);
}
}
}
public override void OnActivate() {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
RefreshCurrentTimedNodeIds();
nodeSelectionLocked = false;
foreach (ushort nodeId in currentTimedNodeIds) {
if (!Constants.ServiceFactory.NetService.IsNodeValid(nodeId)) {
continue;
}
tlsMan.TrafficLightSimulations[nodeId].Housekeeping();
}
}
public override void OnSecondaryClickOverlay() {
if (!IsCursorInPanel()) {
Cleanup();
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
}
}
public override void OnPrimaryClickOverlay() {
if (HoveredNodeId <= 0 || nodeSelectionLocked)
return;
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
switch (MainTool.GetToolMode()) {
case ToolMode.TimedLightsSelectNode:
case ToolMode.TimedLightsShowLights:
if (MainTool.GetToolMode() == ToolMode.TimedLightsShowLights) {
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
ClearSelectedNodes();
}
if (! tlsMan.HasTimedSimulation(HoveredNodeId)) {
if (IsNodeSelected(HoveredNodeId)) {
RemoveSelectedNode(HoveredNodeId);
} else {
AddSelectedNode(HoveredNodeId);
}
} else {
if (SelectedNodeIds.Count == 0) {
//timedSim.housekeeping();
var timedLight = tlsMan.TrafficLightSimulations[HoveredNodeId].TimedLight;
if (timedLight != null) {
SelectedNodeIds = new List<ushort>(timedLight.NodeGroup);
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
}
} else {
MainTool.ShowTooltip(Translation.GetString("NODE_IS_TIMED_LIGHT"));
}
}
break;
case ToolMode.TimedLightsAddNode:
if (SelectedNodeIds.Count <= 0) {
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
return;
}
if (SelectedNodeIds.Contains(HoveredNodeId))
return;
//bool mayEnterBlocked = Options.mayEnterBlockedJunctions;
ITimedTrafficLights existingTimedLight = null;
foreach (var nodeId in SelectedNodeIds) {
if (!tlsMan.HasTimedSimulation(nodeId)) {
continue;
}
//mayEnterBlocked = timedNode.vehiclesMayEnterBlockedJunctions;
existingTimedLight = tlsMan.TrafficLightSimulations[nodeId].TimedLight;
}
/*if (timedSim2 != null)
timedSim2.housekeeping();*/
ITimedTrafficLights timedLight2 = null;
if (! tlsMan.HasTimedSimulation(HoveredNodeId)) {
var nodeGroup = new List<ushort>();
nodeGroup.Add(HoveredNodeId);
tlsMan.SetUpTimedTrafficLight(HoveredNodeId, nodeGroup);
}
timedLight2 = tlsMan.TrafficLightSimulations[HoveredNodeId].TimedLight;
timedLight2.Join(existingTimedLight);
ClearSelectedNodes();
foreach (ushort nodeId in timedLight2.NodeGroup) {
RefreshCurrentTimedNodeIds(nodeId);
AddSelectedNode(nodeId);
}
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
break;
case ToolMode.TimedLightsRemoveNode:
if (SelectedNodeIds.Count <= 0) {
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
return;
}
if (SelectedNodeIds.Contains(HoveredNodeId)) {
tlsMan.RemoveNodeFromSimulation(HoveredNodeId, false, false);
RefreshCurrentTimedNodeIds(HoveredNodeId);
}
RemoveSelectedNode(HoveredNodeId);
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
break;
case ToolMode.TimedLightsCopyLights:
if (nodeIdToCopy == 0 || !tlsMan.HasTimedSimulation(nodeIdToCopy)) {
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
return;
}
// compare geometry
NodeGeometry sourceNodeGeo = NodeGeometry.Get(nodeIdToCopy);
NodeGeometry targetNodeGeo = NodeGeometry.Get(HoveredNodeId);
if (sourceNodeGeo.NumSegmentEnds != targetNodeGeo.NumSegmentEnds) {
MainTool.ShowTooltip(Translation.GetString("The_chosen_traffic_light_program_is_incompatible_to_this_junction"));
return;
}
// check for existing simulation
if (tlsMan.HasTimedSimulation(HoveredNodeId)) {
MainTool.ShowTooltip(Translation.GetString("NODE_IS_TIMED_LIGHT"));
return;
}
ITimedTrafficLights sourceTimedLights = tlsMan.TrafficLightSimulations[nodeIdToCopy].TimedLight;
// copy `nodeIdToCopy` to `HoveredNodeId`
tlsMan.SetUpTimedTrafficLight(HoveredNodeId, new List<ushort> { HoveredNodeId });
tlsMan.TrafficLightSimulations[HoveredNodeId].TimedLight.PasteSteps(sourceTimedLights);
RefreshCurrentTimedNodeIds(HoveredNodeId);
Cleanup();
AddSelectedNode(HoveredNodeId);
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
break;
}
}
public override void OnToolGUI(Event e) {
base.OnToolGUI(e);
switch (MainTool.GetToolMode()) {
case ToolMode.TimedLightsSelectNode:
_guiTimedTrafficLightsNode();
break;
case ToolMode.TimedLightsShowLights:
case ToolMode.TimedLightsAddNode:
case ToolMode.TimedLightsRemoveNode:
_guiTimedTrafficLights();
break;
case ToolMode.TimedLightsCopyLights:
_guiTimedTrafficLightsCopy();
break;
}
}
public override void RenderOverlay(RenderManager.CameraInfo cameraInfo) {
bool onlySelected = MainTool.GetToolMode() == ToolMode.TimedLightsRemoveNode;
//Log._Debug($"nodeSelLocked={nodeSelectionLocked} HoveredNodeId={HoveredNodeId} IsNodeSelected={IsNodeSelected(HoveredNodeId)} onlySelected={onlySelected} isinsideui={MainTool.GetToolController().IsInsideUI} cursorVis={Cursor.visible}");
if (!nodeSelectionLocked &&
HoveredNodeId != 0 &&
(!IsNodeSelected(HoveredNodeId) ^ onlySelected) &&
!MainTool.GetToolController().IsInsideUI &&
Cursor.visible &&
Flags.mayHaveTrafficLight(HoveredNodeId)
) {
MainTool.DrawNodeCircle(cameraInfo, HoveredNodeId, false, false);
}
if (SelectedNodeIds.Count <= 0) return;
foreach (var index in SelectedNodeIds) {
MainTool.DrawNodeCircle(cameraInfo, index, true, false);
}
}
private void _guiTimedControlPanel(int num) {
//Log._Debug("guiTimedControlPanel");
try {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
if (MainTool.GetToolMode() == ToolMode.TimedLightsAddNode || MainTool.GetToolMode() == ToolMode.TimedLightsRemoveNode) {
GUILayout.Label(Translation.GetString("Select_junction"));
if (GUILayout.Button(Translation.GetString("Cancel"))) {
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
} else {
DragWindow(ref _windowRect);
return;
}
}
if (! tlsMan.HasTimedSimulation(SelectedNodeIds[0])) {
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
//Log._Debug("nodesim or timednodemain is null");
DragWindow(ref _windowRect);
return;
}
var timedNodeMain = tlsMan.TrafficLightSimulations[SelectedNodeIds[0]].TimedLight;
if (Event.current.type == EventType.Layout) {
timedLightActive = tlsMan.HasActiveTimedSimulation(SelectedNodeIds[0]);
currentStep = timedNodeMain.CurrentStep;
inTestMode = timedNodeMain.IsInTestMode();
numSteps = timedNodeMain.NumSteps();
}
if (!timedLightActive && numSteps > 0 && !_timedPanelAdd && _timedEditStep < 0 && _timedViewedStep < 0) {
_timedViewedStep = 0;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.GetStep(_timedViewedStep).UpdateLiveLights(true);
}
}
for (var i = 0; i < timedNodeMain.NumSteps(); i++) {
GUILayout.BeginHorizontal();
if (_timedEditStep != i) {
if (timedLightActive) {
if (i == currentStep) {
GUILayout.BeginVertical();
GUILayout.Space(5);
String labelStr = Translation.GetString("State") + " " + (i + 1) + ": (" + Translation.GetString("min/max") + ")" + timedNodeMain.GetStep(i).MinTimeRemaining() + "/" + timedNodeMain.GetStep(i).MaxTimeRemaining();
float flow = Single.NaN;
float wait = Single.NaN;
if (inTestMode) {
try {
timedNodeMain.GetStep(timedNodeMain.CurrentStep).CalcWaitFlow(true, timedNodeMain.CurrentStep, out wait, out flow);
} catch (Exception e) {
Log.Warning("calcWaitFlow in UI: This is not thread-safe: " + e.ToString());
}
} else {
wait = timedNodeMain.GetStep(i).CurrentWait;
flow = timedNodeMain.GetStep(i).CurrentFlow;
}
if (!Single.IsNaN(flow) && !Single.IsNaN(wait))
labelStr += " " + Translation.GetString("avg._flow") + ": " + String.Format("{0:0.##}", flow) + " " + Translation.GetString("avg._wait") + ": " + String.Format("{0:0.##}", wait);
GUIStyle labelLayout = layout;
if (inTestMode && !Single.IsNaN(wait) && !Single.IsNaN(flow)) {
float metric;
if (timedNodeMain.GetStep(i).ShouldGoToNextStep(flow, wait, out metric))
labelLayout = layoutRed;
else
labelLayout = layoutGreen;
} else {
bool inEndTransition = false;
try {
inEndTransition = timedNodeMain.GetStep(i).IsInEndTransition();
} catch (Exception e) {
Log.Error("Error while determining if timed traffic light is in end transition: " + e.ToString());
}
labelLayout = inEndTransition ? layoutYellow : layoutGreen;
}
GUILayout.Label(labelStr, labelLayout);
GUILayout.Space(5);
GUILayout.EndVertical();
if (GUILayout.Button(Translation.GetString("Skip"), GUILayout.Width(80))) {
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.SkipStep();
}
}
} else {
GUILayout.Label(Translation.GetString("State") + " " + (i + 1) + ": " + timedNodeMain.GetStep(i).MinTime + " - " + timedNodeMain.GetStep(i).MaxTime, layout);
}
} else {
GUIStyle labelLayout = layout;
if (_timedViewedStep == i) {
labelLayout = layoutGreen;
}
GUILayout.Label(Translation.GetString("State") + " " + (i + 1) + ": " + timedNodeMain.GetStep(i).MinTime + " - " + timedNodeMain.GetStep(i).MaxTime, labelLayout);
if (_timedEditStep < 0) {
GUILayout.BeginHorizontal(GUILayout.Width(100));
if (i > 0) {
if (GUILayout.Button(Translation.GetString("up"), GUILayout.Width(48))) {
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.MoveStep(i, i - 1);
}
_timedViewedStep = i - 1;
}
} else {
GUILayout.Space(50);
}
if (i < numSteps - 1) {
if (GUILayout.Button(Translation.GetString("down"), GUILayout.Width(48))) {
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.MoveStep(i, i + 1);
}
_timedViewedStep = i + 1;
}
} else {
GUILayout.Space(50);
}
GUILayout.EndHorizontal();
if (GUILayout.Button(Translation.GetString("View"), GUILayout.Width(70))) {
_timedPanelAdd = false;
_timedViewedStep = i;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.GetStep(i).UpdateLiveLights(true);
}
}
if (GUILayout.Button(Translation.GetString("Edit"), GUILayout.Width(65))) {
_timedPanelAdd = false;
_timedEditStep = i;
_timedViewedStep = -1;
_stepMinValue = timedNodeMain.GetStep(i).MinTime;
_stepMaxValue = timedNodeMain.GetStep(i).MaxTime;
_stepMetric = timedNodeMain.GetStep(i).ChangeMetric;
_waitFlowBalance = timedNodeMain.GetStep(i).WaitFlowBalance;
_stepMinValueStr = _stepMinValue.ToString();
_stepMaxValueStr = _stepMaxValue.ToString();
nodeSelectionLocked = true;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.GetStep(i).UpdateLiveLights(true);
}
}
if (GUILayout.Button(Translation.GetString("Delete"), GUILayout.Width(70))) {
_timedPanelAdd = false;
_timedViewedStep = -1;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.RemoveStep(i);
}
}
}
}
} else {
nodeSelectionLocked = true;
int oldStepMinValue = _stepMinValue;
int oldStepMaxValue = _stepMaxValue;
// Editing step
GUILayout.Label(Translation.GetString("Min._Time:"), GUILayout.Width(75));
_stepMinValueStr = GUILayout.TextField(_stepMinValueStr, GUILayout.Height(20));
if (!Int32.TryParse(_stepMinValueStr, out _stepMinValue))
_stepMinValue = oldStepMinValue;
GUILayout.Label(Translation.GetString("Max._Time:"), GUILayout.Width(75));
_stepMaxValueStr = GUILayout.TextField(_stepMaxValueStr, GUILayout.Height(20));
if (!Int32.TryParse(_stepMaxValueStr, out _stepMaxValue))
_stepMaxValue = oldStepMaxValue;
if (GUILayout.Button(Translation.GetString("Save"), GUILayout.Width(70))) {
if (_stepMinValue < 0)
_stepMinValue = 0;
if (_stepMaxValue <= 0)
_stepMaxValue = 1;
if (_stepMaxValue < _stepMinValue)
_stepMaxValue = _stepMinValue;
if (_waitFlowBalance <= 0)
_waitFlowBalance = GlobalConfig.Instance.TimedTrafficLights.FlowToWaitRatio;
foreach (var nodeId in SelectedNodeIds) {
var step = tlsMan.TrafficLightSimulations[nodeId].TimedLight?.GetStep(_timedEditStep);
if (step != null) {
step.MinTime = _stepMinValue;
step.MaxTime = _stepMaxValue;
step.ChangeMetric = _stepMetric;
step.WaitFlowBalance = _waitFlowBalance;
step.UpdateLights();
}
}
_timedViewedStep = _timedEditStep;
_timedEditStep = -1;
nodeSelectionLocked = false;
}
GUILayout.EndHorizontal();
BuildStepChangeMetricDisplay(true);
BuildFlowPolicyDisplay(true);
GUILayout.BeginHorizontal();
}
GUILayout.EndHorizontal();
} // foreach step
GUILayout.BeginHorizontal();
if (_timedEditStep < 0 && !timedLightActive) {
if (_timedPanelAdd) {
nodeSelectionLocked = true;
// new step
int oldStepMinValue = _stepMinValue;
int oldStepMaxValue = _stepMaxValue;
GUILayout.Label(Translation.GetString("Min._Time:"), GUILayout.Width(65));
_stepMinValueStr = GUILayout.TextField(_stepMinValueStr, GUILayout.Height(20));
if (!Int32.TryParse(_stepMinValueStr, out _stepMinValue))
_stepMinValue = oldStepMinValue;
GUILayout.Label(Translation.GetString("Max._Time:"), GUILayout.Width(65));
_stepMaxValueStr = GUILayout.TextField(_stepMaxValueStr, GUILayout.Height(20));
if (!Int32.TryParse(_stepMaxValueStr, out _stepMaxValue))
_stepMaxValue = oldStepMaxValue;
if (GUILayout.Button(Translation.GetString("Add"), GUILayout.Width(70))) {
TrafficManagerTool.ShowAdvisor(this.GetType().Name + "_AddStep");
if (_stepMinValue < 0)
_stepMinValue = 0;
if (_stepMaxValue <= 0)
_stepMaxValue = 1;
if (_stepMaxValue < _stepMinValue)
_stepMaxValue = _stepMinValue;
if (_waitFlowBalance <= 0)
_waitFlowBalance = 1f;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.AddStep(_stepMinValue, _stepMaxValue, _stepMetric, _waitFlowBalance);
}
_timedPanelAdd = false;
_timedViewedStep = timedNodeMain.NumSteps() - 1;
}
if (GUILayout.Button("X", GUILayout.Width(22))) {
_timedPanelAdd = false;
}
GUILayout.EndHorizontal();
BuildStepChangeMetricDisplay(true);
BuildFlowPolicyDisplay(true);
GUILayout.BeginHorizontal();
} else {
if (_timedEditStep < 0) {
if (GUILayout.Button(Translation.GetString("Add_step"))) {
TrafficManagerTool.ShowAdvisor(this.GetType().Name + "_AddStep");
_timedPanelAdd = true;
nodeSelectionLocked = true;
_timedViewedStep = -1;
_timedEditStep = -1;
_stepMetric = StepChangeMetric.Default;
}
}
}
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
if (numSteps > 1 && _timedEditStep < 0) {
if (timedLightActive) {
if (GUILayout.Button(_timedShowNumbers ? Translation.GetString("Hide_counters") : Translation.GetString("Show_counters"))) {
_timedShowNumbers = !_timedShowNumbers;
}
if (GUILayout.Button(Translation.GetString("Stop"))) {
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.Stop();
}
}
/*bool isInTestMode = false;
foreach (var sim in SelectedNodeIndexes.Select(tlsMan.GetNodeSimulation)) {
if (sim.TimedLight.IsInTestMode()) {
isInTestMode = true;
break;
}
}*/
var curStep = timedNodeMain.CurrentStep;
ITimedTrafficLightsStep currentStep = timedNodeMain.GetStep(curStep);
_stepMetric = currentStep.ChangeMetric;
if (currentStep.MaxTime > currentStep.MinTime) {
BuildStepChangeMetricDisplay(false);
}
_waitFlowBalance = timedNodeMain.GetStep(curStep).WaitFlowBalance;
BuildFlowPolicyDisplay(inTestMode);
foreach (var nodeId in SelectedNodeIds) {
var step = tlsMan.TrafficLightSimulations[nodeId].TimedLight?.GetStep(curStep);
if (step != null) {
step.WaitFlowBalance = _waitFlowBalance;
}
}
//var mayEnterIfBlocked = GUILayout.Toggle(timedNodeMain.vehiclesMayEnterBlockedJunctions, Translation.GetString("Vehicles_may_enter_blocked_junctions"), new GUILayoutOption[] { });
var testMode = GUILayout.Toggle(inTestMode, Translation.GetString("Enable_test_mode_(stay_in_current_step)"), new GUILayoutOption[] { });
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.SetTestMode(testMode);
}
} else {
if (_timedEditStep < 0 && !_timedPanelAdd) {
if (GUILayout.Button(Translation.GetString("Start"))) {
_timedPanelAdd = false;
nodeSelectionLocked = false;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.TrafficLightSimulations[nodeId].TimedLight?.Start();
}
}
}
}
}
if (_timedEditStep >= 0) {
DragWindow(ref _windowRect);
return;
}
GUILayout.Space(30);
if (SelectedNodeIds.Count == 1 && timedNodeMain.NumSteps() > 0) {
GUILayout.BeginHorizontal();
if (GUILayout.Button(Translation.GetString("Rotate_left"))) {
timedNodeMain.RotateLeft();
_timedViewedStep = 0;
}
if (GUILayout.Button(Translation.GetString("Copy"))) {
TrafficManagerTool.ShowAdvisor(this.GetType().Name + "_Copy");
nodeIdToCopy = SelectedNodeIds[0];
MainTool.SetToolMode(ToolMode.TimedLightsCopyLights);
}
if (GUILayout.Button(Translation.GetString("Rotate_right"))) {
timedNodeMain.RotateRight();
_timedViewedStep = 0;
}
GUILayout.EndHorizontal();
}
if (!timedLightActive) {
GUILayout.Space(30);
if (GUILayout.Button(Translation.GetString("Add_junction_to_timed_light"))) {
TrafficManagerTool.ShowAdvisor(this.GetType().Name + "_AddJunction");
MainTool.SetToolMode(ToolMode.TimedLightsAddNode);
}
if (SelectedNodeIds.Count > 1) {
if (GUILayout.Button(Translation.GetString("Remove_junction_from_timed_light"))) {
TrafficManagerTool.ShowAdvisor(this.GetType().Name + "_RemoveJunction");
MainTool.SetToolMode(ToolMode.TimedLightsRemoveNode);
}
}
GUILayout.Space(30);
if (GUILayout.Button(Translation.GetString("Remove_timed_traffic_light"))) {
DisableTimed();
ClearSelectedNodes();
MainTool.SetToolMode(ToolMode.TimedLightsSelectNode);
}
}
DragWindow(ref _windowRect);
} catch (Exception e) {
Log.Error($"TimedTrafficLightsTool._guiTimedControlPanel: {e}");
}
}
public override void Cleanup() {
SelectedNodeId = 0;
ClearSelectedNodes();
_timedShowNumbers = false;
_timedPanelAdd = false;
_timedEditStep = -1;
_hoveredNode = 0;
_timedShowNumbers = false;
_timedViewedStep = -1;
timedLightActive = false;
nodeIdToCopy = 0;
}
public override void Initialize() {
base.Initialize();
Cleanup();
if (Options.timedLightsOverlay) {
RefreshCurrentTimedNodeIds();
} else {
currentTimedNodeIds.Clear();
}
}
private void BuildStepChangeMetricDisplay(bool editable) {
GUILayout.BeginVertical();
if (editable) {
GUILayout.Label(Translation.GetString("After_min._time_has_elapsed_switch_to_next_step_if") + ":");
if (GUILayout.Toggle(_stepMetric == StepChangeMetric.Default, GetStepChangeMetricDescription(StepChangeMetric.Default))) {
_stepMetric = StepChangeMetric.Default;
}
if (GUILayout.Toggle(_stepMetric == StepChangeMetric.FirstFlow, GetStepChangeMetricDescription(StepChangeMetric.FirstFlow))) {
_stepMetric = StepChangeMetric.FirstFlow;
}
if (GUILayout.Toggle(_stepMetric == StepChangeMetric.FirstWait, GetStepChangeMetricDescription(StepChangeMetric.FirstWait))) {
_stepMetric = StepChangeMetric.FirstWait;
}
if (GUILayout.Toggle(_stepMetric == StepChangeMetric.NoFlow, GetStepChangeMetricDescription(StepChangeMetric.NoFlow))) {
_stepMetric = StepChangeMetric.NoFlow;
}
if (GUILayout.Toggle(_stepMetric == StepChangeMetric.NoWait, GetStepChangeMetricDescription(StepChangeMetric.NoWait))) {
_stepMetric = StepChangeMetric.NoWait;
}
} else {
GUILayout.Label(Translation.GetString("Adaptive_step_switching") + ": " + GetStepChangeMetricDescription(_stepMetric));
}
GUILayout.EndVertical();
}
private void BuildFlowPolicyDisplay(bool editable) {
string formatStr;
if (_waitFlowBalance < 0.01f)
formatStr = "{0:0.###}";
else if (_waitFlowBalance < 0.1f)
formatStr = "{0:0.##}";
else
formatStr = "{0:0.#}";
GUILayout.BeginHorizontal();
if (editable) {
GUILayout.Label(Translation.GetString("Sensitivity") + " (" + String.Format(formatStr, _waitFlowBalance) + ", " + getWaitFlowBalanceInfo() + "):");
if (_waitFlowBalance <= 0.01f) {
if (_waitFlowBalance >= 0) {
if (GUILayout.Button("-.001")) {
_waitFlowBalance -= 0.001f;
}
}
if (_waitFlowBalance < 0.01f) {
if (GUILayout.Button("+.001")) {
_waitFlowBalance += 0.001f;
}
}
} else if (_waitFlowBalance <= 0.1f) {
if (GUILayout.Button("-.01")) {
_waitFlowBalance -= 0.01f;
}
if (_waitFlowBalance < 0.1f) {
if (GUILayout.Button("+.01")) {
_waitFlowBalance += 0.01f;
}
}
}
if (_waitFlowBalance < 0)
_waitFlowBalance = 0;
if (_waitFlowBalance > 10)
_waitFlowBalance = 10;
GUILayout.EndHorizontal();
_waitFlowBalance = GUILayout.HorizontalSlider(_waitFlowBalance, 0.001f, 10f);
// step snapping
if (_waitFlowBalance < 0.001f) {
_waitFlowBalance = 0.001f;
} else if (_waitFlowBalance < 0.01f) {
_waitFlowBalance = Mathf.Round(_waitFlowBalance * 1000f) * 0.001f;
} else if (_waitFlowBalance < 0.1f) {
_waitFlowBalance = Mathf.Round(_waitFlowBalance * 100f) * 0.01f;
} else if (_waitFlowBalance < 10f) {
_waitFlowBalance = Mathf.Round(_waitFlowBalance * 10f) * 0.1f;
} else {
_waitFlowBalance = 10f;
}
GUILayout.BeginHorizontal();
GUIStyle style = new GUIStyle();
style.normal.textColor = Color.white;
style.alignment = TextAnchor.LowerLeft;
GUILayout.Label(Translation.GetString("Low"), style, new GUILayoutOption[] { GUILayout.Height(10) });
style.alignment = TextAnchor.LowerRight;
GUILayout.Label(Translation.GetString("High"), style, new GUILayoutOption[] { GUILayout.Height(10) });
} else {
GUILayout.Label(Translation.GetString("Sensitivity") + ": " + String.Format(formatStr, _waitFlowBalance) + " (" + getWaitFlowBalanceInfo() + ")");
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
}
private string GetStepChangeMetricDescription(StepChangeMetric metric) {
switch (metric) {
case StepChangeMetric.Default:
default:
return Translation.GetString("flow_ratio") + " < " + Translation.GetString("wait_ratio") + " (" + Translation.GetString("default") + ")";
case StepChangeMetric.FirstFlow:
return Translation.GetString("flow_ratio") + " > 0";
case StepChangeMetric.FirstWait:
return Translation.GetString("wait_ratio") + " > 0";
case StepChangeMetric.NoFlow:
return Translation.GetString("flow_ratio") + " = 0";
case StepChangeMetric.NoWait:
return Translation.GetString("wait_ratio") + " = 0";
}
}
private void _guiTimedTrafficLightsNode() {
_cursorInSecondaryPanel = false;
_windowRect2 = GUILayout.Window(252, _windowRect2, _guiTimedTrafficLightsNodeWindow, Translation.GetString("Select_nodes_windowTitle"), WindowStyle);
_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
}
private void _guiTimedTrafficLights() {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
CustomSegmentLightsManager customTrafficLightsManager = CustomSegmentLightsManager.Instance;
TrafficPriorityManager prioMan = TrafficPriorityManager.Instance;
_cursorInSecondaryPanel = false;
_windowRect = GUILayout.Window(253, _windowRect, _guiTimedControlPanel, Translation.GetString("Timed_traffic_lights_manager"), WindowStyle);
_cursorInSecondaryPanel = _windowRect.Contains(Event.current.mousePosition);
GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(1, 1, 1)); // revert scaling
ShowGUI();
}
private void _guiTimedTrafficLightsCopy() {
_cursorInSecondaryPanel = false;
_windowRect2 = GUILayout.Window(255, _windowRect2, _guiTimedTrafficLightsPasteWindow, Translation.GetString("Paste"), WindowStyle);
_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
}
private void _guiTimedTrafficLightsPasteWindow(int num) {
GUILayout.Label(Translation.GetString("Select_junction"));
}
private void _guiTimedTrafficLightsNodeWindow(int num) {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
if (SelectedNodeIds.Count < 1) {
GUILayout.Label(Translation.GetString("Select_nodes"));
} else {
var txt = SelectedNodeIds.Aggregate("", (current, t) => current + (Translation.GetString("Node") + " " + t + "\n"));
GUILayout.Label(txt);
if (SelectedNodeIds.Count > 0 && GUILayout.Button(Translation.GetString("Deselect_all_nodes"))) {
ClearSelectedNodes();
}
if (!GUILayout.Button(Translation.GetString("Setup_timed_traffic_light"))) return;
_waitFlowBalance = GlobalConfig.Instance.TimedTrafficLights.FlowToWaitRatio;
foreach (var nodeId in SelectedNodeIds) {
tlsMan.SetUpTimedTrafficLight(nodeId, SelectedNodeIds);
RefreshCurrentTimedNodeIds(nodeId);
}
MainTool.SetToolMode(ToolMode.TimedLightsShowLights);
}
DragWindow(ref _windowRect2);
}
private string getWaitFlowBalanceInfo() {
if (_waitFlowBalance < 0.1f) {
return Translation.GetString("Extreme_long_green/red_phases");
} else if (_waitFlowBalance < 0.5f) {
return Translation.GetString("Very_long_green/red_phases");
} else if (_waitFlowBalance < 0.75f) {
return Translation.GetString("Long_green/red_phases");
} else if (_waitFlowBalance < 1.25f) {
return Translation.GetString("Moderate_green/red_phases");
} else if (_waitFlowBalance < 1.5f) {
return Translation.GetString("Short_green/red_phases");
} else if (_waitFlowBalance < 2.5f) {
return Translation.GetString("Very_short_green/red_phases");
} else {
return Translation.GetString("Extreme_short_green/red_phases");
}
}
private void DisableTimed() {
if (SelectedNodeIds.Count <= 0) return;
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
foreach (var selectedNodeId in SelectedNodeIds) {
tlsMan.RemoveNodeFromSimulation(selectedNodeId, true, false);
RefreshCurrentTimedNodeIds(selectedNodeId);
}
}
private void AddSelectedNode(ushort node) {
SelectedNodeIds.Add(node);
}
private bool IsNodeSelected(ushort node) {
return SelectedNodeIds.Contains(node);
}
private void RemoveSelectedNode(ushort node) {
SelectedNodeIds.Remove(node);
}
private void ClearSelectedNodes() {
SelectedNodeIds.Clear();
}
private void drawStraightLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightStraightTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightStraightTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowLightStraightTexture2D);
break;
}
}
private void drawForwardLeftLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightForwardLeftTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightForwardLeftTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowLightForwardLeftTexture2D);
break;
}
}
private void drawForwardRightLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightForwardRightTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightForwardRightTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowLightForwardRightTexture2D);
break;
}
}
private void drawLeftLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightLeftTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightLeftTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowLightLeftTexture2D);
break;
}
}
private void drawRightLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightRightTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightRightTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowLightRightTexture2D);
break;
}
}
private void drawMainLightTexture(RoadBaseAI.TrafficLightState state, Rect rect) {
switch (state) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(rect, TextureResources.GreenLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
GUI.DrawTexture(rect, TextureResources.YellowLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(rect, TextureResources.RedLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.RedToGreen:
GUI.DrawTexture(rect, TextureResources.YellowRedLightTexture2D);
break;
}
}
public override void ShowGUIOverlay(ToolMode toolMode, bool viewOnly) {
if (! ToolMode.TimedLightsShowLights.Equals(toolMode)) {
// TODO refactor timed light related tool modes to sub tool modes
return;
}
if (viewOnly && !Options.timedLightsOverlay)
return;
Vector3 camPos = Singleton<SimulationManager>.instance.m_simulationView.m_position;
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
foreach (ushort nodeId in currentTimedNodeIds) {
if (!Constants.ServiceFactory.NetService.IsNodeValid((ushort)nodeId)) {
continue;
}
if (SelectedNodeIds.Contains((ushort)nodeId)) {
continue;
}
if (tlsMan.HasTimedSimulation((ushort)nodeId)) {
ITimedTrafficLights timedNode = tlsMan.TrafficLightSimulations[nodeId].TimedLight;
var nodePos = Singleton<NetManager>.instance.m_nodes.m_buffer[nodeId].m_position;
Texture2D tex = timedNode.IsStarted() ? (timedNode.IsInTestMode() ? TextureResources.ClockTestTexture2D : TextureResources.ClockPlayTexture2D) : TextureResources.ClockPauseTexture2D;
MainTool.DrawGenericSquareOverlayTexture(tex, camPos, nodePos, 120f, false);
}
}
}
private void ShowGUI() {
TrafficLightSimulationManager tlsMan = TrafficLightSimulationManager.Instance;
CustomSegmentLightsManager customTrafficLightsManager = CustomSegmentLightsManager.Instance;
JunctionRestrictionsManager junctionRestrictionsManager = JunctionRestrictionsManager.Instance;
var hoveredSegment = false;
foreach (var nodeId in SelectedNodeIds) {
if (!tlsMan.HasTimedSimulation(nodeId)) {
continue;
}
ITimedTrafficLights timedNode = tlsMan.TrafficLightSimulations[nodeId].TimedLight;
var nodePos = Singleton<NetManager>.instance.m_nodes.m_buffer[nodeId].m_position;
Vector3 nodeScreenPos;
bool nodeVisible = MainTool.WorldToScreenPoint(nodePos, out nodeScreenPos);
if (!nodeVisible)
continue;
var diff = nodePos - Camera.main.transform.position;
var zoom = 1.0f / diff.magnitude * 100f * MainTool.GetBaseZoom();
NodeGeometry nodeGeometry = NodeGeometry.Get(nodeId);
foreach (SegmentEndGeometry end in nodeGeometry.SegmentEndGeometries) {
if (end == null)
continue;
ushort srcSegmentId = end.SegmentId; // source segment
ICustomSegmentLights liveSegmentLights = customTrafficLightsManager.GetSegmentLights(srcSegmentId, end.StartNode, false);
if (liveSegmentLights == null)
continue;
bool showPedLight = liveSegmentLights.PedestrianLightState != null && junctionRestrictionsManager.IsPedestrianCrossingAllowed(liveSegmentLights.SegmentId, liveSegmentLights.StartNode);
var timedActive = timedNode.IsStarted();
if (! timedActive) {
liveSegmentLights.MakeRedOrGreen();
}
var offset = 17f;
Vector3 segmentLightPos = nodePos;
if (Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_startNode == nodeId) {
segmentLightPos.x += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_startDirection.x * offset;
segmentLightPos.y += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_startDirection.y;
segmentLightPos.z += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_startDirection.z * offset;
} else {
segmentLightPos.x += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_endDirection.x * offset;
segmentLightPos.y += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_endDirection.y;
segmentLightPos.z += Singleton<NetManager>.instance.m_segments.m_buffer[srcSegmentId].m_endDirection.z * offset;
}
Vector3 screenPos;
bool segmentLightVisible = MainTool.WorldToScreenPoint(segmentLightPos, out screenPos);
if (!segmentLightVisible)
continue;
var guiColor = GUI.color;
var manualPedestrianWidth = 36f * zoom;
var manualPedestrianHeight = 35f * zoom;
var pedestrianWidth = 36f * zoom;
var pedestrianHeight = 61f * zoom;
// original / 2.5
var lightWidth = 41f * zoom;
var lightHeight = 97f * zoom;
// SWITCH MODE BUTTON
var modeWidth = 41f * zoom;
var modeHeight = 38f * zoom;
if (showPedLight) {
// pedestrian light
// SWITCH MANUAL PEDESTRIAN LIGHT BUTTON
if (!timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId &&
(_hoveredButton[1] == 1 || _hoveredButton[1] == 2) &&
_hoveredNode == nodeId);
GUI.color = guiColor;
var myRect2 = new Rect(screenPos.x - manualPedestrianWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0) + 5f * zoom,
screenPos.y - manualPedestrianHeight / 2 - 9f * zoom, manualPedestrianWidth,
manualPedestrianHeight);
GUI.DrawTexture(myRect2, liveSegmentLights.ManualPedestrianMode ? TextureResources.PedestrianModeManualTexture2D : TextureResources.PedestrianModeAutomaticTexture2D);
if (myRect2.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 1;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked()) {
liveSegmentLights.ManualPedestrianMode = !liveSegmentLights.ManualPedestrianMode;
}
}
}
// SWITCH PEDESTRIAN LIGHT
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 2 && _hoveredNode == nodeId);
GUI.color = guiColor;
var myRect3 = new Rect(screenPos.x - pedestrianWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0) + 5f * zoom, screenPos.y - pedestrianHeight / 2 + 22f * zoom, pedestrianWidth, pedestrianHeight);
switch (liveSegmentLights.PedestrianLightState) {
case RoadBaseAI.TrafficLightState.Green:
GUI.DrawTexture(myRect3, TextureResources.PedestrianGreenLightTexture2D);
break;
case RoadBaseAI.TrafficLightState.Red:
default:
GUI.DrawTexture(myRect3, TextureResources.PedestrianRedLightTexture2D);
break;
}
if (myRect3.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 2;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
if (!liveSegmentLights.ManualPedestrianMode) {
liveSegmentLights.ManualPedestrianMode = true;
} else {
liveSegmentLights.ChangeLightPedestrian();
}
}
}
}
int lightOffset = -1;
foreach (ExtVehicleType vehicleType in liveSegmentLights.VehicleTypes) {
HashSet<byte> laneIndices = new HashSet<byte>();
for (byte laneIndex = 0; laneIndex < liveSegmentLights.VehicleTypeByLaneIndex.Length; ++laneIndex) {
if (liveSegmentLights.VehicleTypeByLaneIndex[laneIndex] == vehicleType) {
laneIndices.Add(laneIndex);
}
}
//Log._Debug($"Traffic light @ seg. {srcSegmentId} node {nodeId}. Lane indices for vehicleType {vehicleType}: {string.Join(",", laneIndices.Select(x => x.ToString()).ToArray())}");
++lightOffset;
ICustomSegmentLight liveSegmentLight = liveSegmentLights.GetCustomLight(vehicleType);
Vector3 offsetScreenPos = screenPos;
offsetScreenPos.y -= (lightHeight + 10f * zoom) * lightOffset;
if (!timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == -1 &&
_hoveredNode == nodeId);
GUI.color = guiColor;
var myRect1 = new Rect(offsetScreenPos.x - modeWidth / 2,
offsetScreenPos.y - modeHeight / 2 + modeHeight - 7f * zoom, modeWidth, modeHeight);
GUI.DrawTexture(myRect1, TextureResources.LightModeTexture2D);
if (myRect1.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = -1;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked()) {
liveSegmentLight.ToggleMode();
timedNode.ChangeLightMode(srcSegmentId, vehicleType, liveSegmentLight.CurrentMode);
}
}
}
if (vehicleType != ExtVehicleType.None) {
// Info sign
var infoWidth = 56.125f * zoom;
var infoHeight = 51.375f * zoom;
int numInfos = 0;
for (int k = 0; k < TrafficManagerTool.InfoSignsToDisplay.Length; ++k) {
if ((TrafficManagerTool.InfoSignsToDisplay[k] & vehicleType) == ExtVehicleType.None)
continue;
var infoRect = new Rect(offsetScreenPos.x + modeWidth / 2f + 7f * zoom * (float)(numInfos + 1) + infoWidth * (float)numInfos, offsetScreenPos.y - infoHeight / 2f, infoWidth, infoHeight);
guiColor.a = MainTool.GetHandleAlpha(false);
GUI.DrawTexture(infoRect, TextureResources.VehicleInfoSignTextures[TrafficManagerTool.InfoSignsToDisplay[k]]);
++numInfos;
}
}
// Draw light index
/*if (!timedActive && _timedEditStep < 0 && lightOffset == 0) {
var indexSize = 20f * zoom;
var yOffset = indexSize + 77f * zoom - modeHeight * 2;
//var carNumRect = new Rect(offsetScreenPos.x, offsetScreenPos.y - yOffset, counterSize, counterSize);
var segIndexRect = new Rect(offsetScreenPos.x, offsetScreenPos.y - yOffset - indexSize - 2f, indexSize, indexSize);
_counterStyle.fontSize = (int)(15f * zoom);
_counterStyle.normal.textColor = new Color(0f, 0f, 1f);
GUI.Label(segIndexRect, $"#{liveSegmentLight.ClockwiseIndex+1}", _counterStyle);
}*/
#if DEBUG
if (timedActive /*&& _timedShowNumbers*/) {
//var prioSeg = TrafficPriorityManager.Instance.GetPrioritySegment(nodeId, srcSegmentId);
var counterSize = 20f * zoom;
var yOffset = counterSize + 77f * zoom - modeHeight * 2;
//var carNumRect = new Rect(offsetScreenPos.x, offsetScreenPos.y - yOffset, counterSize, counterSize);
var segIdRect = new Rect(offsetScreenPos.x, offsetScreenPos.y - yOffset - counterSize - 2f, counterSize, counterSize);
_counterStyle.fontSize = (int)(15f * zoom);
_counterStyle.normal.textColor = new Color(1f, 0f, 0f);
/*String labelStr = "n/a";
if (prioSeg != null) {
labelStr = prioSeg.GetRegisteredVehicleCount(laneIndices).ToString() + " " + Translation.GetString("incoming");
}
GUI.Label(carNumRect, labelStr, _counterStyle);*/
_counterStyle.normal.textColor = new Color(1f, 0f, 0f);
GUI.Label(segIdRect, Translation.GetString("Segment") + " " + srcSegmentId, _counterStyle);
}
#endif
if (lightOffset == 0 && showPedLight) {
// PEDESTRIAN COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 3);
float numOffset;
if (liveSegmentLights.PedestrianLightState == RoadBaseAI.TrafficLightState.Red) { // TODO check this
numOffset = counterSize + 53f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 29f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 1f) + 24f * zoom - pedestrianWidth / 2,
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(15f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 2;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
SegmentGeometry geometry = SegmentGeometry.Get(srcSegmentId);
if (geometry == null) {
Log.Error($"TimedTrafficLightsTool.ShowGUI: No geometry information available for segment {srcSegmentId}");
continue;
}
bool startNode = geometry.StartNodeId() == nodeId;
if (geometry.IsOutgoingOneWay(startNode))
continue;
var hasOutgoingLeftSegment = geometry.HasOutgoingLeftSegment(startNode);
var hasOutgoingForwardSegment = geometry.HasOutgoingStraightSegment(startNode);
var hasOutgoingRightSegment = geometry.HasOutgoingRightSegment(startNode);
/*var hasLeftSegment = geometry.HasLeftSegment(startNode);
var hasForwardSegment = geometry.HasStraightSegment(startNode);
var hasRightSegment = geometry.HasRightSegment(startNode);*/
bool hasOtherLight = false;
switch (liveSegmentLight.CurrentMode) {
case LightMode.Simple: {
// no arrow light
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 3 && _hoveredNode == nodeId);
GUI.color = guiColor;
var myRect4 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawMainLightTexture(liveSegmentLight.LightMain, myRect4);
if (myRect4.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeMainLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 0);
float numOffset;
if (liveSegmentLight.LightMain == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
GUI.color = guiColor;
}
break;
case LightMode.SingleLeft:
if (hasOutgoingLeftSegment) {
// left arrow light
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 3 && _hoveredNode == nodeId);
GUI.color = guiColor;
var myRect4 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth * 2 : lightWidth) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawLeftLightTexture(liveSegmentLight.LightLeft, myRect4);
if (myRect4.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeLeftLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 1);
float numOffset;
if (liveSegmentLight.LightLeft == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) - pedestrianWidth + 5f * zoom - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth * 2 : lightWidth),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
// forward-right arrow light
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 4 && _hoveredNode == nodeId);
GUI.color = guiColor;
var myRect5 =
new Rect(offsetScreenPos.x - lightWidth / 2 - pedestrianWidth - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f) + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
if (hasOutgoingForwardSegment && hasOutgoingRightSegment) {
drawForwardRightLightTexture(liveSegmentLight.LightMain, myRect5);
hasOtherLight = true;
} else if (hasOutgoingForwardSegment) {
drawStraightLightTexture(liveSegmentLight.LightMain, myRect5);
hasOtherLight = true;
} else if (hasOutgoingRightSegment) {
drawRightLightTexture(liveSegmentLight.LightMain, myRect5);
hasOtherLight = true;
}
if (hasOtherLight && myRect5.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeMainLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 0);
float numOffset;
if (liveSegmentLight.LightMain == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) - pedestrianWidth + 5f * zoom - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
break;
case LightMode.SingleRight: {
// forward-left light
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 3 && _hoveredNode == nodeId);
GUI.color = guiColor;
var myRect4 = new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth * 2 : lightWidth) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
var lightType = 0;
hasOtherLight = false;
if (hasOutgoingForwardSegment && hasOutgoingLeftSegment) {
hasOtherLight = true;
drawForwardLeftLightTexture(liveSegmentLight.LightMain, myRect4);
lightType = 1;
} else if (hasOutgoingForwardSegment) {
hasOtherLight = true;
if (!hasOutgoingRightSegment) {
myRect4 = new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
}
drawStraightLightTexture(liveSegmentLight.LightMain, myRect4);
} else if (hasOutgoingLeftSegment) {
hasOtherLight = true;
if (!hasOutgoingRightSegment) {
myRect4 = new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
}
drawLeftLightTexture(liveSegmentLight.LightMain, myRect4);
}
if (hasOtherLight && myRect4.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeMainLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, lightType);
float numOffset;
if (liveSegmentLight.LightMain == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) - pedestrianWidth + 5f * zoom - (_timedPanelAdd || _timedEditStep >= 0 ? (hasOutgoingRightSegment ? lightWidth * 2 : lightWidth) : (hasOutgoingRightSegment ? lightWidth : 0f)),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
// right arrow light
if (hasOutgoingRightSegment) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 4 &&
_hoveredNode == nodeId);
GUI.color = guiColor;
var rect5 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawRightLightTexture(liveSegmentLight.LightRight, rect5);
if (rect5.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive &&
(_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeRightLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 2);
float numOffset;
if (liveSegmentLight.LightRight == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(
offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) -
pedestrianWidth + 5f * zoom -
(_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) &&
!IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
}
break;
default:
// left arrow light
if (hasOutgoingLeftSegment) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 3 && _hoveredNode == nodeId);
GUI.color = guiColor;
var offsetLight = lightWidth;
if (hasOutgoingRightSegment)
offsetLight += lightWidth;
if (hasOutgoingForwardSegment)
offsetLight += lightWidth;
var myRect4 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? offsetLight : offsetLight - lightWidth) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawLeftLightTexture(liveSegmentLight.LightLeft, myRect4);
if (myRect4.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeLeftLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 1);
float numOffset;
if (liveSegmentLight.LightLeft == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(
offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) -
pedestrianWidth + 5f * zoom -
(_timedPanelAdd || _timedEditStep >= 0 ? offsetLight : offsetLight - lightWidth),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) &&
!IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 3;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
// forward arrow light
if (hasOutgoingForwardSegment) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 4 && _hoveredNode == nodeId);
GUI.color = guiColor;
var offsetLight = lightWidth;
if (hasOutgoingRightSegment)
offsetLight += lightWidth;
var myRect6 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? offsetLight : offsetLight - lightWidth) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawStraightLightTexture(liveSegmentLight.LightMain, myRect6);
if (myRect6.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeMainLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 0);
float numOffset;
if (liveSegmentLight.LightMain == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(
offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) -
pedestrianWidth + 5f * zoom -
(_timedPanelAdd || _timedEditStep >= 0 ? offsetLight : offsetLight - lightWidth),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) &&
!IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 4;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
// right arrow light
if (hasOutgoingRightSegment) {
guiColor.a = MainTool.GetHandleAlpha(_hoveredButton[0] == srcSegmentId && _hoveredButton[1] == 5 && _hoveredNode == nodeId);
GUI.color = guiColor;
var rect6 =
new Rect(offsetScreenPos.x - lightWidth / 2 - (_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f) - pedestrianWidth + 5f * zoom,
offsetScreenPos.y - lightHeight / 2, lightWidth, lightHeight);
drawRightLightTexture(liveSegmentLight.LightRight, rect6);
if (rect6.Contains(Event.current.mousePosition) && !IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 5;
_hoveredNode = nodeId;
hoveredSegment = true;
if (MainTool.CheckClicked() && !timedActive && (_timedPanelAdd || _timedEditStep >= 0)) {
liveSegmentLight.ChangeRightLight();
}
}
// COUNTER
if (timedActive && _timedShowNumbers) {
var counterSize = 20f * zoom;
var counter = timedNode.CheckNextChange(srcSegmentId, end.StartNode, vehicleType, 2);
float numOffset;
if (liveSegmentLight.LightRight == RoadBaseAI.TrafficLightState.Red) {
numOffset = counterSize + 96f * zoom - modeHeight * 2;
} else {
numOffset = counterSize + 40f * zoom - modeHeight * 2;
}
var myRectCounterNum =
new Rect(
offsetScreenPos.x - counterSize + 15f * zoom + (counter >= 10 ? (counter >= 100 ? -10 * zoom : -5 * zoom) : 0f) -
pedestrianWidth + 5f * zoom -
(_timedPanelAdd || _timedEditStep >= 0 ? lightWidth : 0f),
offsetScreenPos.y - numOffset, counterSize, counterSize);
_counterStyle.fontSize = (int)(18f * zoom);
_counterStyle.normal.textColor = new Color(1f, 1f, 1f);
GUI.Label(myRectCounterNum, counter.ToString(), _counterStyle);
if (myRectCounterNum.Contains(Event.current.mousePosition) &&
!IsCursorInPanel()) {
_hoveredButton[0] = srcSegmentId;
_hoveredButton[1] = 5;
_hoveredNode = nodeId;
hoveredSegment = true;
}
}
}
break;
} // end switch liveSegmentLight.CurrentMode
} // end foreach light
} // end foreach segment
} // end foreach node
if (!hoveredSegment) {
_hoveredButton[0] = 0;
_hoveredButton[1] = 0;
}
}
}
}
| 37.72301 | 308 | 0.665168 | [
"MIT"
] | Sipke82/Cities-Skylines-Traffic-Manager-President-Edition | TLM/TLM/UI/SubTools/TimedTrafficLightsTool.cs | 69,186 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TracerAttributes;
namespace Tracer.Lib.Async
{
public class AsyncMethod
{
[NoTrace]
public AsyncMethod()
{
}
private async Task<int> Double(int p)
{
return await Task.Run(() => p * 2);
}
public async Task<int> CallMeAsync(int param, string param2, int paraInt)
{
var result = await Double(paraInt);
return result;
}
public async Task CallMeReturnNodAsync(string param, string param2, int paraInt)
{
var result = await Double(paraInt);
return;
}
private OtherClass _otc = new OtherClass();
private int _num = 2;
public async Task<int> CallMeOtherClass(string param, string param2, int paraInt)
{
var result = await _otc.Double(paraInt);
return result * _num;
}
public async Task<int> CallMeGeneric<T>(T param, string param2, int paraInt)
{
var result = await Double(paraInt);
return result;
}
public async Task<int> Throw(int p)
{
return await Task.Run(() => ThrowException());
}
private int ThrowException()
{
throw new ApplicationException("Err");
return 1;
}
}
public class OtherClass
{
[NoTrace]
public OtherClass()
{
}
public async Task<int> Double(int p)
{
return await DoubleInt(p);
}
private async Task<int> DoubleInt(int p)
{
return await Task.Run(() => p * 2);
}
}
}
| 22.234568 | 89 | 0.533592 | [
"MIT"
] | hhko/Books | 1.Tutorials/Observability/NLog/Tracer/Tracer.Lib/Async/AsyncMethod.cs | 1,803 | C# |
#region references
using acDb = Autodesk.AutoCAD.DatabaseServices;
using acDynNodes = Autodesk.AutoCAD.DynamoNodes;
using acDynApp = Autodesk.AutoCAD.DynamoApp.Services;
using acGeom = Autodesk.AutoCAD.Geometry;
using civApp = Autodesk.Civil.ApplicationServices;
using Autodesk.DesignScript.Geometry;
using AeccProfileViewDepthLabel = Autodesk.Civil.DatabaseServices.ProfileViewDepthLabel;
using Camber.Civil.Styles.Labels.ProfileView;
using DynamoServices;
using Camber.Civil.CivilObjects;
using Camber.Utilities.GeometryConversions;
#endregion
namespace Camber.Civil.Labels
{
[RegisterForTrace]
public sealed class ProfileViewDepthLabel : Label
{
#region properties
internal AeccProfileViewDepthLabel AeccProfileViewDepthLabel => AcObject as AeccProfileViewDepthLabel;
/// <summary>
/// Gets the Profile View that the Profile View Depth Label belongs to.
/// </summary>
public ProfileView ProfileView => ProfileView.GetByObjectId(AeccProfileViewDepthLabel.FeatureId);
/// <summary>
/// Gets the start point of the Profile View Depth Label.
/// </summary>
public Point StartPoint => GeometryConversions.AcPointToDynPoint(AeccProfileViewDepthLabel.StartPoint);
/// <summary>
/// Gets the end point of the Profile View Depth Label.
/// </summary>
public Point EndPoint => GeometryConversions.AcPointToDynPoint(AeccProfileViewDepthLabel.EndPoint);
#endregion
#region constructors
internal ProfileViewDepthLabel(
AeccProfileViewDepthLabel AeccProfileViewDepthLabel,
bool isDynamoOwned = false)
: base(AeccProfileViewDepthLabel, isDynamoOwned)
{ }
/// <summary>
/// Creates a Profile View Depth Label by two points
/// </summary>
/// <param name="profileView"></param>
/// <param name="startPoint"></param>
/// <param name="endPoint"></param>
/// <param name="labelStyle"></param>
/// <returns></returns>
public static ProfileViewDepthLabel ByTwoPoints(
ProfileView profileView,
Point startPoint,
Point endPoint,
ProfileViewDepthLabelStyle labelStyle)
{
acDynNodes.Document document = acDynNodes.Document.Current;
using (var ctx = new acDynApp.DocumentContext(document.AcDocument))
{
civApp.CivilDocument cdoc = civApp.CivilDocument.GetCivilDocument(ctx.Database);
acDb.ObjectId labelId = acDynApp.ElementBinder.GetObjectIdFromTrace(ctx.Database);
var acStartPoint = (acGeom.Point2d)GeometryConversions.DynPointToAcPoint(startPoint, false);
var acEndPoint = (acGeom.Point2d)GeometryConversions.DynPointToAcPoint(endPoint, false);
if (labelId.IsValid && !labelId.IsErased)
{
AeccProfileViewDepthLabel aeccLabel = (AeccProfileViewDepthLabel)labelId.GetObject(acDb.OpenMode.ForWrite);
if (aeccLabel != null)
{
// Update the start and end points
aeccLabel.StartPoint = acStartPoint;
aeccLabel.EndPoint = acEndPoint;
// Update label style
aeccLabel.StyleId = labelStyle.InternalObjectId;
}
}
else
{
// Create new label
labelId = AeccProfileViewDepthLabel.Create(profileView.InternalObjectId, labelStyle.InternalObjectId, acStartPoint, acEndPoint);
}
var createdLabel = labelId.GetObject(acDb.OpenMode.ForRead) as AeccProfileViewDepthLabel;
if (createdLabel != null)
{
return new ProfileViewDepthLabel(createdLabel, true);
}
return null;
}
}
#endregion
#region methods
public override string ToString() => $"ProfileViewDepthLabel(Profile View = {ProfileView.Name})";
/// <summary>
/// Sets the start and end points of a Profile View Depth Label.
/// </summary>
/// <param name="startPoint"></param>
/// <param name="endPoint"></param>
/// <returns></returns>
public ProfileViewDepthLabel SetPoints(Point startPoint, Point endPoint)
{
SetValue((acGeom.Point2d)GeometryConversions.DynPointToAcPoint(startPoint, false), "StartPoint");
SetValue((acGeom.Point2d)GeometryConversions.DynPointToAcPoint(endPoint, false), "EndPoint");
return this;
}
#endregion
}
}
| 40.661017 | 148 | 0.624635 | [
"BSD-3-Clause"
] | mzjensen/Camber | Camber/Civil/Labels/ProfileViewDepthLabel.cs | 4,800 | C# |
#region Licences
// Copyright (C) 2005 Sebastian Faltoni <sebastian@dotnetfireball.net>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#endregion Licences
using System;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
using System.Runtime.CompilerServices;
using Fireball.Streams;
namespace Fireball.Ssh.jsch
{
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use ins source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions ins binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer ins
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class ChannelSftp : ChannelSession
{
private const byte SSH_FXP_INIT= 1;
private const byte SSH_FXP_VERSION= 2;
private const byte SSH_FXP_OPEN= 3;
private const byte SSH_FXP_CLOSE= 4;
private const byte SSH_FXP_READ= 5;
private const byte SSH_FXP_WRITE= 6;
private const byte SSH_FXP_LSTAT= 7;
private const byte SSH_FXP_FSTAT= 8;
private const byte SSH_FXP_SETSTAT= 9;
private const byte SSH_FXP_FSETSTAT= 10;
private const byte SSH_FXP_OPENDIR= 11;
private const byte SSH_FXP_READDIR= 12;
private const byte SSH_FXP_REMOVE= 13;
private const byte SSH_FXP_MKDIR= 14;
private const byte SSH_FXP_RMDIR= 15;
private const byte SSH_FXP_REALPATH= 16;
private const byte SSH_FXP_STAT= 17;
private const byte SSH_FXP_RENAME= 18;
private const byte SSH_FXP_READLINK= 19;
private const byte SSH_FXP_SYMLINK= 20;
private const byte SSH_FXP_STATUS= 101;
private const byte SSH_FXP_HANDLE= 102;
private const byte SSH_FXP_DATA= 103;
private const byte SSH_FXP_NAME= 104;
private const byte SSH_FXP_ATTRS= 105;
private const byte SSH_FXP_EXTENDED= (byte)200;
private const byte SSH_FXP_EXTENDED_REPLY= (byte)201;
// pflags
private const int SSH_FXF_READ= 0x00000001;
private const int SSH_FXF_WRITE= 0x00000002;
private const int SSH_FXF_APPEND= 0x00000004;
private const int SSH_FXF_CREAT= 0x00000008;
private const int SSH_FXF_TRUNC= 0x00000010;
private const int SSH_FXF_EXCL= 0x00000020;
private const int SSH_FILEXFER_ATTR_SIZE= 0x00000001;
private const int SSH_FILEXFER_ATTR_UIDGID= 0x00000002;
private const int SSH_FILEXFER_ATTR_PERMISSIONS= 0x00000004;
private const int SSH_FILEXFER_ATTR_ACMODTIME= 0x00000008;
private const uint SSH_FILEXFER_ATTR_EXTENDED= 0x80000000;
public const int SSH_FX_OK= 0;
public const int SSH_FX_EOF= 1;
public const int SSH_FX_NO_SUCH_FILE= 2;
public const int SSH_FX_PERMISSION_DENIED= 3;
public const int SSH_FX_FAILURE= 4;
public const int SSH_FX_BAD_MESSAGE= 5;
public const int SSH_FX_NO_CONNECTION= 6;
public const int SSH_FX_CONNECTION_LOST= 7;
public const int SSH_FX_OP_UNSUPPORTED= 8;
/*
SSH_FX_OK
Indicates successful completion of the operation.
SSH_FX_EOF
indicates end-of-file condition; for SSH_FX_READ it means that no
more data is available in the file, and for SSH_FX_READDIR it
indicates that no more files are contained in the directory.
SSH_FX_NO_SUCH_FILE
is returned when a reference is made to a file which should exist
but doesn't.
SSH_FX_PERMISSION_DENIED
is returned when the authenticated user does not have sufficient
permissions to perform the operation.
SSH_FX_FAILURE
is a generic catch-all error message; it should be returned if an
error occurs for which there is no more specific error code
defined.
SSH_FX_BAD_MESSAGE
may be returned if a badly formatted packet or protocol
incompatibility is detected.
SSH_FX_NO_CONNECTION
is a pseudo-error which indicates that the client has no
connection to the server (it can only be generated locally by the
client, and MUST NOT be returned by servers).
SSH_FX_CONNECTION_LOST
is a pseudo-error which indicates that the connection to the
server has been lost (it can only be generated locally by the
client, and MUST NOT be returned by servers).
SSH_FX_OP_UNSUPPORTED
indicates that an attempt was made to perform an operation which
is not supported for the server (it may be generated locally by
the client if e.g. the version number exchange indicates that a
required feature is not supported by the server, or it may be
returned by the server if the server does not implement an
operation).
*/
public const int OVERWRITE=0;
public const int RESUME=1;
public const int APPEND=2;
// private bool interactive=true;
private bool interactive=false;
private int count=1;
private Buffer buf=null;
private Packet packet;
private String _version="3";
private int server_version=3;
/*
10. Changes from previous protocol versions
The SSH File Transfer Protocol has changed over time, before it's
standardization. The following is a description of the incompatible
changes between different versions.
10.1 Changes between versions 3 and 2
o The SSH_FXP_READLINK and SSH_FXP_SYMLINK messages were added.
o The SSH_FXP_EXTENDED and SSH_FXP_EXTENDED_REPLY messages were added.
o The SSH_FXP_STATUS message was changed to include fields `error
message' and `language tag'.
10.2 Changes between versions 2 and 1
o The SSH_FXP_RENAME message was added.
10.3 Changes between versions 1 and 0
o Implementation changes, no actual protocol changes.
*/
private String file_separator=Path.DirectorySeparatorChar.ToString();
private char file_separatorc=Path.DirectorySeparatorChar;
private String cwd;
private String home;
private String lcwd;
public ChannelSftp()
{
packet=new Packet(buf);
}
public override void init()
{
/*
io.setInputStream(session.in);
io.setOutputStream(session.out);
*/
}
public override void start()
{
try
{
PipedOutputStream pos=new PipedOutputStream();
io.setOutputStream(pos);
// PipedInputStream pis=new PipedInputStream(pos);
PipedInputStream pis=new MyPipedInputStream(pos, 32*1024);
io.setInputStream(pis);
Request request=new RequestSftp();
request.request(session, this);
// thread=Thread.currentThread();
// buf=new Buffer();
buf=new Buffer(rmpsize);
packet=new Packet(buf);
int i=0;
int j=0;
int length;
int type;
byte[] str;
// send SSH_FXP_INIT
sendINIT();
// receive SSH_FXP_VERSION
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
//System.out.println(io+" "+io.ins+" "+io.out);
length=buf.getInt();
type=buf.getByte(); // 2 -> SSH_FXP_VERSION
server_version=buf.getInt();
//System.out.println("SFTP protocol server-version="+server_version);
// send SSH_FXP_REALPATH
sendREALPATH(Util.getBytes("."));
// receive SSH_FXP_NAME
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
length=buf.getInt();
type=buf.getByte(); // 104 -> SSH_FXP_NAME
buf.getInt(); //
i=buf.getInt(); // count
str=buf.getString(); // filename
home=cwd=Util.getString(str);
str=buf.getString(); // logname
// SftpATTRS.getATTR(buf); // attrs
lcwd=Path.GetFullPath(".");
//thread=new Thread(this);
//thread.setName("Sftp for "+session.host);
//thread.start();
}
catch(Exception e)
{
//System.out.println(e);
if(e is JSchException) throw (JSchException)e;
throw new JSchException(e.ToString());
}
}
public void quit(){ disconnect();}
public void exit(){ disconnect();}
public void lcd(String path)
{
// if(!path.StartsWith("/")){ path=lcwd+file_separator+path; }
if(!isLocalAbsolutePath(path)){ path=lcwd+file_separator+path; }
if(Directory.Exists(path))
{
try
{
path=Path.GetFullPath(path);
}
catch(Exception e){}
lcwd=path;
return;
}
throw new SftpException(SSH_FX_NO_SUCH_FILE, "No such directory");
}
/*
cd /tmp
c->s REALPATH
s->c NAME
c->s STAT
s->c ATTR
*/
public void cd(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
path=(String)(v[0]);
sendREALPATH(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=101 && type!=104)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==101)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
// byte[] str=buf.getString();
// throw new SftpException(i, Util.getString(str));
}
buf.getInt();
i=buf.getInt();
byte[] str=buf.getString();
if(str!=null && str[0]!='/')
{
str=Util.getBytes(cwd+"/"+Util.getString(str));
}
cwd=Util.getString(str);
str=buf.getString(); // logname
i=buf.getInt(); // attrs
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
/*
put foo
c->s OPEN
s->c HANDLE
c->s WRITE
s->c STATUS
c->s CLOSE
s->c STATUS
*/
public void put(String src, String dst)
{
put(src, dst, null, OVERWRITE);
}
public void put(String src, String dst, int mode)
{
put(src, dst, null, mode);
}
public void put(String src, String dst,
SftpProgressMonitor monitor)
{
put(src, dst, monitor, OVERWRITE);
}
public void put(String src, String dst,
SftpProgressMonitor monitor, int mode)
{
// if(!src.StartsWith("/")){ src=lcwd+file_separator+src; }
if(!isLocalAbsolutePath(src)){ src=lcwd+file_separator+src; }
if(!dst.StartsWith("/")){ dst=cwd+"/"+dst; }
//System.out.println("src: "+src+", "+dst);
try
{
ArrayList v=glob_remote(dst);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
dst=(String)(v[0]);
bool _isRemoteDir=isRemoteDir(dst);
v=glob_local(src);
//System.out.println("glob_local: "+v+" dst="+dst);
for(int j=0; j<v.Count; j++)
{
String _src=(String)(v[j]);
String _dst=dst;
if(_isRemoteDir)
{
if(!_dst.EndsWith("/"))
{
_dst+="/";
}
int i=_src.LastIndexOf(file_separatorc);
if(i==-1) _dst+=_src;
else _dst+=_src.Substring(i+1);
}
//System.out.println("_dst "+_dst);
long size_of_dst=0;
if(mode==RESUME)
{
try
{
SftpATTRS attr=stat(_dst);
size_of_dst=attr.getSize();
}
catch(Exception eee)
{
//System.out.println(eee);
}
long size_of_src=new FileInfo(_src).Length;
if(size_of_src<size_of_dst)
{
throw new SftpException(SSH_FX_FAILURE, "failed to resume for "+_dst);
}
if(size_of_src==size_of_dst)
{
return;
}
}
if(monitor!=null)
{
monitor.init(SftpProgressMonitor.PUT, _src, _dst,
(new FileInfo(_src)).Length);
if(mode==RESUME)
{
monitor.count(size_of_dst);
}
}
FileStream fis=null;
try
{
fis=File.OpenRead(_src);
put(fis, _dst, monitor, mode);
}
finally
{
if(fis!=null)
{
// try{
fis.Close();
// }catch(Exception ee){};
}
}
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, e.ToString());
}
}
public void put(Stream src, String dst)
{
put(src, dst, null, OVERWRITE);
}
public void put(Stream src, String dst, int mode)
{
put(src, dst, null, mode);
}
public void put(Stream src, String dst,
SftpProgressMonitor monitor)
{
put(src, dst, monitor, OVERWRITE);
}
public void put(Stream src, String dst,
SftpProgressMonitor monitor, int mode)
{
try
{
if(!dst.StartsWith("/")){ dst=cwd+"/"+dst; }
ArrayList v=glob_remote(dst);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
dst=(String)(v[0]);
if(isRemoteDir(dst))
{
throw new SftpException(SSH_FX_FAILURE, dst+" is a directory");
}
long skip=0;
if(mode==RESUME || mode==APPEND)
{
try
{
SftpATTRS attr=stat(dst);
skip=attr.getSize();
}
catch(Exception eee)
{
//System.out.println(eee);
}
}
if(mode==RESUME && skip>0)
{
long skipped=src.Seek(skip, SeekOrigin.Current);
if(skipped<skip)
{
throw new SftpException(SSH_FX_FAILURE, "failed to resume for "+dst);
}
}
if(mode==OVERWRITE)
{
sendOPENW(Util.getBytes(dst));
}
else
{
sendOPENA(Util.getBytes(dst));
}
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
byte[] data=new byte[buf.buffer.Length-1024];
long offset=0;
if(mode==RESUME || mode==APPEND)
{
offset+=skip;
}
while(true)
{
//i=src.read(data, 0, data.Length);
i=0;
int nread=0;
do
{
nread=src.Read(data, i, data.Length-i);
if(nread>0)
{
i+=nread;
}
}
while(i<data.Length && nread>0);
if(i<=0)break;
sendWRITE(handle, offset, data, 0, i);
offset+=i;
if(!checkStatus()){ break; }
if(monitor!=null && !monitor.count(i))
{
break;
}
}
if(monitor!=null)monitor.end();
_sendCLOSE(handle);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
/**/
public Stream put(String dst)
{
return put(dst, (SftpProgressMonitor)null, OVERWRITE);
}
public Stream put(String dst, int mode)
{
return put(dst, (SftpProgressMonitor)null, mode);
}
public Stream put(String dst, SftpProgressMonitor monitor, int mode)
{
if(!dst.StartsWith("/")){ dst=cwd+"/"+dst; }
try
{
ArrayList v=glob_remote(dst);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
dst=(String)(v[0]);
if(isRemoteDir(dst))
{
throw new SftpException(SSH_FX_FAILURE, dst+" is a directory");
}
long skip=0;
if(mode==RESUME || mode==APPEND)
{
try
{
SftpATTRS attr=stat(dst);
skip=attr.getSize();
}
catch(Exception eee)
{
//System.out.println(eee);
}
}
if(mode==OVERWRITE){ sendOPENW(Util.getBytes(dst)); }
else{ sendOPENA(Util.getBytes(dst)); }
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
long offset=0;
if(mode==RESUME || mode==APPEND)
{
offset+=skip;
}
long[] _offset=new long[1];
_offset[0]=offset;
OutputStreamPut outs = new OutputStreamPut
(this,handle,_offset,monitor);
return outs;
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
internal class OutputStreamPut : java.io.OutputStream
{
ChannelSftp sftp;
byte[] handle;
long[] _offset;
SftpProgressMonitor monitor;
internal OutputStreamPut
(ChannelSftp sftp,
byte[] handle,
long[] _offset,
SftpProgressMonitor monitor):base()
{
this.sftp=sftp;
this.handle=handle;
this._offset=_offset;
this.monitor=monitor;
}
public override void Write(byte[] d, int s, int len)
{
try
{
sftp.sendWRITE(handle, _offset[0], d, s, len);
_offset[0]+=len;
if(!sftp.checkStatus())
{
throw new IOException("jsch status error");
}
if(monitor!=null && !monitor.count(1))
{
throw new IOException("canceled");
}
}
catch(IOException e){ throw e; }
catch(Exception e){ throw new IOException(e.ToString()); }
}
byte[] _data=new byte[1];
public override void WriteByte(byte foo)
{
_data[0]=foo;
Write(_data, 0, 1);
}
public void Write(int foo)
{
this.WriteByte((byte)foo);
}
public override void Close()
{
if(monitor!=null)monitor.end();
try{ sftp._sendCLOSE(handle); }
catch(IOException e){ throw e; }
catch(Exception e)
{
throw new IOException(e.ToString());
}
}
}
/**/
public void get(String src, String dst)
{
get(src, dst, null, OVERWRITE);
}
public void get(String src, String dst,
SftpProgressMonitor monitor)
{
get(src, dst, monitor, OVERWRITE);
}
public void get(String src, String dst,
SftpProgressMonitor monitor, int mode)
{
if(!src.StartsWith("/")){ src=cwd+"/"+src; }
// if(!dst.StartsWith("/")){ dst=lcwd+file_separator+dst; }
if(!isLocalAbsolutePath(dst)){ dst=lcwd+file_separator+dst; }
try
{
ArrayList v=glob_remote(src);
if(v.Count==0)
{
throw new SftpException(SSH_FX_NO_SUCH_FILE, "No such file");
}
for(int j=0; j<v.Count; j++)
{
String _dst=dst;
String _src=(String)(v[j]);
if(Directory.Exists(_dst))
{
if(!_dst.EndsWith(file_separator))
{
_dst+=file_separator;
}
int i=_src.LastIndexOf('/');
if(i==-1) _dst+=src;
else _dst+=_src.Substring(i+1);
}
SftpATTRS attr=stat(_src);
if(mode==RESUME)
{
long size_of_src=attr.getSize();
long size_of_dst=new FileInfo(_dst).Length;
if(size_of_dst>size_of_src)
{
throw new SftpException(SSH_FX_FAILURE, "failed to resume for "+_dst);
}
if(size_of_dst==size_of_src)
{
return;
}
}
if(monitor!=null)
{
monitor.init(SftpProgressMonitor.GET, _src, _dst, attr.getSize());
if(mode==RESUME)
{
monitor.count(new FileInfo(_dst).Length);
}
}
FileStream fos=null;
if(mode==OVERWRITE)
{
fos=new FileStream(_dst, FileMode.Create);
}
else
{
fos=new FileStream(_dst, FileMode.Append); // append
}
_get(_src, fos, monitor, mode, new FileInfo(_dst).Length);
fos.Close();
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void get(String src, Stream dst)
{
get(src, dst, null, OVERWRITE, 0);
}
public void get(String src, Stream dst,
SftpProgressMonitor monitor)
{
get(src, dst, monitor, OVERWRITE, 0);
}
public void get(String src, Stream dst,
SftpProgressMonitor monitor, int mode, long skip)
{
//System.out.println("get: "+src+", "+dst);
try
{
if(!src.StartsWith("/")){ src=cwd+"/"+src; }
ArrayList v=glob_remote(src);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
src=(String)(v[0]);
if(monitor!=null)
{
SftpATTRS attr=stat(src);
monitor.init(SftpProgressMonitor.GET, src, "??", attr.getSize());
if(mode==RESUME)
{
monitor.count(skip);
}
}
_get(src, dst, monitor, mode, skip);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
private void _get(String src, Stream dst,
SftpProgressMonitor monitor, int mode, long skip)
{
//System.out.println("_get: "+src+", "+dst);
try
{
sendOPENR(Util.getBytes(src));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
long offset=0;
if(mode==RESUME)
{
offset+=skip;
}
int request_len=0;
loop:
while(true)
{
request_len=buf.buffer.Length-13;
if(server_version==0){ request_len=1024; }
sendREAD(handle, offset, request_len);
buf.rewind();
i=io.ins.Read(buf.buffer, 0, 13); // 4 + 1 + 4 + 4
if(i!=13)
{
goto BREAK;
}
length=buf.getInt();
type=buf.getByte();
length--;
buf.getInt();
length-=4;
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_DATA)
{
goto BREAK;
}
if(type==SSH_FXP_STATUS)
{
i=buf.getInt();
length-=4;
io.ins.Read(buf.buffer, 13, length);
if(i==SSH_FX_EOF)
{
goto BREAK;
}
throwStatusError(buf, i);
}
i=buf.getInt();
length-=4;
int foo=i;
while(foo>0)
{
int bar=length;
if(bar>buf.buffer.Length)
{
bar=buf.buffer.Length;
}
i=io.ins.Read(buf.buffer, 0, bar);
if(i<0)
{
goto BREAK;
}
int data_len=i;
length-=data_len;
dst.Write(buf.buffer, 0, data_len);
if(monitor!=null)
{
if(!monitor.count(data_len))
{
goto BREAK;
}
}
offset+=data_len;
foo-=data_len;
}
//System.out.println("length: "+length); // length should be 0
}
BREAK:
dst.Flush();
if(monitor!=null)monitor.end();
_sendCLOSE(handle);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public Stream get(String src)
{
return get(src, null, OVERWRITE);
}
public Stream get(String src, SftpProgressMonitor monitor)
{
return get(src, monitor, OVERWRITE);
}
public Stream get(String src, int mode)
{
return get(src, null, mode);
}
public Stream get(String src, SftpProgressMonitor monitor, int mode)
{
if(mode==RESUME)
{
throw new SftpException(SSH_FX_FAILURE, "faile to resume from "+src);
}
if(!src.StartsWith("/")){ src=cwd+"/"+src; }
try
{
ArrayList v=glob_remote(src);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
src=(String)(v[0]);
SftpATTRS attr=stat(src);
if(monitor!=null)
{
monitor.init(SftpProgressMonitor.GET, src, "??", attr.getSize());
}
sendOPENR(Util.getBytes(src));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
long[] _offset=new long[1];
//_offset[0]=0;
int[] _server_version=new int[1];
_server_version[0]=server_version;
InputStreamGet ins=new InputStreamGet(this, handle, _offset, _server_version, monitor);
return ins;
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public class InputStreamGet : java.io.InputStream
{
bool closed=false;
int rest_length=0;
byte[] _data=new byte[1];
ChannelSftp sftp;
byte[] handle;
long[] _offset;
int[]_server_version;
SftpProgressMonitor monitor;
public InputStreamGet(
ChannelSftp sftp,
byte[] handle,
long[] _offset,
int[] _server_version,
SftpProgressMonitor monitor)
{
this.sftp=sftp;
this.handle=handle;
this._offset=_offset;
this._server_version=_server_version;
this.monitor=monitor;
}
public override int ReadByte()
{
int i=Read(_data, 0, 1);
if (i==-1) { return -1; }
else
{
return _data[0]&0xff;
}
}
public int Read(byte[] d)
{
return Read(d, 0, d.Length);
}
public override int Read(byte[] d, int s, int len)
{
if(d==null){throw new NullReferenceException();}
if(s<0 || len <0 || s+len>d.Length)
{
throw new IndexOutOfRangeException();
}
if(len==0){ return 0; }
if(rest_length>0)
{
int foo=rest_length;
if(foo>len) foo=len;
int i=sftp.io.ins.Read(d, s, foo);
if(i<0)
{
throw new IOException("error");
}
rest_length-=foo;
return i;
}
if(sftp.buf.buffer.Length-13<len)
{
len=sftp.buf.buffer.Length-13;
}
if(_server_version[0]==0 && len>1024)
{
len=1024;
}
try{sftp.sendREAD(handle, _offset[0], len);}
catch(Exception e){ throw new IOException("error"); }
sftp.buf.rewind();
int ii=sftp.io.ins.Read(sftp.buf.buffer, 0, 13); // 4 + 1 + 4 + 4
if(ii!=13)
{
throw new IOException("error");
}
rest_length=sftp.buf.getInt();
int type=sftp.buf.getByte();
rest_length--;
sftp.buf.getInt();
rest_length-=4;
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_DATA)
{
throw new IOException("error");
}
if(type==SSH_FXP_STATUS)
{
ii=sftp.buf.getInt();
rest_length-=4;
sftp.io.ins.Read(sftp.buf.buffer, 13, rest_length);
rest_length=0;
if(ii==SSH_FX_EOF)
{
Close();
return -1;
}
//throwStatusError(buf, i);
throw new IOException("error");
}
ii=sftp.buf.getInt();
rest_length-=4;
int goo=ii;
if(goo>0)
{
int bar=rest_length;
if(bar>len)
{
bar=len;
}
ii=sftp.io.ins.Read(d, s, bar);
if(ii<0)
{
return -1;
}
int data_len=ii;
rest_length-=data_len;
if(monitor!=null)
{
if(!monitor.count(data_len))
{
return -1;
}
}
_offset[0]+=data_len;
return ii;
}
return 0; // ??
}
public override void Close()
{
if(closed)return;
closed=true;
/*
while(rest_length>0){
int foo=rest_length;
if(foo>buf.buffer.Length){
foo=buf.buffer.Length;
}
io.ins.Read(buf.buffer, 0, foo);
rest_length-=foo;
}
*/
if(monitor!=null)monitor.end();
try{sftp._sendCLOSE(handle);}
catch(Exception e){throw new IOException("error");}
}
}
public ArrayList ls(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
String dir=path;
byte[] pattern=null;
SftpATTRS attr=null;
if(isPattern(dir) ||
((attr=stat(dir))!=null && !attr.isDir()))
{
int foo=path.LastIndexOf('/');
dir=path.Substring(0, ((foo==0)?1:foo));
pattern=Util.getBytes( path.Substring(foo+1) );
}
sendOPENDIR(Util.getBytes(dir));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
ArrayList v=new ArrayList();
while(true)
{
sendREADDIR(handle);
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
buf.index=i;
length=buf.getInt();
length=length-(i-4);
type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_NAME)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
/*
buf.getInt();
i=buf.getInt();
System.out.println("i="+i);
if(i==SSH_FX_EOF) break;
byte[] str=buf.getString();
throw new SftpException(i, Util.getString(str));
*/
break;
}
buf.getInt();
int count=buf.getInt();
byte[] str;
int flags;
while(count>0)
{
if(length>0)
{
buf.shift();
i=io.ins.Read(buf.buffer, buf.index, buf.buffer.Length-buf.index);
if(i<=0)break;
buf.index+=i;
length-=i;
}
byte[] filename=buf.getString();
//System.out.println("filename: "+Util.getString(filename));
str=buf.getString();
String longname=Util.getString(str);
// System.out.println("longname: "+longname);
SftpATTRS attrs=SftpATTRS.getATTR(buf);
if(pattern==null || Util.glob(pattern, filename))
{
//System.out.println(Util.getString(filename)+" |"+longname+"|");
// v.Add(longname);
v.Add(new LsEntry(Util.getString(filename), longname, attrs));
}
count--;
}
}
_sendCLOSE(handle);
return v;
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void symlink(String oldpath, String newpath)
{
if(server_version<3)
{
throw new SftpException(SSH_FX_FAILURE,
"The remote sshd is too old to support symlink operation.");
}
try
{
if(!oldpath.StartsWith("/")){ oldpath=cwd+"/"+oldpath; }
if(!newpath.StartsWith("/")){ newpath=cwd+"/"+newpath; }
ArrayList v=glob_remote(oldpath);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
oldpath=(String)(v[0]);
sendSYMLINK(Util.getBytes(oldpath), Util.getBytes(newpath));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i==SSH_FX_OK) return;
throwStatusError(buf, i);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void rename(String oldpath, String newpath)
{
if(server_version<2)
{
throw new SftpException(SSH_FX_FAILURE,
"The remote sshd is too old to support rename operation.");
}
try
{
if(!oldpath.StartsWith("/")){ oldpath=cwd+"/"+oldpath; }
if(!newpath.StartsWith("/")){ newpath=cwd+"/"+newpath; }
ArrayList v=glob_remote(oldpath);
if(v.Count!=1)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
oldpath=(String)(v[0]);
v=glob_remote(newpath);
if(v.Count>=2)
{
throw new SftpException(SSH_FX_FAILURE, v.ToString());
}
if(v.Count==1)
{
newpath=(String)(v[0]);
}
sendRENAME(Util.getBytes(oldpath), Util.getBytes(newpath));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i==SSH_FX_OK) return;
throwStatusError(buf, i);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void rm(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendREMOVE(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i!=SSH_FX_OK)
{
throwStatusError(buf, i);
}
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
private bool isRemoteDir(String path)
{
try
{
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS){ return false; }
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
return attr.isDir();
}
catch(Exception e){}
return false;
}
/*
bool isRemoteDir(String path) {
SftpATTRS attr=stat(path);
return attr.isDir();
}
*/
public void chgrp(int gid, String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
attr.setUIDGID(attr.uid, gid);
_setStat(path, attr);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void chown(int uid, String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
attr.setUIDGID(uid, attr.gid);
_setStat(path, attr);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void chmod(int permissions, String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
attr.setPERMISSIONS(permissions);
_setStat(path, attr);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void setMtime(String path, int mtime)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
attr.setACMODTIME(attr.getATime(), mtime);
_setStat(path, attr);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void rmdir(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
sendRMDIR(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i!=SSH_FX_OK)
{
throwStatusError(buf, i);
}
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void mkdir(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
sendMKDIR(Util.getBytes(path), null);
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i==SSH_FX_OK) return;
throwStatusError(buf, i);
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public SftpATTRS stat(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
sendSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
return attr;
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
//return null;
}
public SftpATTRS lstat(String path)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
sendLSTAT(Util.getBytes(path));
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_ATTRS)
{
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
SftpATTRS attr=SftpATTRS.getATTR(buf);
return attr;
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public void setStat(String path, SftpATTRS attr)
{
try
{
if(!path.StartsWith("/")){ path=cwd+"/"+path; }
ArrayList v=glob_remote(path);
for(int j=0; j<v.Count; j++)
{
path=(String)(v[j]);
_setStat(path, attr);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
private void _setStat(String path, SftpATTRS attr)
{
try
{
sendSETSTAT(Util.getBytes(path), attr);
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i!=SSH_FX_OK)
{
throwStatusError(buf, i);
}
}
catch(Exception e)
{
if(e is SftpException) throw (SftpException)e;
throw new SftpException(SSH_FX_FAILURE, "");
}
}
public String pwd(){ return cwd; }
public String lpwd(){ return lcwd; }
public String version(){ return _version; }
private bool checkStatus()
{
buf.rewind();
io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
int i=buf.getInt();
if(i!=SSH_FX_OK)
{
throwStatusError(buf, i);
//System.out.println("getInt="+buf.getInt());
}
return true;
}
private void _sendCLOSE(byte[] handle)
{
sendCLOSE(handle);
buf.rewind();
int i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i==SSH_FX_OK) return;
throwStatusError(buf, i);
}
private void sendINIT()
{
packet.reset();
putHEAD(SSH_FXP_INIT, 5);
buf.putInt(3); // version 3
session.write(packet, this, 5+4);
}
private void sendREALPATH(byte[] path)
{
sendPacketPath(SSH_FXP_REALPATH, path);
}
private void sendSTAT(byte[] path)
{
sendPacketPath(SSH_FXP_STAT, path);
}
private void sendLSTAT(byte[] path)
{
sendPacketPath(SSH_FXP_LSTAT, path);
}
private void sendFSTAT(byte[] handle)
{
sendPacketPath(SSH_FXP_FSTAT, handle);
}
private void sendSETSTAT(byte[] path, SftpATTRS attr)
{
packet.reset();
putHEAD(SSH_FXP_SETSTAT, 9+path.Length+attr.length());
buf.putInt(count++);
buf.putString(path); // path
attr.dump(buf);
session.write(packet, this, 9+path.Length+attr.length()+4);
}
private void sendREMOVE(byte[] path)
{
sendPacketPath(SSH_FXP_REMOVE, path);
}
private void sendMKDIR(byte[] path, SftpATTRS attr)
{
packet.reset();
putHEAD(SSH_FXP_MKDIR, 9+path.Length+(attr!=null?attr.length():4));
buf.putInt(count++);
buf.putString(path); // path
if(attr!=null) attr.dump(buf);
else buf.putInt(0);
session.write(packet, this, 9+path.Length+(attr!=null?attr.length():4)+4);
}
private void sendRMDIR(byte[] path)
{
sendPacketPath(SSH_FXP_RMDIR, path);
}
private void sendSYMLINK(byte[] p1, byte[] p2)
{
sendPacketPath(SSH_FXP_SYMLINK, p1, p2);
}
private void sendREADLINK(byte[] path)
{
sendPacketPath(SSH_FXP_READLINK, path);
}
private void sendOPENDIR(byte[] path)
{
sendPacketPath(SSH_FXP_OPENDIR, path);
}
private void sendREADDIR(byte[] path)
{
sendPacketPath(SSH_FXP_READDIR, path);
}
private void sendRENAME(byte[] p1, byte[] p2)
{
sendPacketPath(SSH_FXP_RENAME, p1, p2);
}
private void sendCLOSE(byte[] path)
{
sendPacketPath(SSH_FXP_CLOSE, path);
}
private void sendOPENR(byte[] path)
{
sendOPEN(path, SSH_FXF_READ);
}
private void sendOPENW(byte[] path)
{
sendOPEN(path, SSH_FXF_WRITE|SSH_FXF_CREAT|SSH_FXF_TRUNC);
}
private void sendOPENA(byte[] path)
{
sendOPEN(path, SSH_FXF_WRITE|/*SSH_FXF_APPEND|*/SSH_FXF_CREAT);
}
private void sendOPEN(byte[] path, int mode)
{
packet.reset();
putHEAD(SSH_FXP_OPEN, 17+path.Length);
buf.putInt(count++);
buf.putString(path);
buf.putInt(mode);
buf.putInt(0); // attrs
session.write(packet, this, 17+path.Length+4);
}
private void sendPacketPath(byte fxp, byte[] path)
{
packet.reset();
putHEAD(fxp, 9+path.Length);
buf.putInt(count++);
buf.putString(path); // path
session.write(packet, this, 9+path.Length+4);
}
private void sendPacketPath(byte fxp, byte[] p1, byte[] p2)
{
packet.reset();
putHEAD(fxp, 13+p1.Length+p2.Length);
buf.putInt(count++);
buf.putString(p1);
buf.putString(p2);
session.write(packet, this, 13+p1.Length+p2.Length+4);
}
private void sendWRITE(byte[] handle, long offset,
byte[] data, int start, int length)
{
packet.reset();
putHEAD(SSH_FXP_WRITE, 21+handle.Length+length);
buf.putInt(count++);
buf.putString(handle);
buf.putLong(offset);
buf.putString(data, start, length);
session.write(packet, this, 21+handle.Length+length+4);
}
private void sendREAD(byte[] handle, long offset, int length)
{
packet.reset();
putHEAD(SSH_FXP_READ, 21+handle.Length);
buf.putInt(count++);
buf.putString(handle);
buf.putLong(offset);
buf.putInt(length);
session.write(packet, this, 21+handle.Length+4);
}
private void putHEAD(byte type, int length)
{
buf.putByte((byte)Session.SSH_MSG_CHANNEL_DATA);
buf.putInt(recipient);
buf.putInt(length+4);
buf.putInt(length);
buf.putByte(type);
}
private ArrayList glob_remote(String _path)
{
//System.out.println("glob_remote: "+_path);
ArrayList v=new ArrayList();
byte[] path=Util.getBytes(_path);
int i=path.Length-1;
while(i>=0){if(path[i]=='*' || path[i]=='?')break;i--;}
if(i<0){ v.Add(_path); return v;}
while(i>=0){if(path[i]=='/')break;i--;}
if(i<0){ v.Add(_path); return v;}
byte[] dir;
if(i==0){dir=new byte[]{(byte)'/'};}
else
{
dir=new byte[i];
Array.Copy(path, 0, dir, 0, i);
}
//System.out.println("dir: "+Util.getString(dir));
byte[] pattern=new byte[path.Length-i-1];
Array.Copy(path, i+1, pattern, 0, pattern.Length);
//System.out.println("file: "+Util.getString(pattern));
sendOPENDIR(dir);
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
int length=buf.getInt();
int type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_HANDLE)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
buf.getInt();
i=buf.getInt();
throwStatusError(buf, i);
}
buf.getInt();
byte[] handle=buf.getString(); // filename
while(true)
{
sendREADDIR(handle);
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
buf.index=i;
length=buf.getInt();
length=length-(i-4);
type=buf.getByte();
if(type!=SSH_FXP_STATUS && type!=SSH_FXP_NAME)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
if(type==SSH_FXP_STATUS)
{
break;
}
buf.getInt();
int count=buf.getInt();
byte[] str;
int flags;
while(count>0)
{
if(length>0)
{
buf.shift();
i=io.ins.Read(buf.buffer, buf.index, buf.buffer.Length-buf.index);
if(i<=0)break;
buf.index+=i;
length-=i;
}
byte[] filename=buf.getString();
//System.out.println("filename: "+Util.getString(filename));
str=buf.getString();
SftpATTRS attrs=SftpATTRS.getATTR(buf);
if(Util.glob(pattern, filename))
{
v.Add(Util.getString(dir)+"/"+Util.getString(filename));
}
count--;
}
}
sendCLOSE(handle);
buf.rewind();
i=io.ins.Read(buf.buffer, 0, buf.buffer.Length);
length=buf.getInt();
type=buf.getByte();
if(type!=SSH_FXP_STATUS)
{
throw new SftpException(SSH_FX_FAILURE, "");
}
buf.getInt();
i=buf.getInt();
if(i==SSH_FX_OK) return v;
return null;
}
private ArrayList glob_local(String _path)
{
//System.out.println("glob_local: "+_path);
ArrayList v=new ArrayList();
byte[] path=Util.getBytes(_path);
int i=path.Length-1;
while(i>=0){if(path[i]=='*' || path[i]=='?')break;i--;}
if(i<0){ v.Add(_path); return v;}
while(i>=0){if(path[i]==file_separatorc)break;i--;}
if(i<0){ v.Add(_path); return v;}
byte[] dir;
if(i==0){dir=new byte[]{(byte)file_separatorc};}
else
{
dir=new byte[i];
Array.Copy(path, 0, dir, 0, i);
}
byte[] pattern=new byte[path.Length-i-1];
Array.Copy(path, i+1, pattern, 0, pattern.Length);
//System.out.println("dir: "+Util.getString(dir)+" pattern: "+Util.getString(pattern));
try
{
ArrayList children;
children=new ArrayList(Directory.GetDirectories( Util.getString(dir) ));
children.AddRange( Directory.GetFiles(Util.getString(dir)) );
for(int j=0; j<children.Count; j++)
{
//System.out.println("children: "+children[j]);
string child = (string)children[j];
if(Util.glob(pattern, Util.getBytes(child)))
{
v.Add(Util.getString(dir)+file_separator+child);
}
}
}
catch(Exception e)
{
}
return v;
}
private void throwStatusError(Buffer buf, int i)
{
if(server_version>=3)
{
byte[] str=buf.getString();
//byte[] tag=buf.getString();
throw new SftpException(i, Util.getString(str));
}
else
{
throw new SftpException(i, "Failure");
}
}
private static bool isLocalAbsolutePath(String path)
{
return Path.IsPathRooted(path);
}
/*
public void finalize() throws Throwable{
super.finalize();
}
*/
public override void disconnect()
{
//waitForRunningThreadFinish(10000);
clearRunningThreads();
base.disconnect();
}
private ArrayList threadList=null;
[MethodImpl(MethodImplOptions.Synchronized)]
protected void addRunningThread(Thread thread)
{
if(threadList==null)threadList=new ArrayList();
threadList.Add(thread);
}
[MethodImpl(MethodImplOptions.Synchronized)]
protected void clearRunningThreads()
{
if(threadList==null)return;
for(int t=0;t<threadList.Count;t++)
{
Thread thread=(Thread)threadList[t];
if(thread!=null)
if(thread.IsAlive)
thread.Interrupt();
}
threadList.Clear();
}
private bool isPattern(String path)
{
return path.IndexOf("*")!=-1 || path.IndexOf("?")!=-1;
}
public class LsEntry
{
private String filename;
private String longname;
private SftpATTRS attrs;
internal LsEntry(String filename, String longname, SftpATTRS attrs)
{
setFilename(filename);
setLongname(longname);
setAttrs(attrs);
}
public String getFilename(){return filename;}
void setFilename(String filename){this.filename = filename;}
public String getLongname(){return longname;}
void setLongname(String longname){this.longname = longname;}
public SftpATTRS getAttrs(){return attrs;}
void setAttrs(SftpATTRS attrs) {this.attrs = attrs;}
public override String ToString(){ return longname; }
}
}
}
| 25.969683 | 92 | 0.58606 | [
"MIT"
] | RivenZoo/FullSource | Jx3Full/Source/Source/Tools/GameDesignerEditor/Controls/luaEditor/fireball_src/Fireball.Ssh/Fireball.Ssh/jsch/ChannelSftp.cs | 52,712 | C# |
using System;
namespace Pixytech.Core.Logging
{
public class NLogLogger : ILog
{
private readonly object _logger;
private static readonly Func<object, bool> IsDebugEnabledDelegate;
private static readonly Func<object, bool> IsInfoEnabledDelegate;
private static readonly Func<object, bool> IsWarnEnabledDelegate;
private static readonly Func<object, bool> IsErrorEnabledDelegate;
private static readonly Func<object, bool> IsFatalEnabledDelegate;
private static readonly Action<object, string> DebugDelegate;
private static readonly Action<object, string, Exception> DebugExceptionDelegate;
private static readonly Action<object, string, object[]> DebugFormatDelegate;
private static readonly Action<object, string> InfoDelegate;
private static readonly Action<object, string, Exception> InfoExceptionDelegate;
private static readonly Action<object, string, object[]> InfoFormatDelegate;
private static readonly Action<object, string> WarnDelegate;
private static readonly Action<object, string, Exception> WarnExceptionDelegate;
private static readonly Action<object, string, object[]> WarnFormatDelegate;
private static readonly Action<object, string> ErrorDelegate;
private static readonly Action<object, string, Exception> ErrorExceptionDelegate;
private static readonly Action<object, string, object[]> ErrorFormatDelegate;
private static readonly Action<object, string> FatalDelegate;
private static readonly Action<object, string, Exception> FatalExceptionDelegate;
private static readonly Action<object, string, object[]> FatalFormatDelegate;
public bool IsDebugEnabled
{
get
{
return IsDebugEnabledDelegate(_logger);
}
}
public bool IsInfoEnabled
{
get
{
return IsInfoEnabledDelegate(_logger);
}
}
public bool IsWarnEnabled
{
get
{
return IsWarnEnabledDelegate(_logger);
}
}
public bool IsErrorEnabled
{
get
{
return IsErrorEnabledDelegate(_logger);
}
}
public bool IsFatalEnabled
{
get
{
return IsFatalEnabledDelegate(_logger);
}
}
static NLogLogger()
{
Type logType = typeof(NLog.Logger);
IsDebugEnabledDelegate = logType.GetInstancePropertyDelegate<bool>("IsDebugEnabled");
IsInfoEnabledDelegate = logType.GetInstancePropertyDelegate<bool>("IsInfoEnabled");
IsWarnEnabledDelegate = logType.GetInstancePropertyDelegate<bool>("IsWarnEnabled");
IsErrorEnabledDelegate = logType.GetInstancePropertyDelegate<bool>("IsErrorEnabled");
IsFatalEnabledDelegate = logType.GetInstancePropertyDelegate<bool>("IsFatalEnabled");
DebugDelegate = logType.GetInstanceMethodDelegate<string>("Debug");
DebugExceptionDelegate = logType.GetInstanceMethodDelegate<string,Exception>("DebugException");
DebugFormatDelegate = logType.GetInstanceMethodDelegate<string,object[]>("Debug");
InfoDelegate = logType.GetInstanceMethodDelegate<string>("Info");
InfoExceptionDelegate = logType.GetInstanceMethodDelegate<string,Exception>("InfoException");
InfoFormatDelegate = logType.GetInstanceMethodDelegate<string,object[]>("Info");
WarnDelegate = logType.GetInstanceMethodDelegate<string>("Warn");
WarnExceptionDelegate = logType.GetInstanceMethodDelegate<string,Exception>("WarnException");
WarnFormatDelegate = logType.GetInstanceMethodDelegate<string,object[]>("Warn");
ErrorDelegate = logType.GetInstanceMethodDelegate<string>("Error");
ErrorExceptionDelegate = logType.GetInstanceMethodDelegate<string,Exception>("ErrorException");
ErrorFormatDelegate = logType.GetInstanceMethodDelegate<string,object[]>("Error");
FatalDelegate = logType.GetInstanceMethodDelegate<string>("Fatal");
FatalExceptionDelegate = logType.GetInstanceMethodDelegate<string,Exception>("FatalException");
FatalFormatDelegate = logType.GetInstanceMethodDelegate<string,object[]>("Fatal");
}
public NLogLogger(object logger)
{
_logger = logger;
}
public void Debug(string message)
{
DebugDelegate(_logger, message);
}
public void Debug(string message, Exception exception)
{
DebugExceptionDelegate(_logger, message, exception);
}
public void DebugFormat(string format, params object[] args)
{
DebugFormatDelegate(_logger, format, args);
}
public void Info(string message)
{
InfoDelegate(_logger, message);
}
public void Info(string message, Exception exception)
{
InfoExceptionDelegate(_logger, message, exception);
}
public void InfoFormat(string format, params object[] args)
{
InfoFormatDelegate(_logger, format, args);
}
public void Warn(string message)
{
WarnDelegate(_logger, message);
}
public void Warn(string message, Exception exception)
{
WarnExceptionDelegate(_logger, message, exception);
}
public void WarnFormat(string format, params object[] args)
{
WarnFormatDelegate(_logger, format, args);
}
public void Error(string message)
{
ErrorDelegate(_logger, message);
}
public void Error(string message, Exception exception)
{
ErrorExceptionDelegate(_logger, message, exception);
}
public void ErrorFormat(string format, params object[] args)
{
ErrorFormatDelegate(_logger, format, args);
}
public void Fatal(string message)
{
FatalDelegate(_logger, message);
}
public void Fatal(string message, Exception exception)
{
FatalExceptionDelegate(_logger, message, exception);
}
public void FatalFormat(string format, params object[] args)
{
FatalFormatDelegate(_logger, format, args);
}
}
}
| 42.954248 | 107 | 0.64227 | [
"Apache-2.0"
] | Pixytech/Frameworks | Pixytech.Core/Logging/NLogLogger.cs | 6,574 | C# |
using UnityEngine;
namespace ExpressoBits.Console.UI
{
[CreateAssetMenu(fileName = "New Theme", menuName = "Expresso Bits/Console/Theme", order = 0)]
public class Theme : ScriptableObject
{
public Font font;
[Header("Log Attributes")]
public LogAttribute defaultLogAttribute;
public LogAttribute warnLogAttribute;
public LogAttribute errorLogAttribute;
public LogAttribute helpLogAttribute;
public LogAttribute successLogAttribute;
}
} | 30.470588 | 98 | 0.689189 | [
"MIT"
] | ExpressoBits/EBConsole | Runtime/Scripts/UI/Theme.cs | 520 | C# |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Describes whether existing vertex or index buffer data will be overwritten or discarded during a SetData operation.
/// </summary>
[Flags]
public enum SetDataOptions
{
/// <summary>
/// Portions of existing data in the buffer may be overwritten during this operation.
/// </summary>
None,
/// <summary>
/// The SetData operation will discard the entire buffer. A pointer to a new memory area is returned so that the direct memory access (DMA) and rendering from the previous area do not stall.
/// </summary>
Discard,
/// <summary>
/// The SetData operation will not overwrite existing data in the vertex and index buffers. Specifying this option allows the driver to return immediately from a SetData operation and continue rendering.
/// </summary>
NoOverwrite
}
class SetDataOptionsHelper
{
public static MapMode ConvertToMapMode(SetDataOptions options)
{
switch (options)
{
case SetDataOptions.None:
return MapMode.Write;
case SetDataOptions.Discard:
return MapMode.WriteDiscard;
case SetDataOptions.NoOverwrite:
return MapMode.WriteNoOverwrite;
}
return MapMode.Write;
}
}
} | 41.68254 | 211 | 0.677837 | [
"MIT"
] | VirusFree/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/SetDataOptions.cs | 2,628 | C# |
namespace Spectre.Console.Rendering;
/// <summary>
/// Contains extension methods for <see cref="BoxBorder"/>.
/// </summary>
public static class BoxExtensions
{
/// <summary>
/// Gets the safe border for a border.
/// </summary>
/// <param name="border">The border to get the safe border for.</param>
/// <param name="safe">Whether or not to return the safe border.</param>
/// <returns>The safe border if one exist, otherwise the original border.</returns>
public static BoxBorder GetSafeBorder(this BoxBorder border, bool safe)
{
if (border is null)
{
throw new ArgumentNullException(nameof(border));
}
if (safe && border.SafeBorder != null)
{
border = border.SafeBorder;
}
return border;
}
} | 29.071429 | 87 | 0.614251 | [
"MIT"
] | BlackOfWorld/spectre.console | src/Spectre.Console/Extensions/BoxExtensions.cs | 814 | C# |
//*******************************************************************************************//
// //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer //
// //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup //
// //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved. //
// https://www.bytescout.com //
// https://pdf.co //
// //
//*******************************************************************************************//
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PDF2XLS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PDF2XLS")]
[assembly: AssemblyCopyright("Copyright � 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b445ec64-fe6a-4279-b208-a6715646bd69")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 49.297872 | 95 | 0.483815 | [
"Apache-2.0"
] | atkins126/ByteScout-SDK-SourceCode | Data Extraction Suite/C#/Convert PDF To XLS with PDF Extractor SDK/Properties/AssemblyInfo.cs | 2,320 | 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.Azure.Monitoring
{
/// <summary>
/// Manages an Monitor Action Rule which type is action group.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Azure = Pulumi.Azure;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs
/// {
/// Location = "West Europe",
/// });
/// var exampleActionGroup = new Azure.Monitoring.ActionGroup("exampleActionGroup", new Azure.Monitoring.ActionGroupArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// ShortName = "exampleactiongroup",
/// });
/// var exampleActionRuleActionGroup = new Azure.Monitoring.ActionRuleActionGroup("exampleActionRuleActionGroup", new Azure.Monitoring.ActionRuleActionGroupArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// ActionGroupId = exampleActionGroup.Id,
/// Scope = new Azure.Monitoring.Inputs.ActionRuleActionGroupScopeArgs
/// {
/// Type = "ResourceGroup",
/// ResourceIds =
/// {
/// exampleResourceGroup.Id,
/// },
/// },
/// Tags =
/// {
/// { "foo", "bar" },
/// },
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Monitor Action Rule can be imported using the `resource id`, e.g.
///
/// ```sh
/// $ pulumi import azure:monitoring/actionRuleActionGroup:ActionRuleActionGroup example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AlertsManagement/actionRules/actionRule1
/// ```
/// </summary>
public partial class ActionRuleActionGroup : Pulumi.CustomResource
{
/// <summary>
/// Specifies the resource id of monitor action group.
/// </summary>
[Output("actionGroupId")]
public Output<string> ActionGroupId { get; private set; } = null!;
/// <summary>
/// A `condition` block as defined below.
/// </summary>
[Output("condition")]
public Output<Outputs.ActionRuleActionGroupCondition?> Condition { get; private set; } = null!;
/// <summary>
/// Specifies a description for the Action Rule.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// Is the Action Rule enabled? Defaults to `true`.
/// </summary>
[Output("enabled")]
public Output<bool?> Enabled { get; private set; } = null!;
/// <summary>
/// Specifies the name of the Monitor Action Rule. Changing this forces a new resource to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Specifies the name of the resource group in which the Monitor Action Rule should exist. Changing this forces a new resource to be created.
/// </summary>
[Output("resourceGroupName")]
public Output<string> ResourceGroupName { get; private set; } = null!;
/// <summary>
/// A `scope` block as defined below.
/// </summary>
[Output("scope")]
public Output<Outputs.ActionRuleActionGroupScope?> Scope { get; private set; } = null!;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Create a ActionRuleActionGroup resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ActionRuleActionGroup(string name, ActionRuleActionGroupArgs args, CustomResourceOptions? options = null)
: base("azure:monitoring/actionRuleActionGroup:ActionRuleActionGroup", name, args ?? new ActionRuleActionGroupArgs(), MakeResourceOptions(options, ""))
{
}
private ActionRuleActionGroup(string name, Input<string> id, ActionRuleActionGroupState? state = null, CustomResourceOptions? options = null)
: base("azure:monitoring/actionRuleActionGroup:ActionRuleActionGroup", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ActionRuleActionGroup resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ActionRuleActionGroup Get(string name, Input<string> id, ActionRuleActionGroupState? state = null, CustomResourceOptions? options = null)
{
return new ActionRuleActionGroup(name, id, state, options);
}
}
public sealed class ActionRuleActionGroupArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the resource id of monitor action group.
/// </summary>
[Input("actionGroupId", required: true)]
public Input<string> ActionGroupId { get; set; } = null!;
/// <summary>
/// A `condition` block as defined below.
/// </summary>
[Input("condition")]
public Input<Inputs.ActionRuleActionGroupConditionArgs>? Condition { get; set; }
/// <summary>
/// Specifies a description for the Action Rule.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Is the Action Rule enabled? Defaults to `true`.
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// Specifies the name of the Monitor Action Rule. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Specifies the name of the resource group in which the Monitor Action Rule should exist. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// A `scope` block as defined below.
/// </summary>
[Input("scope")]
public Input<Inputs.ActionRuleActionGroupScopeArgs>? Scope { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public ActionRuleActionGroupArgs()
{
}
}
public sealed class ActionRuleActionGroupState : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the resource id of monitor action group.
/// </summary>
[Input("actionGroupId")]
public Input<string>? ActionGroupId { get; set; }
/// <summary>
/// A `condition` block as defined below.
/// </summary>
[Input("condition")]
public Input<Inputs.ActionRuleActionGroupConditionGetArgs>? Condition { get; set; }
/// <summary>
/// Specifies a description for the Action Rule.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// Is the Action Rule enabled? Defaults to `true`.
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// Specifies the name of the Monitor Action Rule. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Specifies the name of the resource group in which the Monitor Action Rule should exist. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName")]
public Input<string>? ResourceGroupName { get; set; }
/// <summary>
/// A `scope` block as defined below.
/// </summary>
[Input("scope")]
public Input<Inputs.ActionRuleActionGroupScopeGetArgs>? Scope { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public ActionRuleActionGroupState()
{
}
}
}
| 38.182143 | 228 | 0.576747 | [
"ECL-2.0",
"Apache-2.0"
] | suresh198526/pulumi-azure | sdk/dotnet/Monitoring/ActionRuleActionGroup.cs | 10,691 | 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.460)
// Version 5.460.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Collections;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace ComponentFactory.Krypton.Toolkit
{
internal class KryptonBreadCrumbDesigner : ControlDesigner
{
#region Instance Fields
private bool _lastHitTest;
private KryptonBreadCrumb _breadCrumb;
private IDesignerHost _designerHost;
private IComponentChangeService _changeService;
private ISelectionService _selectionService;
#endregion
#region Public Overrides
/// <summary>
/// Initializes the designer with the specified component.
/// </summary>
/// <param name="component">The IComponent to associate the designer with.</param>
public override void Initialize(IComponent component)
{
// Validate the parameter reference
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
// Let base class do standard stuff
base.Initialize(component);
// The resizing handles around the control need to change depending on the
// value of the AutoSize and AutoSizeMode properties. When in AutoSize you
// do not get the resizing handles, otherwise you do.
AutoResizeHandles = true;
// Cast to correct type
_breadCrumb = component as KryptonBreadCrumb;
if (_breadCrumb != null)
{
// Hook into bread crumb events
_breadCrumb.GetViewManager().MouseUpProcessed += OnBreadCrumbMouseUp;
_breadCrumb.GetViewManager().DoubleClickProcessed += OnBreadCrumbDoubleClick;
}
// Get access to the design services
_designerHost = (IDesignerHost)GetService(typeof(IDesignerHost));
_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
_selectionService = (ISelectionService)GetService(typeof(ISelectionService));
// We need to know when we are being removed
_changeService.ComponentRemoving += OnComponentRemoving;
}
/// <summary>
/// Gets the collection of components associated with the component managed by the designer.
/// </summary>
public override ICollection AssociatedComponents
{
get
{
ArrayList compound = new ArrayList(base.AssociatedComponents);
if (_breadCrumb != null)
{
compound.AddRange(_breadCrumb.ButtonSpecs);
compound.AddRange(_breadCrumb.RootItem.Items);
}
return compound;
}
}
/// <summary>
/// Gets the design-time action lists supported by the component associated with the designer.
/// </summary>
public override DesignerActionListCollection ActionLists
{
get
{
// Create a collection of action lists
DesignerActionListCollection actionLists = new DesignerActionListCollection
{
// Add the bread crumb specific list
new KryptonBreadCrumbActionList(this)
};
return actionLists;
}
}
#endregion
#region Protected Overrides
/// <summary>
/// Releases all resources used by the component.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
// Unhook from events
if (_breadCrumb != null)
{
_breadCrumb.GetViewManager().MouseUpProcessed -= OnBreadCrumbMouseUp;
_breadCrumb.GetViewManager().DoubleClickProcessed -= OnBreadCrumbDoubleClick;
}
_changeService.ComponentRemoving -= OnComponentRemoving;
// Must let base class do standard stuff
base.Dispose(disposing);
}
/// <summary>
/// Indicates whether a mouse click at the specified point should be handled by the control.
/// </summary>
/// <param name="point">A Point indicating the position at which the mouse was clicked, in screen coordinates.</param>
/// <returns>true if a click at the specified point is to be handled by the control; otherwise, false.</returns>
protected override bool GetHitTest(Point point)
{
if (_breadCrumb != null)
{
// Ask the control if it wants to process the point
bool ret = _breadCrumb.DesignerGetHitTest(_breadCrumb.PointToClient(point));
// If the navigator does not want the mouse point then make sure the
// tracking element is informed that the mouse has left the control
if (!ret && _lastHitTest)
{
_breadCrumb.DesignerMouseLeave();
}
// Cache the last answer recovered
_lastHitTest = ret;
return ret;
}
else
{
return false;
}
}
/// <summary>
/// Receives a call when the mouse leaves the control.
/// </summary>
protected override void OnMouseLeave()
{
_breadCrumb?.DesignerMouseLeave();
base.OnMouseLeave();
}
#endregion
#region Implementation
private void OnBreadCrumbMouseUp(object sender, MouseEventArgs e)
{
if ((_breadCrumb != null) && (e.Button == MouseButtons.Left))
{
// Get any component associated with the current mouse position
Component component = _breadCrumb.DesignerComponentFromPoint(new Point(e.X, e.Y));
if (component != null)
{
// Force the layout to be update for any change in selection
_breadCrumb.PerformLayout();
// Select the component
ArrayList selectionList = new ArrayList
{
component
};
_selectionService.SetSelectedComponents(selectionList, SelectionTypes.Auto);
}
}
}
private void OnBreadCrumbDoubleClick(object sender, Point pt)
{
// Get any component associated with the current mouse position
Component component = _breadCrumb?.DesignerComponentFromPoint(pt);
if (component != null)
{
// Get the designer for the component
IDesigner designer = _designerHost.GetDesigner(component);
// Request code for the default event be generated
designer.DoDefaultAction();
}
}
private void OnComponentRemoving(object sender, ComponentEventArgs e)
{
// If our control is being removed
if ((_breadCrumb != null) && (e.Component == _breadCrumb))
{
// Need access to host in order to delete a component
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
// We need to remove all the button spec instances
for (int i = _breadCrumb.ButtonSpecs.Count - 1; i >= 0; i--)
{
// Get access to the indexed button spec
ButtonSpec spec = _breadCrumb.ButtonSpecs[i];
// Must wrap button spec removal in change notifications
_changeService.OnComponentChanging(_breadCrumb, null);
// Perform actual removal of button spec from bread crumb
_breadCrumb.ButtonSpecs.Remove(spec);
// Get host to remove it from design time
host.DestroyComponent(spec);
// Must wrap button spec removal in change notifications
_changeService.OnComponentChanged(_breadCrumb, null, null, null);
}
}
}
#endregion
}
}
| 38.564315 | 157 | 0.573596 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.460 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Designers/KryptonBreadCrumbDesigner.cs | 9,297 | C# |
using CSRedis;
using Microsoft.Extensions.Configuration;
using OptionsPractice.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OptionsPractice.Extension
{
public static class RedisConfigurationExtensions
{
public static IConfigurationBuilder AddRedisConfiguration(this IConfigurationBuilder builder, RedisConfigurationOptions options)
{
return builder.Add(new RedisConfigurationSource(options));
}
}
}
| 28.263158 | 137 | 0.746741 | [
"MIT"
] | Regularly-Archive/2020 | src/OptionsPractice/Extension/RedisConfigurationExtensions.cs | 539 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Linq;
using System.Security;
using MappingEdu.Common.Exceptions;
using MappingEdu.Core.Domain;
using MappingEdu.Core.Domain.Security;
using MappingEdu.Core.Repositories;
using MappingEdu.Service.Model.MappingProject;
namespace MappingEdu.Service.MappingProjects
{
public interface IMappingProjectTemplateService
{
void Delete(Guid mappingProjectId, Guid templateId);
MappingProjectTemplateModel Get(Guid templateId, Guid mappingProjectId);
MappingProjectTemplateModel[] Get(Guid mappingProjectId);
MappingProjectTemplateModel Post(Guid mappingProjectId, MappingProjectTemplateModel model);
MappingProjectTemplateModel Put(Guid mappingProjectId, Guid synonymId, MappingProjectTemplateModel model);
}
public class MappingProjectTemplateService : IMappingProjectTemplateService
{
private readonly IRepository<MappingProjectTemplate> _templateRepository;
private readonly IMappingProjectRepository _mappingProjectRepository;
public MappingProjectTemplateService(IRepository<MappingProjectTemplate> templateRepository, IMappingProjectRepository mappingProjectRepository)
{
_templateRepository = templateRepository;
_mappingProjectRepository = mappingProjectRepository;
}
public MappingProjectTemplateModel Get(Guid templateId, Guid mappingProjectId)
{
var template = GetTemplate(templateId, mappingProjectId);
return new MappingProjectTemplateModel
{
MappingProjectTemplateId = template.MappingProjectTemplateId,
MappingProjectId = template.MappingProjectId,
Template = template.Template,
Title = template.Title
};
}
public MappingProjectTemplateModel[] Get(Guid mappingProjectId)
{
var mappingProject = GetMappingProject(mappingProjectId);
var synonyms = _templateRepository.GetAllQueryable().Where(x => x.MappingProjectId == mappingProjectId);
return synonyms.ToList().Select(x =>
new MappingProjectTemplateModel
{
MappingProjectTemplateId = x.MappingProjectTemplateId,
MappingProjectId = x.MappingProjectId,
Template = x.Template,
Title = x.Title
}).ToArray();
}
public MappingProjectTemplateModel Post(Guid mappingProjectId, MappingProjectTemplateModel model)
{
GetMappingProject(mappingProjectId, MappingProjectUser.MappingProjectUserRole.Edit);
var template = new MappingProjectTemplate
{
MappingProjectId = mappingProjectId,
Title = model.Title,
Template = model.Template
};
_templateRepository.Add(template);
_templateRepository.SaveChanges();
model.MappingProjectTemplateId = template.MappingProjectTemplateId;
return model;
}
public MappingProjectTemplateModel Put(Guid mappingProjectId, Guid templateId, MappingProjectTemplateModel model)
{
var template = GetTemplate(templateId, mappingProjectId, MappingProjectUser.MappingProjectUserRole.Edit);
template.Template = model.Template;
template.Title = model.Title;
_templateRepository.SaveChanges();
return model;
}
public void Delete(Guid mappingProjectId, Guid templateId)
{
var template = GetTemplate(templateId, mappingProjectId, MappingProjectUser.MappingProjectUserRole.Edit);
_templateRepository.Delete(template);
_templateRepository.SaveChanges();
}
private MappingProject GetMappingProject(Guid mappingProjectId, MappingProjectUser.MappingProjectUserRole role = MappingProjectUser.MappingProjectUserRole.Guest)
{
var mappingProject = _mappingProjectRepository.Get(mappingProjectId);
if (null == mappingProject)
throw new NotFoundException(string.Format("Mapping Project with id '{0}' does not exist.", mappingProjectId));
if (!Principal.Current.IsAdministrator && !mappingProject.HasAccess(role))
throw new SecurityException(String.Format("User needs at least {0} Access to peform this action", role));
return mappingProject;
}
private MappingProjectTemplate GetTemplate(Guid templateId, Guid mappingProjectId, MappingProjectUser.MappingProjectUserRole role = MappingProjectUser.MappingProjectUserRole.Guest)
{
var template = _templateRepository.Get(templateId);
if (null == template)
throw new NotFoundException(string.Format("Mapping Project Template with id '{0}' does not exist.", templateId));
if (template.MappingProjectId != mappingProjectId)
throw new NotFoundException(string.Format("Mapping Project with id '{0}' does not have Mapping Project Template of '{1}'.", mappingProjectId, templateId));
if (!Principal.Current.IsAdministrator && !template.MappingProject.HasAccess(role))
throw new SecurityException(String.Format("User needs at least {0} Access to peform this action", role));
return template;
}
}
} | 42.902256 | 188 | 0.68647 | [
"Apache-2.0"
] | Ed-Fi-Exchange-OSS/MappingEDU | src/MappingEdu.Service/MappingProjects/MappingProjectTemplateService.cs | 5,708 | C# |
using System.Diagnostics;
using Discord.WebSocket;
namespace HoLLy.DiscordBot.Permissions.Conditions.Users
{
[DebuggerDisplay("DEFAULTUSER")]
internal class DefaultUserCondition : IUserCondition
{
public bool Match(SocketUser user, ISocketMessageChannel c) => true;
}
}
| 24.666667 | 76 | 0.746622 | [
"BSD-3-Clause"
] | HoLLy-HaCKeR/DiscordBotV5 | DiscordBot5/Permissions/Conditions/Users/DefaultUserCondition.cs | 298 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.ContractsLight;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Threading.Tasks;
using BuildXL.Engine.Cache;
using BuildXL.Engine.Serialization;
using BuildXL.Native.IO;
using BuildXL.Pips;
using BuildXL.Scheduler;
using BuildXL.Scheduler.Graph;
using BuildXL.Utilities;
using BuildXL.Utilities.Instrumentation.Common;
using BuildXL.Utilities.Qualifier;
using BuildXL.Utilities.Serialization;
using BuildXL.Utilities.Configuration;
namespace BuildXL.Engine
{
/// <summary>
/// Helper saving and loading engine state between runs
/// </summary>
public sealed class EngineSerializer
{
#region FileNames
internal const string PathTableFile = "PathTable";
internal const string StringTableFile = "StringTable";
internal const string SymbolTableFile = "SymbolTable";
internal const string QualifierTableFile = "QualifierTable";
internal const string PipTableFile = "PipTable";
internal const string PreviousInputsFile = "PreviousInputs";
internal const string PreviousInputsJournalCheckpointFile = "PreviousInputsJournalCheckpoint";
internal const string PreviousInputsIntermediateFile = "PreviousInputs.tmp";
internal const string MountPathExpanderFile = "MountPathExpander";
internal const string ConfigFileStateFile = "ConfigFileState";
internal const string RunningTimeTableFile = "RunningTimeTable";
internal const string DirectedGraphFile = "DirectedGraph";
internal const string PipGraphFile = "PipGraph";
internal const string PipGraphIdFile = "PipGraphId";
internal const string HistoricTableSizes = "HistoricTableSizes";
internal const string SchedulerDirtyNodesCheckpointFile = "SchedulerDirtyNodesCheckpoint";
internal const string SchedulerJournalCheckpointFile = "SchedulerJournalCheckpoint";
internal const string EngineStateFile = "EngineState";
internal const string HistoricMetadataCacheLocation = "HistoricMetadataCache";
internal const string CorruptFilesLogLocation = "Error-CorruptState";
#endregion
private readonly string m_engineCacheLocation;
private readonly bool m_debug;
private readonly List<Task<SerializationResult>> m_serializationTasks = new List<Task<SerializationResult>>();
private readonly List<Task> m_deserializationTasks = new List<Task>();
private readonly object m_deserializationSyncObject = new object();
private long m_bytesDeserialized;
private long m_bytesSerialized;
private long m_bytesSavedDueToCompression;
private object m_correlationId;
private readonly bool m_useCompression;
private readonly FileSystemStreamProvider m_readStreamProvider;
private readonly ITempDirectoryCleaner m_tempDirectoryCleaner;
/// <summary>
/// Constructor
/// </summary>
public EngineSerializer(
LoggingContext loggingContext,
string engineCacheLocation,
FileEnvelopeId? correlationId = null,
bool useCompression = false,
bool debug = false,
bool readOnly = false,
FileSystemStreamProvider readStreamProvider = null,
ITempDirectoryCleaner tempDirectoryCleaner = null)
{
Contract.Requires(loggingContext != null);
Contract.Requires(engineCacheLocation != null);
Contract.Requires(Path.IsPathRooted(engineCacheLocation));
Contract.Requires(!string.IsNullOrWhiteSpace(engineCacheLocation));
LoggingContext = loggingContext;
m_engineCacheLocation = engineCacheLocation;
m_debug = debug;
m_correlationId = correlationId;
m_useCompression = useCompression;
m_readStreamProvider = readStreamProvider ?? FileSystemStreamProvider.Default;
m_tempDirectoryCleaner = tempDirectoryCleaner;
if (!readOnly)
{
try
{
FileUtilities.CreateDirectoryWithRetry(engineCacheLocation);
}
catch (Exception ex)
{
ExceptionRootCause rootCause = ExceptionUtilities.AnalyzeExceptionRootCause(ex);
BuildXL.Tracing.Logger.Log.UnexpectedCondition(LoggingContext, ex.ToStringDemystified() + Environment.NewLine + rootCause);
throw new BuildXLException("Unable to create engine serializer cache directory: ", ex);
}
}
}
internal char EngineCacheDriveLetter => m_engineCacheLocation[0];
internal string PreviousInputsIntermediate => Path.Combine(m_engineCacheLocation, PreviousInputsIntermediateFile);
internal string PreviousInputsFinalized => Path.Combine(m_engineCacheLocation, PreviousInputsFile);
internal string PreviousInputsJournalCheckpoint => Path.Combine(m_engineCacheLocation, PreviousInputsJournalCheckpointFile);
/// <summary>
/// Count of total bytes deserialized
/// </summary>
internal long BytesDeserialized => Volatile.Read(ref m_bytesDeserialized);
/// <summary>
/// Count of total bytes serialized
/// </summary>
internal long BytesSerialized => Volatile.Read(ref m_bytesSerialized);
/// <summary>
/// Count of total bytes saved due to compression
/// </summary>
internal long BytesSavedDueToCompression => Volatile.Read(ref m_bytesSavedDueToCompression);
/// <summary>
/// The logging context used during serialization
/// </summary>
internal LoggingContext LoggingContext { get; }
/// <summary>
/// Moves the PreviousInputs file from the temp location to its final location.
/// </summary>
internal bool FinalizePreviousInputsFile()
{
try
{
if (!File.Exists(PreviousInputsIntermediate))
{
Contract.Assume(false, "Intermediate PreviousInputs file did not exist at " + PreviousInputsIntermediate);
}
FileUtilities.MoveFileAsync(PreviousInputsIntermediate, PreviousInputsFinalized, replaceExisting: true).Wait();
return true;
}
catch (BuildXLException)
{
return false;
}
}
/// <summary>
/// Tries to delete previous input journal checkpoint file.
/// </summary>
internal bool TryDeletePreviousInputsJournalCheckpointFile()
{
return FileUtilities.TryDeleteFile(PreviousInputsJournalCheckpoint, waitUntilDeletionFinished: true, tempDirectoryCleaner: m_tempDirectoryCleaner).Succeeded;
}
internal IList<Task<SerializationResult>> SerializationTasks => m_serializationTasks;
internal async Task WaitForPendingDeserializationsAsync()
{
int index = 0;
while (true)
{
Task deserializationTask;
lock (m_deserializationSyncObject)
{
var count = m_deserializationTasks.Count;
if (index >= count)
{
break;
}
deserializationTask = m_deserializationTasks[index];
}
await deserializationTask;
index++;
}
}
/// <summary>
/// Gets the full path to a serializable file given its label
/// </summary>
internal string GetFullPath(string objectLabel)
{
return Path.Combine(m_engineCacheLocation, objectLabel);
}
/// <summary>
/// Gets the full path to a serializable file given its file type
/// </summary>
internal string GetFullPath(GraphCacheFile fileType)
{
return Path.Combine(m_engineCacheLocation, GetFileName(fileType));
}
/// <summary>
/// Creates and starts a task to deserialize an object
/// </summary>
/// <param name="file">This will become the filename</param>
/// <param name="deserializer">Deserialization function; its get a reader for the file stream, and a function that allows obtaining additional streams if needed</param>
/// <param name="skipHeader">If enabled, the correlation id is not checked for consistency</param>
/// <returns>task for deserialized value</returns>
internal Task<TObject> DeserializeFromFileAsync<TObject>(
GraphCacheFile file,
Func<BuildXLReader, Task<TObject>> deserializer,
bool skipHeader = false)
{
var task = Task.Run(
async () =>
{
var objectLabel = GetFileName(file);
string path = GetFullPath(objectLabel);
FileEnvelope fileEnvelope = GetFileEnvelope(file);
var result = default(TObject);
try
{
Stopwatch sw = Stopwatch.StartNew();
using (var fileStreamWrapper = m_readStreamProvider.OpenReadStream(path))
{
var fileStream = fileStreamWrapper.Value;
FileEnvelopeId persistedCorrelationId = fileEnvelope.ReadHeader(fileStream);
if (!skipHeader)
{
// We are going to check if all files that are going to be (concurrently) deserialized have matching correlation ids.
// The first discovered correlation id is going to be used to check all others.
if (m_correlationId == null)
{
Interlocked.CompareExchange(ref m_correlationId, persistedCorrelationId, null);
}
FileEnvelope.CheckCorrelationIds(persistedCorrelationId, (FileEnvelopeId)m_correlationId);
}
var isCompressed = fileStream.ReadByte() == 1;
using (Stream readStream = isCompressed ? new DeflateStream(fileStream, CompressionMode.Decompress) : fileStream)
using (BuildXLReader reader = new BuildXLReader(m_debug, readStream, leaveOpen: false))
{
result = await deserializer(reader);
}
}
Tracing.Logger.Log.DeserializedFile(LoggingContext, path, sw.ElapsedMilliseconds);
return result;
}
catch (BuildXLException ex)
{
if (ex.InnerException is FileNotFoundException)
{
// Files might be deleted manually in the EngineCache directory. Log it as verbose.
Tracing.Logger.Log.FailedToDeserializeDueToFileNotFound(LoggingContext, path);
return result;
}
Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.LogEventMessage);
return result;
}
catch (IOException ex)
{
Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.Message);
return result;
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception ex)
{
// There are 2 reasons to be here.
// 1. A malformed file can cause ContractException, IndexOutOfRangeException, MemoryException or something else.
// 2. We may have a bug.
// Since the malformed file will always cause a crash until someone removes the file from the cache, allow BuildXL to recover
// by eating the exception. However remember to log it in order to keep track of bugs.
ExceptionRootCause rootCause = ExceptionUtilities.AnalyzeExceptionRootCause(ex);
BuildXL.Tracing.Logger.Log.UnexpectedCondition(LoggingContext, ex.ToStringDemystified() + Environment.NewLine + rootCause);
Tracing.Logger.Log.FailedToDeserializePipGraph(LoggingContext, path, ex.Message);
return result;
}
});
lock (m_deserializationSyncObject)
{
m_deserializationTasks.Add(task);
}
return task;
}
/// <summary>
/// Creates and starts a task to serialize an object.
/// </summary>
/// <param name="fileType">Type for the object to serialize. This will become the filename</param>
/// <param name="serializer">Serialization action to perform</param>
/// <param name="overrideName">Overrides the default file name for the file type. This is used to atomically write some files (via renames)</param>
/// <returns>whether serialization was successful</returns>
internal Task<SerializationResult> SerializeToFileAsync(
GraphCacheFile fileType,
Action<BuildXLWriter> serializer,
string overrideName = null)
{
var task = SerializeToFileInternal(fileType, serializer, overrideName);
SerializationTasks.Add(task);
return task;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:DoNotDisposeObjectsMultipleTimes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("AsyncUsage", "AsyncFixer02:MissingAsyncOpportunity")]
private async Task<SerializationResult> SerializeToFileInternal(GraphCacheFile fileType, Action<BuildXLWriter> serializer, string overrideName)
{
// Unblock the caller
await Task.Yield();
FileUtilities.CreateDirectory(m_engineCacheLocation);
string fileName = overrideName ?? GetFileName(fileType);
string path = Path.Combine(m_engineCacheLocation, fileName);
SerializationResult serializationResult = new SerializationResult()
{
Success = false,
FileType = fileType,
FullPath = path,
};
var fileEnvelope = GetFileEnvelope(fileType);
Contract.Assume(m_correlationId is FileEnvelopeId, "EngineSerializer must be initialized with a valid correlation id");
var correlationId = (FileEnvelopeId)m_correlationId;
try
{
// We must delete the existing file in case it was hardlinked from the cache. Opening a filestream
// that truncates the existing file will fail if it is a hardlink.
FileUtilities.DeleteFile(path, tempDirectoryCleaner: m_tempDirectoryCleaner);
using (
FileStream fileStream = FileUtilities.CreateFileStream(
path,
FileMode.Create,
FileAccess.Write,
FileShare.Delete,
// Do not write the file with SequentialScan since it will be reread in the subsequent build
FileOptions.None))
{
Stopwatch sw = Stopwatch.StartNew();
fileEnvelope.WriteHeader(fileStream, correlationId);
// Write whether the file is compressed or not.
fileStream.WriteByte(m_useCompression ? (byte)1 : (byte)0);
long uncompressedLength = 0;
if (m_useCompression)
{
using (var writer = new BuildXLWriter(m_debug, new TrackedStream(new DeflateStream(fileStream, CompressionLevel.Fastest, leaveOpen: true)), false, false))
{
// TODO: We can improve performance significantly by parallelizing the compression.
// There's no setting to do that, but given you have the entire file content upfront in a memory stream,
// it shouldn't be particularly complicated to split the memory stream into reasonably sized chunks (say 100MB)
// and compress each of them into separate MemoryStream backed DeflateStreams in separate threads.
// Then just write those out to a file. Of course you'll need to write out the position of those streams
// into the header when you write out the actual file.
serializer(writer);
uncompressedLength = writer.BaseStream.Length;
}
}
else
{
using (var writer = new BuildXLWriter(m_debug, fileStream, leaveOpen: true, logStats: false))
{
serializer(writer);
uncompressedLength = writer.BaseStream.Length;
}
}
Interlocked.Add(ref m_bytesSavedDueToCompression, uncompressedLength - fileStream.Length);
fileEnvelope.FixUpHeader(fileStream, correlationId);
Tracing.Logger.Log.SerializedFile(LoggingContext, fileName, sw.ElapsedMilliseconds);
serializationResult.Success = true;
Interlocked.Add(ref m_bytesSerialized, fileStream.Position);
}
}
catch (BuildXLException ex)
{
Tracing.Logger.Log.FailedToSerializePipGraph(LoggingContext, ex.LogEventMessage);
}
catch (IOException ex)
{
Tracing.Logger.Log.FailedToSerializePipGraph(LoggingContext, ex.Message);
}
return serializationResult;
}
private static FileEnvelope GetFileEnvelope(GraphCacheFile fileType)
{
switch (fileType)
{
case GraphCacheFile.PreviousInputs:
return InputTracker.FileEnvelope;
case GraphCacheFile.PipTable:
return PipTable.FileEnvelope;
case GraphCacheFile.PathTable:
return PathTable.FileEnvelope;
case GraphCacheFile.StringTable:
return StringTable.FileEnvelope;
case GraphCacheFile.SymbolTable:
return SymbolTable.FileEnvelope;
case GraphCacheFile.QualifierTable:
return QualifierTable.FileEnvelope;
case GraphCacheFile.MountPathExpander:
return MountPathExpander.FileEnvelope;
case GraphCacheFile.ConfigState:
return ConfigFileState.FileEnvelope;
case GraphCacheFile.DirectedGraph:
return DirectedGraph.FileEnvelope;
case GraphCacheFile.PipGraph:
return PipGraph.FileEnvelopeGraph;
case GraphCacheFile.PipGraphId:
return PipGraph.FileEnvelopeGraphId;
case GraphCacheFile.HistoricTableSizes:
return EngineContext.HistoricTableSizesFileEnvelope;
default:
throw Contract.AssertFailure("Unhandled GraphCacheFile");
}
}
private static string GetFileName(GraphCacheFile fileType)
{
switch (fileType)
{
case GraphCacheFile.PreviousInputs:
return PreviousInputsFile;
case GraphCacheFile.PipTable:
return PipTableFile;
case GraphCacheFile.PathTable:
return PathTableFile;
case GraphCacheFile.StringTable:
return StringTableFile;
case GraphCacheFile.SymbolTable:
return SymbolTableFile;
case GraphCacheFile.QualifierTable:
return QualifierTableFile;
case GraphCacheFile.MountPathExpander:
return MountPathExpanderFile;
case GraphCacheFile.ConfigState:
return ConfigFileStateFile;
case GraphCacheFile.DirectedGraph:
return DirectedGraphFile;
case GraphCacheFile.PipGraph:
return PipGraphFile;
case GraphCacheFile.PipGraphId:
return PipGraphIdFile;
case GraphCacheFile.HistoricTableSizes:
return HistoricTableSizes;
default:
throw Contract.AssertFailure("Unhandled GraphCacheFile");
}
}
/// <summary>
/// When a corruption is detected, moves the engine state into the logs directory for future debugging
/// and to prevent the corrupt state from impacting future builds.
/// </summary>
public static bool TryLogAndRemoveCorruptEngineState(IConfiguration configuration, PathTable pathTable, LoggingContext loggingContext)
{
var engineCache = configuration.Layout.EngineCacheDirectory.ToString(pathTable);
var fileContentTableFile = configuration.Layout.FileContentTableFile.ToString(pathTable);
bool success = true;
// Non-recursive directory enumeration to prevent deleting folders which are persisted build-over-build in the engine cache
// but are not engine state (ex: HistoricMetadatCache and FingerprintStore)
FileUtilities.EnumerateDirectoryEntries(engineCache, (fileName, attributes) =>
{
if (!FileUtilities.IsDirectoryNoFollow(attributes))
{
var filePath = Path.Combine(engineCache, fileName);
success &= SchedulerUtilities.TryLogAndMaybeRemoveCorruptFile(
filePath,
configuration,
pathTable,
loggingContext,
removeFile: filePath != fileContentTableFile /* exclude the file content table which can impact performance significantly if deleted */);
}
});
return success;
}
/// <summary>
/// Result from serialization
/// </summary>
internal struct SerializationResult
{
/// <summary>
/// Whether serialization was successful
/// </summary>
public bool Success;
/// <summary>
/// Type of file serialized, as understood by the underlying graph-cache.
/// </summary>
public GraphCacheFile FileType;
/// <summary>
/// Full path of file written to disk
/// </summary>
public string FullPath;
}
}
}
| 46.163842 | 179 | 0.574838 | [
"MIT"
] | MatisseHack/BuildXL | Public/Src/Engine/Dll/Serialization/EngineSerializer.cs | 24,513 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Objects
{
/// <summary>
/// Thank You Info
/// </summary>
public class ThankYouInfo
{
/// <summary>
/// Gets or sets Text.
/// </summary>
public string Text
{
get;
set;
}
/// <summary>
/// Gets or sets Title.
/// </summary>
public string Title
{
get;
set;
}
/// <summary>
/// Gets or sets MessageID.
/// </summary>
public int MessageID
{
get;
set;
}
/// <summary>
/// Gets or sets ThanksInfo.
/// </summary>
public string ThanksInfo
{
get;
set;
}
/// <summary>
/// Gets or sets Thanks.
/// </summary>
public string Thanks
{
get;
set;
}
}
}
| 25.833333 | 64 | 0.540943 | [
"Apache-2.0"
] | 10by10pixel/YAFNET | yafsrc/YAF.Types/Objects/ThankYouInfo.cs | 1,941 | C# |
using System;
using System.Text;
namespace Eto.Parse.Samples.Markdown
{
static class Extensions
{
public static void AppendUnixLine(this StringBuilder builder)
{
builder.Append('\n');
}
public static void AppendUnixLine(this StringBuilder builder, string line)
{
builder.Append(line);
builder.Append('\n');
}
}
}
| 16.190476 | 76 | 0.711765 | [
"MIT"
] | ArsenShnurkov/Eto.Parse | Eto.Parse.Samples/Markdown/Extensions.cs | 340 | 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 mediapackage-vod-2018-11-07.normal.json service model.
*/
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.MediaPackageVod;
using Amazon.MediaPackageVod.Model;
using Amazon.MediaPackageVod.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public partial class MediaPackageVodMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("mediapackage-vod");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogsMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ConfigureLogsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ConfigureLogsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ConfigureLogs_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("ConfigureLogs");
var request = InstantiateClassGenerator.Execute<ConfigureLogsRequest>();
var marshaller = new ConfigureLogsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ConfigureLogs", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ConfigureLogsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAssetMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateAssetResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as CreateAssetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreateAsset_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreateAsset");
var request = InstantiateClassGenerator.Execute<CreateAssetRequest>();
var marshaller = new CreateAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreateAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreateAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfigurationMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreatePackagingConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as CreatePackagingConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingConfiguration_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<CreatePackagingConfigurationRequest>();
var marshaller = new CreatePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroupMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreatePackagingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as CreatePackagingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void CreatePackagingGroup_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("CreatePackagingGroup");
var request = InstantiateClassGenerator.Execute<CreatePackagingGroupRequest>();
var marshaller = new CreatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("CreatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = CreatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAssetMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DeleteAssetResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DeleteAssetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeleteAsset_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeleteAsset");
var request = InstantiateClassGenerator.Execute<DeleteAssetRequest>();
var marshaller = new DeleteAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeleteAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeleteAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfigurationMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DeletePackagingConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DeletePackagingConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingConfiguration_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DeletePackagingConfigurationRequest>();
var marshaller = new DeletePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroupMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DeletePackagingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DeletePackagingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DeletePackagingGroup_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DeletePackagingGroup");
var request = InstantiateClassGenerator.Execute<DeletePackagingGroupRequest>();
var marshaller = new DeletePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DeletePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DeletePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAssetMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribeAssetResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DescribeAssetResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribeAsset_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribeAsset");
var request = InstantiateClassGenerator.Execute<DescribeAssetRequest>();
var marshaller = new DescribeAssetRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribeAsset", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribeAssetResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfigurationMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribePackagingConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DescribePackagingConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingConfiguration_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingConfiguration");
var request = InstantiateClassGenerator.Execute<DescribePackagingConfigurationRequest>();
var marshaller = new DescribePackagingConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingConfiguration", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingConfigurationResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroupMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DescribePackagingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as DescribePackagingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void DescribePackagingGroup_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("DescribePackagingGroup");
var request = InstantiateClassGenerator.Execute<DescribePackagingGroupRequest>();
var marshaller = new DescribePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("DescribePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = DescribePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssetsMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListAssetsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListAssetsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListAssets_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListAssets");
var request = InstantiateClassGenerator.Execute<ListAssetsRequest>();
var marshaller = new ListAssetsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListAssets", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListAssetsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurationsMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPackagingConfigurationsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListPackagingConfigurationsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingConfigurations_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingConfigurations");
var request = InstantiateClassGenerator.Execute<ListPackagingConfigurationsRequest>();
var marshaller = new ListPackagingConfigurationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingConfigurations", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingConfigurationsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroupsMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListPackagingGroupsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListPackagingGroupsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListPackagingGroups_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("ListPackagingGroups");
var request = InstantiateClassGenerator.Execute<ListPackagingGroupsRequest>();
var marshaller = new ListPackagingGroupsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListPackagingGroups", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = ListPackagingGroupsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void ListTagsForResourceMarshallTest()
{
var operation = service_model.FindOperation("ListTagsForResource");
var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>();
var marshaller = new ListTagsForResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("ListTagsForResource", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as ListTagsForResourceResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void TagResourceMarshallTest()
{
var operation = service_model.FindOperation("TagResource");
var request = InstantiateClassGenerator.Execute<TagResourceRequest>();
var marshaller = new TagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("TagResource", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UntagResourceMarshallTest()
{
var operation = service_model.FindOperation("UntagResource");
var request = InstantiateClassGenerator.Execute<UntagResourceRequest>();
var marshaller = new UntagResourceRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UntagResource", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroupMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdatePackagingGroupResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context) as UpdatePackagingGroupResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_ForbiddenExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ForbiddenException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ForbiddenException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_InternalServerErrorExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("InternalServerErrorException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","InternalServerErrorException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_NotFoundExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("NotFoundException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","NotFoundException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_ServiceUnavailableExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("ServiceUnavailableException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","ServiceUnavailableException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_TooManyRequestsExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyRequestsException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","TooManyRequestsException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("MediaPackageVod")]
public void UpdatePackagingGroup_UnprocessableEntityExceptionMarshallTest()
{
var operation = service_model.FindOperation("UpdatePackagingGroup");
var request = InstantiateClassGenerator.Execute<UpdatePackagingGroupRequest>();
var marshaller = new UpdatePackagingGroupRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
TestTools.RequestValidator.Validate("UpdatePackagingGroup", request, internalRequest, service_model);
var exception = operation.Exceptions.First(e => e.Name.Equals("UnprocessableEntityException"));
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"},
{"x-amzn-ErrorType","UnprocessableEntityException"},
}
};
var payloadResponse = new JsonSampleGenerator(service_model, exception).Execute();
webResponse.Headers["Content-Length"] = UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString();
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), true, webResponse, true);
var response = UpdatePackagingGroupResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK);
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
} | 50.404792 | 152 | 0.65828 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/test/Services/MediaPackageVod/UnitTests/Generated/Marshalling/MediaPackageVodMarshallingTests.cs | 162,001 | C# |
/*
Copyright (c) 2018-2021 Festo AG & Co. KG <https://www.festo.com/net/de_de/Forms/web/contact_international>
Author: Michael Hoffmeister
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
// ReSharper disable ClassNeverInstantiated.Global
namespace AasxIntegrationBase
{
public class AasxPluginHelper
{
public static string LoadLicenseTxtFromAssemblyDir(
string licFileName = "LICENSE.txt", Assembly assy = null)
{
// expand assy?
if (assy == null)
assy = Assembly.GetExecutingAssembly();
// build fn
var fn = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(assy.Location),
licFileName);
if (File.Exists(fn))
{
var licTxt = File.ReadAllText(fn);
return licTxt;
}
// no
return "";
}
}
}
| 26.085106 | 107 | 0.606852 | [
"Apache-2.0"
] | JMayrbaeurl/aasx-package-explorer | src/AasxIntegrationBase/AasxPluginHelper.cs | 1,228 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using BlueYonder.Flights.Service.Middleware;
namespace BlueYonder.Flights.Service
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| 29.632653 | 106 | 0.663223 | [
"MIT"
] | ARambazamba/20487 | AllFiles/Mod04/DemoFiles/01 ErrorHandlingMiddleware/Starter/BlueYonder.Flights.Service/Startup.cs | 1,454 | C# |
//
// Copyright (c) 2008-2015 the Urho3D project.
// Copyright (c) 2015 Xamarin Inc
// Copyright (c) 2016 THUNDERBEAST GAMES LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Collections.Generic;
using System.Linq;
using AtomicEngine;
namespace FeatureExamples
{
public class SoundEffectsSample : Sample
{
readonly Dictionary<string, string> sounds = new Dictionary<string, string>
{
{"Fist", "Sounds/PlayerFistHit.wav"},
{"Explosion", "Sounds/BigExplosion.wav"},
{"Power-up", "Sounds/Powerup.wav"},
};
public SoundEffectsSample() : base() { }
public override void Start()
{
base.Start();
CreateUI();
}
void CreateUI()
{
var cache = GetSubsystem<ResourceCache>();
var layout = new UILayout() { Axis = UI_AXIS.UI_AXIS_Y };
layout.Rect = UIView.Rect;
UIView.AddChild(layout);
// Create a scene which will not be actually rendered, but is used to hold SoundSource components while they play sounds
scene = new Scene();
// Create buttons for playing back sounds
foreach (var item in sounds)
{
var button = new UIButton();
layout.AddChild(button);
button.Text = item.Key;
button.SubscribeToEvent<WidgetEvent>(button, e => {
if (e.Type == UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK)
{
// Get the sound resource
Sound sound = cache.Get<Sound>(item.Value);
if (sound != null)
{
// Create a scene node with a SoundSource component for playing the sound. The SoundSource component plays
// non-positional audio, so its 3D position in the scene does not matter. For positional sounds the
// SoundSource3D component would be used instead
Node soundNode = scene.CreateChild("Sound");
SoundSource soundSource = soundNode.CreateComponent<SoundSource>();
soundSource.Play(sound);
// In case we also play music, set the sound volume below maximum so that we don't clip the output
soundSource.Gain = 0.75f;
// Set the sound component to automatically remove its scene node from the scene when the sound is done playing
}
}
});
}
// Create buttons for playing/stopping music
var playMusicButton = new UIButton();
layout.AddChild(playMusicButton);
playMusicButton.Text = "Play Music";
playMusicButton.SubscribeToEvent<WidgetEvent> (playMusicButton, e => {
if (e.Type != UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK)
return;
if (scene.GetChild ("Music", false) != null)
return;
var music = cache.Get<Sound>("Music/StoryTime.ogg");
music.Looped = true;
Node musicNode = scene.CreateChild ("Music");
SoundSource musicSource = musicNode.CreateComponent<SoundSource> ();
// Set the sound type to music so that master volume control works correctly
musicSource.SetSoundType ("Music");
musicSource.Play (music);
});
var audio = GetSubsystem<Audio>();
// FIXME: Removing the music node is not stopping music
var stopMusicButton = new UIButton();
layout.AddChild(stopMusicButton);
stopMusicButton.Text = "Stop Music";
stopMusicButton.SubscribeToEvent<WidgetEvent>(stopMusicButton, e =>
{
if (e.Type != UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK)
return;
scene.RemoveChild(scene.GetChild("Music", false));
});
// Effect Volume Slider
var slider = new UISlider();
layout.AddChild(slider);
slider.SetLimits(0, 1);
slider.Text = "Sound Volume";
slider.SubscribeToEvent<WidgetEvent>(slider, e =>
{
if (e.Type != UI_EVENT_TYPE.UI_EVENT_TYPE_CHANGED)
return;
Log.Info($"Setting Effects to {slider.Value}");
audio.SetMasterGain("Effect", slider.Value);
});
// Music Volume Slider
var slider2 = new UISlider();
layout.AddChild(slider2);
slider2.SetLimits(0, 1);
slider2.Text = "Music Volume";
slider2.SubscribeToEvent<WidgetEvent>(slider2, e =>
{
if (e.Type != UI_EVENT_TYPE.UI_EVENT_TYPE_CHANGED)
return;
Log.Info($"Setting Music to {slider2.Value}");
audio.SetMasterGain("Music", slider2.Value);
});
}
}
}
| 37.929936 | 139 | 0.596306 | [
"MIT"
] | AtomicGameEngine/AtomicExamples | FeatureExamples/CSharp/Resources/Scripts/14_SoundEffects.cs | 5,955 | C# |
using System;
using System.Collections.Generic;
using Umbraco.Core.Configuration;
using umbraco.BusinessLogic.Actions;
using umbraco.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.cms.presentation.Trees;
using umbraco.interfaces;
using Umbraco.Core;
using Action = umbraco.BusinessLogic.Actions.Action;
namespace umbraco
{
/// <summary>
/// Handles loading the content tree into umbraco's application tree
/// </summary>
[Obsolete("This is no longer used and will be removed from the codebase in the future")]
//[Tree(Constants.Applications.Content, "content", "Content", silent: true)]
public class loadContent : BaseContentTree
{
public loadContent(string application)
: base(application)
{
this._StartNodeID = CurrentUser.StartNodeId;
}
private Document m_document;
private int _StartNodeID;
/// <summary>
/// Returns the Document object of the starting node for the current User. This ensures
/// that the Document object is only instantiated once.
/// </summary>
protected Document StartNode
{
get
{
if (m_document == null)
{
m_document = new Document(StartNodeID);
}
if (!m_document.Path.Contains(CurrentUser.StartNodeId.ToString()))
{
var doc = new Document(CurrentUser.StartNodeId);
if (!string.IsNullOrEmpty(doc.Path) && doc.Path.Contains(this.StartNodeID.ToString()))
{
m_document = doc;
}
else
{
return null;
}
}
return m_document;
}
}
protected override bool LoadMinimalDocument
{
get
{
return true;
}
}
/// <summary>
/// Creates the root node context menu for the content tree.
/// Depending on the current User's permissions, this menu will change.
/// If the current User's starting node is not -1 (the normal root content tree node)
/// then the menu will be built based on the permissions of the User's start node.
/// </summary>
/// <param name="actions"></param>
protected override void CreateRootNodeActions(ref List<IAction> actions)
{
actions.Clear();
if (StartNodeID != -1)
{
//get the document for the start node id
Document doc = StartNode;
if (doc == null)
{
return;
}
//get the allowed actions for the user for the current node
List<IAction> nodeActions = GetUserActionsForNode(doc);
//get the allowed actions for the tree based on the users allowed actions
List<IAction> allowedMenu = GetUserAllowedActions(AllowedActions, nodeActions);
actions.AddRange(allowedMenu);
}
else
{
// we need to get the default permissions as you can't set permissions on the very root node
List<IAction> nodeActions = Action.FromString(CurrentUser.GetPermissions("-1"));
List<IAction> allowedRootActions = new List<IAction>();
allowedRootActions.Add(ActionNew.Instance);
allowedRootActions.Add(ActionSort.Instance);
List<IAction> allowedMenu = GetUserAllowedActions(allowedRootActions, nodeActions);
actions.AddRange(allowedMenu);
if (allowedMenu.Count > 0)
actions.Add(ContextMenuSeperator.Instance);
// default actions for all users
actions.Add(ActionRePublish.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionRefresh.Instance);
//actions.Add(ActionTreeEditMode.Instance);
}
}
protected override void CreateAllowedActions(ref List<IAction> actions)
{
actions.Clear();
actions.Add(ActionNew.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionDelete.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionMove.Instance);
actions.Add(ActionCopy.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionSort.Instance);
actions.Add(ActionRollback.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionChangeDocType.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionPublish.Instance);
actions.Add(ActionToPublish.Instance);
actions.Add(ActionAssignDomain.Instance);
actions.Add(ActionRights.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionProtect.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionUnPublish.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionNotify.Instance);
actions.Add(ActionSendToTranslate.Instance);
actions.Add(ContextMenuSeperator.Instance);
actions.Add(ActionRefresh.Instance);
}
/// <summary>
/// Creates the root node for the content tree. If the current User does
/// not have access to the actual content tree root, then we'll display the
/// node that correlates to their StartNodeID
/// </summary>
/// <param name="rootNode"></param>
protected override void CreateRootNode(ref XmlTreeNode rootNode)
{
if (StartNodeID != -1)
{
Document doc = StartNode;
if (doc == null)
{
rootNode = new NullTree(this.app).RootNode;
rootNode.Text = "You do not have permission for this content tree";
rootNode.HasChildren = false;
rootNode.Source = string.Empty;
}
else
{
rootNode = CreateNode(doc, RootNodeActions);
}
}
else
{
if (IsDialog)
rootNode.Action = "javascript:openContent(-1);";
}
}
/// <summary>
/// If the user is an admin, always return entire tree structure, otherwise
/// return the user's start node id.
/// </summary>
public override int StartNodeID
{
get
{
return this._StartNodeID;
}
}
/// <summary>
/// Adds the recycling bin node. This method should only actually add the recycle bin node when the tree is initially created and if the user
/// actually has access to the root node.
/// </summary>
/// <returns></returns>
protected XmlTreeNode CreateRecycleBin()
{
if (m_id == -1 && !this.IsDialog)
{
//create a new content recycle bin tree, initialized with it's startnodeid
ContentRecycleBin bin = new ContentRecycleBin(this.m_app);
bin.ShowContextMenu = this.ShowContextMenu;
bin.id = bin.StartNodeID;
return bin.RootNode;
}
return null;
}
/// <summary>
/// Override the render method to add the recycle bin to the end of this tree
/// </summary>
/// <param name="Tree"></param>
public override void Render(ref XmlTree tree)
{
base.Render(ref tree);
XmlTreeNode recycleBin = CreateRecycleBin();
if (recycleBin != null)
tree.Add(recycleBin);
}
}
}
| 38.484018 | 150 | 0.541172 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadContent.cs | 8,430 | C# |
using System.Text;
namespace Tortuga.Dragnet;
public class VerificationStep
{
public VerificationStep(string? checkType, string message, Severity severity)
{
Message = message;
CheckType = checkType;
Severity = severity;
if (severity != Severity.Message)
StackTrace = Environment.StackTrace;
}
public Severity Severity { get; private set; }
public string? StackTrace { get; private set; }
public string? CheckType { get; private set; }
public string Message { get; private set; }
public override string ToString()
{
var result = new StringBuilder();
if (!string.IsNullOrWhiteSpace(CheckType))
result.AppendLine(CheckType);
if (!string.IsNullOrWhiteSpace(Message))
result.AppendLine(Message);
if (!string.IsNullOrWhiteSpace(StackTrace))
result.AppendLine(StackTrace);
return result.ToString();
}
}
| 24.085714 | 78 | 0.737841 | [
"MIT"
] | TortugaResearch/Anchor | Tortuga.Anchor/Tortuga.Anchor.Tests/Dragnet/VerificationStep.cs | 843 | C# |
using System.Web.Mvc;
using System.Web.Routing;
namespace Demo.Quartz3.Web.Owin
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalFilters.Filters.Add(new HandleErrorAttribute());
RouteCollection routes = RouteTable.Routes;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 28.909091 | 99 | 0.577044 | [
"MIT"
] | MyTkme/CrystalQuartz | src/Demo.Quartz3.Web.Owin/Global.asax.cs | 638 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace RepoInsight.BusinessLogic.Repository
{
/// <summary>
/// Contains methods to create <see cref="IRepoObjectInfo"/> objects for an repository.
/// </summary>
public interface IRepoObjectInfoFactory
{
/// <summary>
/// Creates a list of <see cref="IRepoObjectInfo"/> for the given repository.
/// </summary>
/// <param name="repositoryPath">
/// The path to the repository.
/// This can be a path on the file system, an url or even a single file depending on the implementation of the factory.
/// </param>
/// <returns>A list of <see cref="IRepoObjectInfo"/>.</returns>
List<IRepoObjectInfo> CreateObjectInfos(string repositoryPath);
}
}
| 35.26087 | 127 | 0.649815 | [
"MIT"
] | Aeddi13/RepoInsight | RepoInsight.BusinessLogic/Repository/IRepoObjectInfoFactory.cs | 813 | C# |
using eCommerceStarterCode.Data;
using eCommerceStarterCode.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace eCommerceStarterCode.Controllers
{
[Route("api/products")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET <baseurl>/api/products
[HttpGet]
public IActionResult GetAllProducts()
{
var products = _context.Products;
return Ok(products);
}
// POST <baseurl>/api/products
[HttpPost, Authorize]
public IActionResult Post([FromBody] Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
//return StatusCode(201, value);
return Ok(product);
}
// GET api/products
[HttpGet("{productId}")]
public IActionResult GetProductbyId(int productId)
{
var products = _context.Products
.Where(p => p.Id == productId)
.SingleOrDefault();
return Ok(products);
}
}
}
| 26.851852 | 63 | 0.621379 | [
"MIT"
] | almessier/ClothingECommerceBackEnd | eCommerceStarterCode/Controllers/ProductsController.cs | 1,452 | C# |
using UnityEngine;
using System.Collections;
public class UIControllerMainScene : MonoBehaviour {
public GameObject office;
public GameObject bedroom;
private Player player;
private const string OFFICE = "office";
private const string BEDROOM = "bedroom";
void Start () {
this.player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
}
void Update() {
foreach (Collectible item in player.inventory.items) {
if (item.identifier == OFFICE) {
office.SetActive(true);
} else if (item.identifier == BEDROOM) {
bedroom.SetActive(true);
}
}
}
}
| 24.607143 | 88 | 0.616836 | [
"MIT"
] | brunopagno/abandon-gds | Assets/Scripts/Controls/UIControllerMainScene.cs | 691 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:932232227861cd6d0b1cdf7f5d24146bcfe58b0ee239732254e392d66d7e2d9c
size 965
| 32 | 75 | 0.882813 | [
"MIT"
] | kenx00x/ahhhhhhhhhhhh | ahhhhhhhhhh/Library/PackageCache/com.unity.test-framework@1.1.9/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/ApplePlatformSetup.cs | 128 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Build.Data
{
public interface IDataMemberProvider
{
void ResolveDataMembers(Type type, List<DataMember> members);
}
}
| 14.9375 | 69 | 0.723849 | [
"MIT"
] | liuwenjiexx/Unity.Build.Data | src/BuildData/IDataMemberProvider.cs | 241 | C# |
using Emgu.CV;
using Emgu.CV.Structure;
using FaceDetection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace FFRecognizer
{
public partial class TrainingForm : Form
{
//Camera specific
VideoCapture grabber;
//Images for finding face
Image<Bgr, Byte> currentFrame;
Image<Gray, byte> result = null;
Image<Gray, byte> gray_frame = null;
//Classifier
CascadeClassifier _face;
//For aquiring 10 images in a row
List<Image<Gray, byte>> resultImages = new List<Image<Gray, byte>>();
int results_list_pos = 0;
int num_faces_to_aquire = 10;
bool RECORD = false;
//Saving Jpg
List<Image<Gray, byte>> ImagestoWrite = new List<Image<Gray, byte>>();
EncoderParameters ENC_Parameters = new EncoderParameters(1);
EncoderParameter ENC = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100);
ImageCodecInfo Image_Encoder_JPG;
//Saving XAML Data file
List<string> NamestoWrite = new List<string>();
List<string> NamesforFile = new List<string>();
XmlDocument docu = new XmlDocument();
MainForm _parent;
public TrainingForm(MainForm parent)
{
InitializeComponent();
_parent = parent;
_face = parent._face;
ENC_Parameters.Param[0] = ENC;
Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
initialise_capture();
}
private void initialise_capture()
{
grabber = new VideoCapture();
grabber.QueryFrame();
//Initialize the FrameGraber event
Application.Idle += new EventHandler(FrameGrabber);
}
private Image<Bgr, byte> Detection(Image<Bgr, byte> image)
{
long detectionTime;
List<Rectangle> faces = new List<Rectangle>();
List<Rectangle> eyes = new List<Rectangle>();
DetectFace.Detect(
image, "haarcascade_frontalface_default.xml", "haarcascade_eye.xml",
faces, eyes,
out detectionTime);
foreach (Rectangle face in faces)
CvInvoke.Rectangle(image, face, new Bgr(Color.Red).MCvScalar, 2);
foreach (Rectangle eye in eyes)
CvInvoke.Rectangle(image, eye, new Bgr(Color.Blue).MCvScalar, 2);
//display the image
return image;
}
//Process Frame
private void FrameGrabber(object sender, EventArgs e)
{
//Get the current frame form capture device
currentFrame = grabber.QueryFrame().ToImage<Bgr, byte>().Resize(320, 240, Emgu.CV.CvEnum.Inter.Cubic);
//Convert it to Grayscale
if (currentFrame != null)
{
gray_frame = currentFrame.Convert<Gray, Byte>();
//Face Detector
//MCvAvgComp[][] facesDetected = gray_frame.DetectHaarCascade(Face, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20)); //old method
Rectangle[] facesDetected = _face.DetectMultiScale(gray_frame, 1.2, 10, new Size(50, 50), Size.Empty);
//Action for each element detected
for (int i = 0; i < facesDetected.Length; i++)// (Rectangle face_found in facesDetected)
{
//This will focus in on the face from the haar results its not perfect but it will remove a majoriy
//of the background noise
//facesDetected[i].X += (int)(facesDetected[i].Height * 0.15);
//facesDetected[i].Y += (int)(facesDetected[i].Width * 0.22);
//facesDetected[i].Height -= (int)(facesDetected[i].Height * 0.3);
//facesDetected[i].Width -= (int)(facesDetected[i].Width * 0.35);
result = currentFrame.Copy(facesDetected[i]).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.Inter.Cubic);
result._EqualizeHist();
face_PICBX.Image = result.ToBitmap();
//draw the face detected in the 0th (gray) channel with blue color
currentFrame.Draw(facesDetected[i], new Bgr(Color.Red), 2);
}
if (RECORD && facesDetected.Length > 0 && resultImages.Count < num_faces_to_aquire)
{
resultImages.Add(result);
count_lbl.Text = "Count: " + resultImages.Count.ToString();
if (resultImages.Count == num_faces_to_aquire)
{
ADD_BTN.Enabled = true;
NEXT_BTN.Visible = true;
PREV_btn.Visible = true;
count_lbl.Visible = false;
Single_btn.Visible = true;
ADD_ALL.Visible = true;
RECORD = false;
Application.Idle -= new EventHandler(FrameGrabber);
}
}
image_PICBX.Image = currentFrame.ToBitmap();
}
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private void TrainingForm_FormClosing(object sender, FormClosingEventArgs e)
{
stop_capture();
_parent.retrain();
_parent.initialise_capture();
}
private void stop_capture()
{
Application.Idle -= new EventHandler(FrameGrabber);
if (grabber != null)
{
grabber.Dispose();
}
//Initialize the FrameGraber event
}
private void ADD_BTN_Click(object sender, EventArgs e)
{
if (resultImages.Count == num_faces_to_aquire)
{
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
stop_capture();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
initialise_capture();
}
}
private void PREV_btn_Click(object sender, EventArgs e)
{
if (results_list_pos > 0)
{
results_list_pos--;
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
NEXT_BTN.Enabled = true;
}
else
{
PREV_btn.Enabled = false;
}
}
private void NEXT_BTN_Click(object sender, EventArgs e)
{
if (results_list_pos < resultImages.Count - 1)
{
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
results_list_pos++;
PREV_btn.Enabled = true;
}
else
{
NEXT_BTN.Enabled = false;
}
}
private void ADD_ALL_Click(object sender, EventArgs e)
{
for (int i = 0; i < resultImages.Count; i++)
{
face_PICBX.Image = resultImages[i].ToBitmap();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
Thread.Sleep(100);
}
ADD_ALL.Visible = false;
//restart single face detection
Single_btn_Click(null, null);
}
private bool save_training_data(Image face_data)
{
try
{
Random rand = new Random();
bool file_create = true;
string facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
while (file_create)
{
if (!File.Exists(Application.StartupPath + "/TrainedFaces/" + facename))
{
file_create = false;
}
else
{
facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
}
}
if (Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
else
{
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
if (File.Exists(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"))
{
//File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", NAME_PERSON.Text + "\n\r");
bool loading = true;
while (loading)
{
try
{
docu.Load(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
loading = false;
}
catch
{
docu = null;
docu = new XmlDocument();
Thread.Sleep(10);
}
}
//Get the root element
XmlElement root = docu.DocumentElement;
XmlElement face_D = docu.CreateElement("FACE");
XmlElement name_D = docu.CreateElement("NAME");
XmlElement file_D = docu.CreateElement("FILE");
//Add the values for each nodes
//name.Value = textBoxName.Text;
//age.InnerText = textBoxAge.Text;
//gender.InnerText = textBoxGender.Text;
name_D.InnerText = NAME_PERSON.Text;
file_D.InnerText = facename;
//Construct the Person element
//person.Attributes.Append(name);
face_D.AppendChild(name_D);
face_D.AppendChild(file_D);
//Add the New person element to the end of the root element
root.AppendChild(face_D);
//Save the document
docu.Save(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
//XmlElement child_element = docu.CreateElement("FACE");
//docu.AppendChild(child_element);
//docu.Save("TrainedLabels.xml");
}
else
{
FileStream FS_Face = File.OpenWrite(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
using (XmlWriter writer = XmlWriter.Create(FS_Face))
{
writer.WriteStartDocument();
writer.WriteStartElement("Faces_For_Training");
writer.WriteStartElement("FACE");
writer.WriteElementString("NAME", NAME_PERSON.Text);
writer.WriteElementString("FILE", facename);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
FS_Face.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private void RECORD_BTN_Click(object sender, EventArgs e)
{
if (RECORD)
{
RECORD = false;
}
else
{
if (resultImages.Count == 10)
{
resultImages.Clear();
Application.Idle += new EventHandler(FrameGrabber);
}
RECORD = true;
ADD_BTN.Enabled = false;
}
}
private void Delete_Data_BTN_Click(object sender, EventArgs e)
{
if (Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
Directory.Delete(Application.StartupPath + "/TrainedFaces/", true);
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
}
}
private void Single_btn_Click(object sender, EventArgs e)
{
RECORD = false;
resultImages.Clear();
NEXT_BTN.Visible = false;
PREV_btn.Visible = false;
Application.Idle += new EventHandler(FrameGrabber);
Single_btn.Visible = false;
count_lbl.Text = "Count: 0";
count_lbl.Visible = true;
}
}
}
| 37.644986 | 182 | 0.511986 | [
"Apache-2.0"
] | nguyendev/DATN | Code/FisherFaceRecognizer/TrainingForm.cs | 13,893 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace Project0.Data
{
public partial class Order
{
public Order()
{
Items = new HashSet<Item>();
}
public int Id { get; set; }
public int StoreId { get; set; }
public int? CustomerId { get; set; }
public DateTime Time { get; set; }
public virtual StoreCustomer Customer { get; set; }
public virtual Store Store { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
}
| 22.44 | 60 | 0.579323 | [
"MIT"
] | 2011-nov02-net/Joseph-project0 | Project0/Project0.Data/Order.cs | 563 | C# |
using System.ComponentModel.DataAnnotations;
using MarketingBox.AffiliateApi.Pagination;
using Microsoft.AspNetCore.Mvc;
namespace MarketingBox.AffiliateApi.Models.CampaignBoxes.Requests
{
public class CampaignBoxesSearchRequest : PaginationRequest<long?>
{
[FromQuery(Name = "id")]
public long? Id { get; set; }
[FromQuery(Name = "campaignId")]
public long? CampaignId { get; set; }
[Required, FromQuery(Name = "boxId")]
public long BoxId { get; set; }
}
}
| 27.473684 | 70 | 0.676245 | [
"MIT"
] | MyJetWallet/MarketingBox.AffiliateApi | src/MarketingBox.AffiliateApi/Models/CampaignBoxes/Requests/CampaignsSearchRequest.cs | 524 | 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 Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal readonly struct ILEmitCallSiteAnalysisResult
{
public ILEmitCallSiteAnalysisResult(int size) : this()
{
Size = size;
}
public ILEmitCallSiteAnalysisResult(int size, bool hasScope)
{
Size = size;
HasScope = hasScope;
}
public readonly int Size;
public readonly bool HasScope;
public ILEmitCallSiteAnalysisResult Add(in ILEmitCallSiteAnalysisResult other) =>
new ILEmitCallSiteAnalysisResult(Size + other.Size, HasScope | other.HasScope);
}
} | 31.703704 | 91 | 0.67757 | [
"MIT"
] | 06needhamt/runtime | src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalysisResult.cs | 856 | 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.MachineLearningServices.V20200515Preview.Outputs
{
[OutputType]
public sealed class RegistryListCredentialsResultResponseResult
{
public readonly string Location;
public readonly ImmutableArray<Outputs.PasswordResponseResult> Passwords;
public readonly string Username;
[OutputConstructor]
private RegistryListCredentialsResultResponseResult(
string location,
ImmutableArray<Outputs.PasswordResponseResult> passwords,
string username)
{
Location = location;
Passwords = passwords;
Username = username;
}
}
}
| 28.970588 | 81 | 0.697462 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/MachineLearningServices/V20200515Preview/Outputs/RegistryListCredentialsResultResponseResult.cs | 985 | C# |
using AspNetSeo.Testing;
using Xunit;
namespace AspNetSeo.Mvc.Tests
{
public class SeoMetaDescriptionAttributeTest
{
[Fact]
public void OnHandleSeoValues_TestMetaDescription_SetsMetaDescription()
{
// Arrange
var attribute = new SeoMetaDescriptionAttribute(TestData.MetaDescription);
var seo = SeoHelperTestFactory.Create();
// Act
attribute.OnHandleSeoValues(seo);
// Assert
Assert.Equal(TestData.MetaDescription, seo.MetaDescription);
}
[Fact]
public void OnHandleSeoValues_TestMetaDescription_SetsMetaDescriptionOnly()
{
// Arrange
var attribute = new SeoMetaDescriptionAttribute(TestData.MetaDescription);
var seo = SeoHelperTestFactory.Create();
// Act
attribute.OnHandleSeoValues(seo);
// Assert
Assert.Null(seo.LinkCanonical);
Assert.Null(seo.MetaKeywords);
Assert.Null(seo.MetaRobotsIndex);
Assert.Null(seo.Title);
}
}
} | 27.243902 | 86 | 0.606983 | [
"MIT"
] | techbuzzz/AspNetSeo | test/AspNetSeo.Mvc.Tests/SeoMetaDescriptionAttributeTest.cs | 1,119 | C# |
/***************************************************************************************************
*
* Copyright © 2017 Florian Schneidereit
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************************************/
#region Using Directives
using System;
using VSEssentials.Common;
#endregion
namespace VSEssentials.InsertGuidCommand
{
public enum GuidParenthesis
{
[LocalizableDescription(
LocalizationProvider = typeof(InsertGuidCommandLocalizationProvider),
ResourceName = InsertGuidCommandLocalizedResourceNames.GuidParenthesisNoneDescription)]
None,
[LocalizableDescription(
LocalizationProvider = typeof(InsertGuidCommandLocalizationProvider),
ResourceName = InsertGuidCommandLocalizedResourceNames.GuidParenthesisCurlyBracketsDescription)]
CurlyBrackets,
[LocalizableDescription(
LocalizationProvider = typeof(InsertGuidCommandLocalizationProvider),
ResourceName = InsertGuidCommandLocalizedResourceNames.GuidParenthesisSquareBracketsDescription)]
SquareBrackets,
[LocalizableDescription(
LocalizationProvider = typeof(InsertGuidCommandLocalizationProvider),
ResourceName = InsertGuidCommandLocalizedResourceNames.GuidParenthesisAngleBracketsDescription)]
AngleBrackets,
[LocalizableDescription(
LocalizationProvider = typeof(InsertGuidCommandLocalizationProvider),
ResourceName = InsertGuidCommandLocalizedResourceNames.GuidParenthesisRoundBracketsDescription)]
RoundBrackets
}
}
| 46.118644 | 109 | 0.70158 | [
"MIT"
] | flatcode/VSEssentials | src/Extensions/InsertGuidCommand/Sources/GuidParenthesis.cs | 2,724 | C# |
// SwitchParser.cs
//
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
namespace Microsoft.Ajax.Utilities
{
public class InvalidSwitchEventArgs : EventArgs
{
public string SwitchPart { get; set; }
public string ParameterPart { get; set; }
}
public class UnknownParameterEventArgs : EventArgs
{
public IList<string> Arguments { get; private set; }
public int Index { get; set; }
public string SwitchPart { get; set; }
public string ParameterPart { get; set; }
public UnknownParameterEventArgs(IList<string> arguments)
{
Arguments = arguments;
}
}
/// <summary>
/// Enumeration indicating how existing files will be treated
/// </summary>
public enum ExistingFileTreatment
{
/// <summary>
/// Existing files will be overwritten, but existing files marked with the read-only flag will not
/// </summary>
Auto = 0,
/// <summary>
/// Any existing file will be overwritten, regardless of the state of its read-only flag
/// </summary>
Overwrite,
/// <summary>
///
/// Existing files will be preserved (not overwritten)
/// </summary>
Preserve
}
public class SwitchParser
{
#region private fields
private bool m_isMono;
private bool m_noPretty;
#endregion
#region properties
/// <summary>
/// Gets the parsed JavaScript code settings object
/// </summary>
public CodeSettings JSSettings { get; private set; }
/// <summary>
/// Gets the parsed CSS settings object
/// </summary>
public CssSettings CssSettings { get; private set; }
/// <summary>
/// Gets a boolean value indicating whether or not Analyze mode is specified (default is false)
/// </summary>
public bool AnalyzeMode { get; private set; }
/// <summary>
/// Gets a string value indication the report format specified for analyze more (default is null)
/// </summary>
public string ReportFormat { get; private set; }
/// <summary>
/// Gets the path for the analyze scope report file (default is null, output to console)
/// </summary>
public string ReportPath { get; private set; }
/// <summary>
/// Gets a boolean value indicating whether or not Pretty-Print mode is specified (default is false)
/// </summary>
public bool PrettyPrint { get; private set; }
/// <summary>
/// Gets or sets an integer value indicating the warning severity threshold for reporting. Default is zero (syntax errors only).
/// </summary>
public int WarningLevel { get; set; }
/// <summary>
/// Gets or sets a flag indicating how existing files should be treated.
/// </summary>
public ExistingFileTreatment Clobber { get; set; }
/// <summary>
/// Gets the string output encoding name. Default is null, indicating the default output encoding should be used.
/// </summary>
public string EncodingOutputName { get; private set; }
/// <summary>
/// Gets the string input encoding name. Default is null, indicating the default output encoding should be used.
/// </summary>
public string EncodingInputName { get; private set; }
#endregion
#region events
// events that are fired under different circumstances while parsing the switches
public event EventHandler<InvalidSwitchEventArgs> InvalidSwitch;
public event EventHandler<UnknownParameterEventArgs> UnknownParameter;
public event EventHandler JSOnlyParameter;
public event EventHandler CssOnlyParameter;
#endregion
public SwitchParser()
{
// initialize with default values
JSSettings = new CodeSettings();
CssSettings = new CssSettings();
// see if this is running under the Mono runtime (on UNIX)
m_isMono = Type.GetType("Mono.Runtime") != null;
}
public SwitchParser(CodeSettings scriptSettings, CssSettings cssSettings)
{
// apply the switches to these two settings objects
JSSettings = scriptSettings ?? new CodeSettings();
CssSettings = cssSettings ?? new CssSettings();
}
public SwitchParser Clone()
{
// clone the settings
var newParser = new SwitchParser(this.JSSettings.Clone(), this.CssSettings.Clone());
// don't forget to copy the other properties
newParser.AnalyzeMode = this.AnalyzeMode;
newParser.EncodingInputName = this.EncodingInputName;
newParser.EncodingOutputName = this.EncodingOutputName;
newParser.PrettyPrint = this.PrettyPrint;
newParser.ReportFormat = this.ReportFormat;
newParser.ReportPath = this.ReportPath;
newParser.WarningLevel = this.WarningLevel;
return newParser;
}
#region command line to argument array
public static string[] ToArguments(string commandLine)
{
List<string> args = new List<string>();
if (!string.IsNullOrEmpty(commandLine))
{
var length = commandLine.Length;
for (var ndx = 0; ndx < length; ++ndx)
{
// skip initial spaces
while (ndx < length && char.IsWhiteSpace(commandLine[ndx]))
{
++ndx;
}
// don't create it if we don't need it yet
StringBuilder sb = null;
try
{
// if not at the end yet
if (ndx < length)
{
// grab the first character
var firstCharacter = commandLine[ndx];
// see if starts with a double-quote
var inDelimiter = firstCharacter == '"';
if (inDelimiter)
{
// we found a delimiter -- we're going to need one
sb = StringBuilderPool.Acquire();
}
// if it is, start at the NEXT character
var start = inDelimiter ? ndx + 1 : ndx;
// skip the first character -- we already know it's not whitespace or a delimiter,
// so we don't really care what the heck it is at this point.
while (++ndx < length)
{
// get the current character
var ch = commandLine[ndx];
if (inDelimiter)
{
// in delimiter mode.
// we only care if we found the closing delimiter
if (ch == '"')
{
// BUT if it's a double double-quote, then treat those two characters as
// a single double-quote
if (ndx + 1 < length && commandLine[ndx + 1] == '"')
{
// add what we have so far (if anything)
if (ndx > start)
{
sb.Append(commandLine.Substring(start, ndx - start));
}
// insert a single double-quote into the string builder
sb.Append('"');
// skip over the quote and start on the NEXT character
start = ++ndx + 1;
}
else
{
// found it; end delimiter mode
inDelimiter = false;
if (ndx > start)
{
// add what we have so far
sb.Append(commandLine.Substring(start, ndx - start));
}
// start is the NEXT character after the quote
start = ndx + 1;
}
}
}
else
{
// not in delimiter mode.
// if it's a whitespace, stop looping -- we found the end
if (char.IsWhiteSpace(ch))
{
break;
}
else if (ch == '"')
{
// we found a start delimiter
inDelimiter = true;
// create the string builder now if we haven't already
if (sb == null)
{
sb = StringBuilderPool.Acquire();
}
// add what we have up to the start delimiter into the string builder
// because we're going to have to add this escaped string to it WITHOUT
// the double-quotes
sb.Append(commandLine.Substring(start, ndx - start));
// and start this one at the next character -- not counting the quote
start = ndx + 1;
}
}
}
// we now have the start end end of the argument
// if the start and end character are the same delimiter characters, trim them off
// otherwise just use what's between them
if (sb != null)
{
// add what we have left (if any)
if (ndx > start)
{
sb.Append(commandLine.Substring(start, ndx - start));
}
// and send the whole shebang to the list
args.Add(sb.ToString());
}
else
{
// no double-quotes encountered, so just pull the substring
// directly from the command line
args.Add(commandLine.Substring(start, ndx - start));
}
}
}
finally
{
sb.Release();
}
}
}
return args.ToArray();
}
#endregion
#region Parse command line
/// <summary>
/// Takes a full command-line string and parses the switches into the appropriate settings objects
/// </summary>
/// <param name="commandLine"></param>
public void Parse(string commandLine)
{
// no command line, then nothing to parse
if (!string.IsNullOrEmpty(commandLine))
{
// convert the command line to an argument list and pass it
// to the appropriate override
Parse(ToArguments(commandLine));
}
}
#endregion
#region parse arguments
/// <summary>
/// Takes an array of arguments and parses the switches into the appropriate settings objects
/// </summary>
/// <param name="args"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Justification="Big switch statement"),
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Big switch statement")]
public void Parse(string[] args)
{
var listSeparators = new[] { ',', ';' };
if (args != null)
{
var levelSpecified = false;
var renamingSpecified = false;
var killSpecified = false;
var minifySpecified = false;
bool parameterFlag;
for (var ndx = 0; ndx < args.Length; ++ndx)
{
// parameter switch
var thisArg = args[ndx];
// don't use the forward-slash for switches if this is running under the Mono runtime.
// Mono is a .NET for UNIX implementation, and the UNIX OS uses forward slashes as the directory separator.
if (thisArg.Length > 1
&& (thisArg.StartsWith("-", StringComparison.Ordinal) // this is a normal hyphen (minus character)
|| thisArg.StartsWith("–", StringComparison.Ordinal) // this character is what Word will convert a hyphen to
|| (!m_isMono && thisArg.StartsWith("/", StringComparison.Ordinal))))
{
// general switch syntax is -switch:param
var parts = thisArg.Substring(1).Split(':');
var switchPart = parts[0].ToUpperInvariant();
var paramPart = parts.Length == 1 ? null : parts[1];
var paramPartUpper = paramPart == null ? null : paramPart.ToUpperInvariant();
// switch off the switch part
switch (switchPart)
{
case "AMD":
// amd support
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.AmdSupport = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "ANALYZE":
case "A": // <-- old-style
// ignore any arguments
AnalyzeMode = true;
// by default, we have no report format
ReportFormat = null;
if (paramPartUpper != null)
{
var items = paramPartUpper.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in items)
{
if (string.CompareOrdinal(item, "OUT") == 0)
{
// if the analyze part is "out," then the NEXT arg string
// is the output path the analyze scope report should be written to.
if (ndx >= args.Length - 1)
{
// must be followed by a path
OnInvalidSwitch(switchPart, paramPart);
}
else
{
ReportPath = args[++ndx];
}
}
else
{
// must be a report format. There can be only one, so clobber whatever
// is there from before -- last one listed wins.
ReportFormat = item;
}
}
}
// if analyze was specified but no warning level, jack up the warning level
// so everything is shown
if (!levelSpecified)
{
// we want to analyze, and we didn't specify a particular warning level.
// go ahead and report all errors
WarningLevel = int.MaxValue;
}
break;
case "ASPNET":
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
// same setting for both CSS and JS
JSSettings.AllowEmbeddedAspNetBlocks =
CssSettings.AllowEmbeddedAspNetBlocks = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "BRACES":
if (paramPartUpper == "NEW")
{
JSSettings.BlocksStartOnSameLine =
CssSettings.BlocksStartOnSameLine = BlockStart.NewLine;
}
else if (paramPartUpper == "SAME")
{
JSSettings.BlocksStartOnSameLine =
CssSettings.BlocksStartOnSameLine = BlockStart.SameLine;
}
else if (paramPartUpper == "SOURCE")
{
JSSettings.BlocksStartOnSameLine =
CssSettings.BlocksStartOnSameLine = BlockStart.UseSource;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "CC":
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
// actually, the flag is the opposite of the member -- turn CC ON and we DON'T
// want to ignore them; turn CC OFF and we DO want to ignore them
JSSettings.IgnoreConditionalCompilation = !parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
OnJSOnlyParameter();
break;
case "CLOBBER":
// just putting the clobber switch on the command line without any arguments
// is the same as putting -clobber:true and perfectly valid.
if (paramPartUpper == null)
{
Clobber = ExistingFileTreatment.Overwrite;
}
else if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
Clobber = parameterFlag ? ExistingFileTreatment.Overwrite : ExistingFileTreatment.Auto;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "COLORS":
// two options: hex or names
if (paramPartUpper == "HEX")
{
CssSettings.ColorNames = CssColor.Hex;
}
else if (paramPartUpper == "STRICT")
{
CssSettings.ColorNames = CssColor.Strict;
}
else if (paramPartUpper == "MAJOR")
{
CssSettings.ColorNames = CssColor.Major;
}
else if (paramPartUpper == "NOSWAP")
{
CssSettings.ColorNames = CssColor.NoSwap;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
OnCssOnlyParameter();
break;
case "COMMENTS":
// four options for css: none, all, important, or hacks
// two options for js: none, important
// (default is important)
if (paramPartUpper == "NONE")
{
CssSettings.CommentMode = CssComment.None;
JSSettings.PreserveImportantComments = false;
}
else if (paramPartUpper == "ALL")
{
CssSettings.CommentMode = CssComment.All;
OnCssOnlyParameter();
}
else if (paramPartUpper == "IMPORTANT")
{
CssSettings.CommentMode = CssComment.Important;
JSSettings.PreserveImportantComments = true;
}
else if (paramPartUpper == "HACKS")
{
CssSettings.CommentMode = CssComment.Hacks;
OnCssOnlyParameter();
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "CONST":
// options: MOZ or ES6 (ES6 is the default)
if (paramPartUpper == "MOZ")
{
JSSettings.ConstStatementsMozilla = true;
}
else if (paramPartUpper == "ES6")
{
JSSettings.ConstStatementsMozilla = false;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "CSS":
OnCssOnlyParameter();
if (paramPartUpper != null)
{
switch (paramPartUpper)
{
case "FULL":
CssSettings.CssType = CssType.FullStyleSheet;
break;
case "DECLS":
CssSettings.CssType = CssType.DeclarationList;
break;
default:
// not an expected value
OnInvalidSwitch(switchPart, paramPart);
break;
}
}
break;
case "CULTURE":
if (paramPart.IsNullOrWhiteSpace())
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
CultureInfo cultureInfo;
if (!TryCreateCultureInfo(paramPart, out cultureInfo))
{
// no such culture. Try just the language part, if there is one and it's
// different than what we already tried
var cultureParts = paramPart.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
if (!cultureParts[0].Equals(paramPart, StringComparison.OrdinalIgnoreCase))
{
TryCreateCultureInfo(cultureParts[0], out cultureInfo);
}
}
if (cultureInfo == null)
{
// not valid
OnInvalidSwitch(switchPart, paramPart);
}
else
{
// set the thread's current culture to what was specified
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
}
break;
case "DEBUG":
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// see if the param part is a comma-delimited list
if (paramPartUpper != null && paramPartUpper.IndexOf(',') >= 0)
{
// we have a comma-separated list.
// the first item is the flag (if any), and the rest (if any) are the "debug" lookup names
var items = paramPart.Split(listSeparators);
// use the first value as the debug boolean switch.
// since we are splitting the non-uppercase param part, we need to
// make sure the first item is capitalized for our boolean test.
if (BooleanSwitch(items[0].ToUpperInvariant(), true, out parameterFlag))
{
// actually the inverse - a TRUE on the -debug switch means we DON'T want to
// strip debug statements, and a FALSE means we DO want to strip them
JSSettings.StripDebugStatements = !parameterFlag;
// make sure we align the DEBUG define to the new switch value
AlignDebugDefine(JSSettings.StripDebugStatements, JSSettings.PreprocessorValues);
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// clear out the existing debug list
JSSettings.DebugLookupList = null;
// start with index 1, since index 0 was the flag
for (var item = 1; item < items.Length; ++item)
{
// get the identifier that was specified
var identifier = items[item];
if (!identifier.IsNullOrWhiteSpace())
{
if (!JSSettings.AddDebugLookup(identifier))
{
OnInvalidSwitch(switchPart, identifier);
}
}
}
}
else if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
// no commas -- just use the entire param part as the boolean value.
// just putting the debug switch on the command line without any arguments
// is the same as putting -debug:true and perfectly valid.
// actually the inverse - a TRUE on the -debug switch means we DON'T want to
// strip debug statements, and a FALSE means we DO want to strip them
JSSettings.StripDebugStatements = !parameterFlag;
// make sure we align the DEBUG define to the new switch value
AlignDebugDefine(JSSettings.StripDebugStatements, JSSettings.PreprocessorValues);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "DEFINE":
// the parts can be a comma-separate list of identifiers
if (string.IsNullOrEmpty(paramPartUpper))
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
foreach (string define in paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries))
{
string trimmedName;
string value;
var ndxEquals = define.IndexOf('=');
if (ndxEquals < 0)
{
trimmedName = define.Trim();
value = string.Empty;
}
else
{
trimmedName = define.Substring(0, ndxEquals).Trim();
value = define.Substring(ndxEquals + 1);
}
// better be a valid JavaScript identifier
if (!JSScanner.IsValidIdentifier(trimmedName))
{
OnInvalidSwitch(switchPart, define);
}
else
{
// JS Settings
JSSettings.PreprocessorValues[trimmedName] = value;
// CSS settings
CssSettings.PreprocessorValues[trimmedName] = value;
}
// if we're defining the DEBUG name, set the strip-debug-statements flag to false
if (string.Compare(trimmedName, "DEBUG", StringComparison.OrdinalIgnoreCase) == 0)
{
JSSettings.StripDebugStatements = false;
}
}
}
break;
case "ENC":
// the encoding is the next argument
if (ndx >= args.Length - 1)
{
// must be followed by an encoding
OnInvalidSwitch(switchPart, paramPart);
}
else
{
string encoding = args[++ndx];
// whether this is an in or an out encoding
if (paramPartUpper == "IN")
{
// save the name -- we'll create the encoding later because we may
// override it on a file-by-file basis in an XML file
EncodingInputName = encoding;
}
else if (paramPartUpper == "OUT")
{
// just save the name -- we'll create the encoding later because we need
// to know whether we are JS or CSS to pick the right encoding fallback
EncodingOutputName = encoding;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
break;
case "ESC":
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.AlwaysEscapeNonAscii = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
OnJSOnlyParameter();
break;
case "EVALS":
// three options: ignore, make immediate scope safe, or make all scopes safe
if (paramPartUpper == "IGNORE")
{
JSSettings.EvalTreatment = EvalTreatment.Ignore;
}
else if (paramPartUpper == "IMMEDIATE")
{
JSSettings.EvalTreatment = EvalTreatment.MakeImmediateSafe;
}
else if (paramPartUpper == "SAFEALL")
{
JSSettings.EvalTreatment = EvalTreatment.MakeAllSafe;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "EXPR":
// two options: minify (default) or raw
if (paramPartUpper == "MINIFY")
{
CssSettings.MinifyExpressions = true;
}
else if (paramPartUpper == "RAW")
{
CssSettings.MinifyExpressions = false;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
OnCssOnlyParameter();
break;
case "FNAMES":
// three options:
// LOCK -> keep all NFE names, don't allow renaming of function names
// KEEP -> keep all NFE names, but allow function names to be renamed
// ONLYREF -> remove unref'd NFE names, allow function named to be renamed (DEFAULT)
if (paramPartUpper == "LOCK")
{
// don't remove function expression names
JSSettings.RemoveFunctionExpressionNames = false;
// and preserve the names (don't allow renaming)
JSSettings.PreserveFunctionNames = true;
}
else if (paramPartUpper == "KEEP")
{
// don't remove function expression names
JSSettings.RemoveFunctionExpressionNames = false;
// but it's okay to rename them
JSSettings.PreserveFunctionNames = false;
}
else if (paramPartUpper == "ONLYREF")
{
// remove function expression names if they aren't referenced
JSSettings.RemoveFunctionExpressionNames = true;
// and rename them if we so desire
JSSettings.PreserveFunctionNames = false;
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "GLOBAL":
case "G": // <-- old style
// the parts can be a comma-separate list of identifiers
if (string.IsNullOrEmpty(paramPartUpper))
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
foreach (string global in paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries))
{
// better be a valid JavaScript identifier
if (!JSSettings.AddKnownGlobal(global))
{
OnInvalidSwitch(switchPart, global);
}
}
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "IE8FIX":
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
CssSettings.FixIE8Fonts = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
OnCssOnlyParameter();
break;
case "IGNORE":
// list of error codes to ignore (not report)
// the parts can be a comma-separate list of identifiers
if (string.IsNullOrEmpty(paramPartUpper))
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
foreach (string errorCode in paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries))
{
if (string.Compare(errorCode, "ALL", StringComparison.OrdinalIgnoreCase) == 0)
{
// we want to ignore ALL errors. So set the appropriate flag
JSSettings.IgnoreAllErrors =
CssSettings.IgnoreAllErrors = true;
}
else
{
// don't add duplicates
JSSettings.IgnoreErrorCollection.Add(errorCode);
CssSettings.IgnoreErrorCollection.Add(errorCode);
}
}
}
break;
case "INLINE":
if (string.IsNullOrEmpty(paramPart))
{
// no param parts. This defaults to inline-safe
JSSettings.InlineSafeStrings = true;
}
else
{
// for each comma-separated part...
foreach (var inlinePart in paramPartUpper.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries))
{
if (string.CompareOrdinal(inlinePart, "FORCE") == 0)
{
// this is the force flag -- throw an error if any string literal
// sources are not properly escaped AND make sure the output is
// safe
JSSettings.ErrorIfNotInlineSafe = true;
JSSettings.InlineSafeStrings = true;
}
else if (string.CompareOrdinal(inlinePart, "NOFORCE") == 0)
{
// this is the noforce flag; don't throw an error is the source isn't inline safe.
// don't change whatever the output-inline-safe flag may happen to be, though
JSSettings.ErrorIfNotInlineSafe = false;
}
else
{
// assume it must be the boolean flag.
// if no param part, will return true (indicating the default)
// if invalid param part, will throw error
if (BooleanSwitch(inlinePart, true, out parameterFlag))
{
JSSettings.InlineSafeStrings = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
}
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "JS":
if (paramPart == null)
{
// normal settings
JSSettings.SourceMode = JavaScriptSourceMode.Program;
JSSettings.Format = JavaScriptFormat.Normal;
}
else
{
// comma-delimited list of JS settings
var tokens = paramPartUpper.Split(',', ';');
foreach (var token in tokens)
{
switch (token)
{
case "JSON":
// JSON is incompatible with any other tokens, so throw an error
// if it's not the only token
if (tokens.Length > 1)
{
OnInvalidSwitch(switchPart, paramPart);
}
// nothing to "minify" in the JSON format, so turn off the minify flag
JSSettings.MinifyCode = false;
// JSON affects both the input (it's an expression) and the output
// (use the JSON-output visitor)
JSSettings.SourceMode = JavaScriptSourceMode.Expression;
JSSettings.Format = JavaScriptFormat.JSON;
break;
case "PROG":
case "PROGRAM":
// this is the default setting
JSSettings.SourceMode = JavaScriptSourceMode.Program;
break;
case "MOD":
case "MODULE":
JSSettings.SourceMode = JavaScriptSourceMode.Module;
break;
case "EXPR":
case "EXPRESSION":
JSSettings.SourceMode = JavaScriptSourceMode.Expression;
break;
case "EVT":
case "EVENT":
JSSettings.SourceMode = JavaScriptSourceMode.EventHandler;
break;
case "ES5":
// say we are targetting ECMAScript 5. ECMAScript 6 features won't
// be disabled; future feature may change them to ES5-equivalents.
JSSettings.ScriptVersion = ScriptVersion.EcmaScript5;
break;
case "ES6":
// say we are targetting ECMAScript 6 so the parser will know ahead of
// time and not be surprised by new syntax. Future feature may generate
// ES6 syntax for optimizations.
JSSettings.ScriptVersion = ScriptVersion.EcmaScript6;
break;
default:
// later: ES5 to convert any ES6 syntax to ES5-compatible
// later: ES6 to create ES6 syntax when optimizing
// etc.
// those two examples will affect the format property.
// but for now, not supported
OnInvalidSwitch(switchPart, paramPart);
break;
}
}
}
OnJSOnlyParameter();
break;
case "KILL":
killSpecified = true;
// optional integer switch argument
if (paramPartUpper == null)
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
// get the numeric portion
long killSwitch;
if (paramPartUpper.StartsWith("0X", StringComparison.OrdinalIgnoreCase))
{
// it's hex -- convert the number after the "0x"
if (paramPartUpper.Substring(2).TryParseLongInvariant(NumberStyles.AllowHexSpecifier, out killSwitch))
{
// save the switch for both JS and Css
JSSettings.KillSwitch = CssSettings.KillSwitch = killSwitch;
// for CSS, we only look at the first bit: preeserve important comments
if ((killSwitch & 1) != 0)
{
// we set the kill, so make sure the comments are set to none
CssSettings.CommentMode = CssComment.None;
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else if (paramPartUpper.TryParseLongInvariant(NumberStyles.AllowLeadingSign, out killSwitch))
{
// save the switch for both JS and CSS
JSSettings.KillSwitch = CssSettings.KillSwitch = killSwitch;
// for CSS, we only look at the first bit: preeserve important comments
if ((killSwitch & 1) != 0)
{
// we set the kill, so make sure the comments are set to none
CssSettings.CommentMode = CssComment.None;
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
break;
case "LINE":
case "LINES":
if (string.IsNullOrEmpty(paramPartUpper))
{
// if no number specified, use the max default threshold
JSSettings.LineBreakThreshold =
CssSettings.LineBreakThreshold = int.MaxValue - 1000;
// single-line mode
JSSettings.OutputMode =
CssSettings.OutputMode = OutputMode.SingleLine;
// and four spaces per indent level
JSSettings.IndentSize =
CssSettings.IndentSize = 4;
}
else
{
// split along commas (case-insensitive)
var lineParts = paramPartUpper.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries);
// by default, the line-break index will be 1 (the second option).
// we will change this index to 0 if the first parameter is multi/single
// instead of the line-break character count.
var breakIndex = 1;
if (lineParts.Length <= 3)
{
// if the first optional part is numeric, then it's the line threshold.
// might also be "multi" or "single", thereby skipping the line threshold.
// (don't need to check length greater than zero -- will always be at least one element returned from Split)
if (!string.IsNullOrEmpty(lineParts[0]))
{
// must be an unsigned decimal integer value
int lineThreshold;
if (lineParts[0].TryParseIntInvariant(NumberStyles.None, out lineThreshold))
{
JSSettings.LineBreakThreshold =
CssSettings.LineBreakThreshold = lineThreshold;
}
else if (lineParts[0][0] == 'S')
{
// single-line mode
JSSettings.OutputMode =
CssSettings.OutputMode = OutputMode.SingleLine;
// the line-break index was the first one (zero)
breakIndex = 0;
}
else if (lineParts[0][0] == 'M')
{
// multiple-line mode
JSSettings.OutputMode =
CssSettings.OutputMode = OutputMode.MultipleLines;
// the line-break index was the first one (zero)
breakIndex = 0;
}
else
{
OnInvalidSwitch(switchPart, lineParts[0]);
}
}
else
{
// use the default
JSSettings.LineBreakThreshold =
CssSettings.LineBreakThreshold = int.MaxValue - 1000;
}
if (lineParts.Length > breakIndex)
{
// if the line-break index was zero, then we already processed it
// and we can skip the logic
if (breakIndex > 0)
{
// second optional part is single or multiple line output
if (string.IsNullOrEmpty(lineParts[breakIndex]) || lineParts[breakIndex][0] == 'S')
{
// single-line mode
JSSettings.OutputMode =
CssSettings.OutputMode = OutputMode.SingleLine;
}
else if (lineParts[breakIndex][0] == 'M')
{
// multiple-line mode
JSSettings.OutputMode =
CssSettings.OutputMode = OutputMode.MultipleLines;
}
else
{
// must either be missing, or start with S (single) or M (multiple)
OnInvalidSwitch(switchPart, lineParts[breakIndex]);
}
}
// move on to the next part
++breakIndex;
if (lineParts.Length > breakIndex)
{
// third optional part is the spaces-per-indent value
if (!string.IsNullOrEmpty(lineParts[breakIndex]))
{
// get the numeric portion; must be a decimal integer
int indentSize;
if (lineParts[breakIndex].TryParseIntInvariant(NumberStyles.None, out indentSize))
{
// same value for JS and CSS.
// don't need to check for negative, because the tryparse method above does NOT
// allow for a sign -- no sign, no negative.
JSSettings.IndentSize = CssSettings.IndentSize = indentSize;
}
else
{
OnInvalidSwitch(switchPart, lineParts[breakIndex]);
}
}
else
{
// default of 4
JSSettings.IndentSize =
CssSettings.IndentSize = 4;
}
}
}
}
else
{
// only 1-3 parts allowed
OnInvalidSwitch(switchPart, paramPart);
}
}
break;
case "LITERALS":
// two areas with two options each: keep or combine and eval or noeval
if (paramPartUpper == "KEEP")
{
// no longer supported....
//JSSettings.CombineDuplicateLiterals = false;
}
else if (paramPartUpper == "COMBINE")
{
// no longer supported....
//JSSettings.CombineDuplicateLiterals = true;
}
else if (paramPartUpper == "EVAL")
{
JSSettings.EvalLiteralExpressions = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else if (paramPartUpper == "NOEVAL")
{
JSSettings.EvalLiteralExpressions = false;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "MAC":
// optional boolean switch
// no arg is valid scenario (default is true)
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.MacSafariQuirks = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "MINIFY":
minifySpecified = true;
if (renamingSpecified && JSSettings.LocalRenaming != LocalRenaming.KeepAll)
{
// minify can only exist if rename is set to KeepAll
OnInvalidSwitch(switchPart, paramPart);
}
else if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
// optional boolean switch
// no arg is a valid scenario (default is true)
JSSettings.MinifyCode = parameterFlag;
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
if (parameterFlag)
{
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "NEW":
// two options: keep and collapse
if (paramPartUpper == "KEEP")
{
JSSettings.CollapseToLiteral = false;
}
else if (paramPartUpper == "COLLAPSE")
{
JSSettings.CollapseToLiteral = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "NFE": // <-- deprecate; use FNAMES option instead
if (paramPartUpper == "KEEPALL")
{
JSSettings.RemoveFunctionExpressionNames = false;
}
else if (paramPartUpper == "ONLYREF")
{
JSSettings.RemoveFunctionExpressionNames = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
// this seems to be a common one for people to wonder why it's not working properly.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "NOCLOBBER":
// putting the noclobber switch on the command line without any arguments
// is the same as putting -noclobber:true and perfectly valid.
if (paramPartUpper == null)
{
Clobber = ExistingFileTreatment.Preserve;
}
else if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
Clobber = parameterFlag ? ExistingFileTreatment.Preserve : ExistingFileTreatment.Auto;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "NORENAME":
// the parts can be a comma-separate list of identifiers
if (string.IsNullOrEmpty(paramPartUpper))
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
foreach (string ident in paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries))
{
// better be a valid JavaScript identifier
if (!JSSettings.AddNoAutoRename(ident))
{
OnInvalidSwitch(switchPart, ident);
}
}
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "NOVENDER":
if (string.IsNullOrEmpty(paramPartUpper))
{
// if there's no param part, then we are being asked to clear the collection
CssSettings.ExcludeVendorPrefixes.Clear();
}
else
{
var vendorPrefixes = paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach(var prefix in vendorPrefixes)
{
if (CssScanner.IsValidVendorPrefix(prefix))
{
CssSettings.ExcludeVendorPrefixes.Add(prefix);
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
}
OnCssOnlyParameter();
break;
case "OBJ":
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// two options: MINify or QUOTE
if (paramPartUpper == "MIN")
{
JSSettings.QuoteObjectLiteralProperties = false;
}
else if (paramPartUpper == "QUOTE")
{
JSSettings.QuoteObjectLiteralProperties = true;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "PPONLY":
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// just putting the pponly switch on the command line without any arguments
// is the same as putting -pponly:true and perfectly valid.
if (paramPart == null)
{
JSSettings.PreprocessOnly = true;
}
else if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.PreprocessOnly = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "PRETTY":
case "P": // <-- old style
// doesn't take a flag -- just set to pretty
PrettyPrint = true;
if (m_noPretty)
{
// already encountered a switch that is incompatible with -pretty
OnInvalidSwitch(switchPart, paramPart);
}
// by default, pretty mode turns off minification, which sets a bunch of other flags as well
JSSettings.MinifyCode = false;
// and some other flags for pretty-mode
JSSettings.OutputMode = CssSettings.OutputMode = OutputMode.MultipleLines;
CssSettings.KillSwitch = ~((long)TreeModifications.PreserveImportantComments);
CssSettings.RemoveEmptyBlocks = false;
// optional integer switch argument
if (paramPartUpper != null)
{
// get the numeric portion; must be a decimal integer
int indentSize;
if (paramPart.TryParseIntInvariant(NumberStyles.None, out indentSize))
{
// same value for JS and CSS.
// don't need to check for negative, because the tryparse method above does NOT
// allow for a sign -- no sign, no negative.
JSSettings.IndentSize = CssSettings.IndentSize = indentSize;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
break;
case "RENAME":
if (paramPartUpper == null)
{
// treat as if it's unknown
ndx = OnUnknownParameter(args, ndx, switchPart, paramPart);
}
else if (paramPartUpper.IndexOf('=') > 0)
{
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// there is at least one equal sign -- treat this as a set of JS identifier
// pairs. split on commas -- multiple pairs can be specified
var paramPairs = paramPart.Split(listSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (var paramPair in paramPairs)
{
// split on the equal sign -- each pair needs to have an equal sige
var pairParts = paramPair.Split('=');
if (pairParts.Length == 2)
{
// there is an equal sign. The first part is the source name and the
// second part is the new name to which to rename those entities.
string fromIdentifier = pairParts[0];
string toIdentifier = pairParts[1];
// make sure both parts are valid JS identifiers
var fromIsValid = JSScanner.IsValidIdentifier(fromIdentifier);
var toIsValid = JSScanner.IsValidIdentifier(toIdentifier);
if (fromIsValid && toIsValid)
{
// create the map if it hasn't been created yet.
var toExisting = JSSettings.GetNewName(fromIdentifier);
if (toExisting == null)
{
JSSettings.AddRenamePair(fromIdentifier, toIdentifier);
}
else if (string.CompareOrdinal(toIdentifier, toExisting) != 0)
{
// from-identifier already exists, and the to-identifier doesn't match.
// can't rename the same name to two different names!
OnInvalidSwitch(switchPart, fromIdentifier);
}
}
else
{
if (fromIsValid)
{
// the toIdentifier is invalid!
OnInvalidSwitch(switchPart, toIdentifier);
}
if (toIsValid)
{
// the fromIdentifier is invalid!
OnInvalidSwitch(switchPart, fromIdentifier);
}
}
}
else
{
// either zero or more than one equal sign. Invalid.
OnInvalidSwitch(switchPart, paramPart);
}
}
}
else
{
// no equal sign; just a plain option
// three options: all, localization, none
if (paramPartUpper == "ALL")
{
JSSettings.LocalRenaming = LocalRenaming.CrunchAll;
// automatic renaming strategy has been specified by this option
renamingSpecified = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else if (paramPartUpper == "LOCALIZATION")
{
JSSettings.LocalRenaming = LocalRenaming.KeepLocalizationVars;
// automatic renaming strategy has been specified by this option
renamingSpecified = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else if (paramPartUpper == "NONE")
{
JSSettings.LocalRenaming = LocalRenaming.KeepAll;
// automatic renaming strategy has been specified by this option
renamingSpecified = true;
}
else if (paramPartUpper == "NOPROPS")
{
// manual-renaming does not change property names
JSSettings.ManualRenamesProperties = false;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
// since we specified a rename switch OTHER than none,
// let's make sure we don't *automatically* turn off switches that would
// stop renaming, which we have explicitly said we want.
if (JSSettings.LocalRenaming != LocalRenaming.KeepAll)
{
ResetRenamingKill(killSpecified);
// if minify was specified as turned off, then this is invalid
if (minifySpecified && !JSSettings.MinifyCode)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "REORDER":
// default is true
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.ReorderScopeDeclarations = parameterFlag;
// if the -pretty switch has been specified, we have an incompatible set of switches.
if (parameterFlag)
{
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "STRICT":
// default is false, but if we specify this switch without a parameter, then
// we assume we are turning it ON
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.StrictMode = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "TERM":
// optional boolean argument, defaults to true
if (BooleanSwitch(paramPartUpper, true, out parameterFlag))
{
JSSettings.TermSemicolons =
CssSettings.TermSemicolons = parameterFlag;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "UNUSED":
// two options: keep and remove
if (paramPartUpper == "KEEP")
{
JSSettings.RemoveUnneededCode = false;
CssSettings.RemoveEmptyBlocks = false;
}
else if (paramPartUpper == "REMOVE")
{
JSSettings.RemoveUnneededCode = true;
CssSettings.RemoveEmptyBlocks = true;
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "VAR":
m_noPretty = true;
if (PrettyPrint || string.IsNullOrEmpty(paramPartUpper))
{
OnInvalidSwitch(switchPart, paramPart);
}
else
{
var firstLetters = paramPart;
string partLetters = null;
var commaPosition = paramPart.IndexOf(',');
if (commaPosition == 0)
{
// no first letters; just part letters
firstLetters = null;
partLetters = paramPart.Substring(commaPosition + 1);
}
else if (commaPosition > 0)
{
// first letters and part letters
firstLetters = paramPart.Substring(0, commaPosition);
partLetters = paramPart.Substring(commaPosition + 1);
}
// if we specified first letters, set them now
if (!string.IsNullOrEmpty(firstLetters))
{
CrunchEnumerator.FirstLetters = firstLetters;
}
// if we specified part letters, use it -- otherwise use the first letters.
if (!string.IsNullOrEmpty(partLetters))
{
CrunchEnumerator.PartLetters = partLetters;
}
else if (!string.IsNullOrEmpty(firstLetters))
{
// we don't have any part letters, but we do have first letters. reuse.
CrunchEnumerator.PartLetters = firstLetters;
}
}
// this is a JS-only switch
OnJSOnlyParameter();
break;
case "WARN":
case "W": // <-- old style
if (string.IsNullOrEmpty(paramPartUpper))
{
// just "-warn" without anything else means all errors and warnings
WarningLevel = int.MaxValue;
}
else
{
// must be an unsigned decimal integer value
int warningLevel;
if (paramPart.TryParseIntInvariant(NumberStyles.None, out warningLevel))
{
WarningLevel = warningLevel;
}
else
{
OnInvalidSwitch(switchPart, paramPart);
}
}
levelSpecified = true;
break;
//
// Backward-compatibility switches different from new switches
//
case "D":
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// equivalent to -debug:false (default behavior)
JSSettings.StripDebugStatements = true;
OnJSOnlyParameter();
break;
case "E":
case "EO":
// equivalent to -enc:out <encoding>
if (parts.Length < 2)
{
// must be followed by an encoding
OnInvalidSwitch(switchPart, paramPart);
}
// just save the name -- we'll create the encoding later because we need
// to know whether we are JS or CSS to pick the right encoding fallback
EncodingOutputName = paramPart;
break;
case "EI":
// equivalent to -enc:in <encoding>
if (parts.Length < 2)
{
// must be followed by an encoding
OnInvalidSwitch(switchPart, paramPart);
}
// save the name
EncodingInputName = paramPart;
break;
case "H":
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// equivalent to -rename:all -unused:remove (default behavior)
JSSettings.LocalRenaming = LocalRenaming.CrunchAll;
JSSettings.RemoveUnneededCode = true;
OnJSOnlyParameter();
// renaming is specified by this option
renamingSpecified = true;
// since we specified a rename switch OTHER than none,
// let's make sure we don't *automatically* turn off switches that would
// stop renaming, which we have explicitly said we want.
ResetRenamingKill(killSpecified);
// if minify was specified as turned off, then this is invalid
if (minifySpecified && !JSSettings.MinifyCode)
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "HL":
// if the -pretty switch has been specified, we have an incompatible set of switches.
m_noPretty = true;
if (PrettyPrint)
{
OnInvalidSwitch(switchPart, paramPart);
}
// equivalent to -rename:localization -unused:remove
JSSettings.LocalRenaming = LocalRenaming.KeepLocalizationVars;
JSSettings.RemoveUnneededCode = true;
OnJSOnlyParameter();
// renaming is specified by this option
renamingSpecified = true;
// since we specified a rename switch OTHER than none,
// let's make sure we don't *automatically* turn off switches that would
// stop renaming, which we have explicitly said we want.
ResetRenamingKill(killSpecified);
// if minify was specified as turned off, then this is invalid
if (minifySpecified && !JSSettings.MinifyCode)
{
OnInvalidSwitch(switchPart, paramPart);
}
break;
case "HC":
// equivalent to -literals:combine -rename:all -unused:remove
// literal-combining no longer supported....
//JSSettings.CombineDuplicateLiterals = true;
goto case "H";
case "HLC":
case "HCL":
// equivalent to -literals:combine -rename:localization -unused:remove
// literal-combining no longer supported....
//JSSettings.CombineDuplicateLiterals = true;
goto case "HL";
case "J":
// equivalent to -evals:ignore (default behavior)
JSSettings.EvalTreatment = EvalTreatment.Ignore;
OnJSOnlyParameter();
break;
case "K":
// equivalent to -inline:true (default behavior)
JSSettings.InlineSafeStrings = true;
OnJSOnlyParameter();
break;
case "L":
// equivalent to -new:keep (default is collapse)
JSSettings.CollapseToLiteral = false;
OnJSOnlyParameter();
break;
case "M":
// equivalent to -mac:true (default behavior)
JSSettings.MacSafariQuirks = true;
OnJSOnlyParameter();
break;
case "Z":
// equivalent to -term:true (default is false)
JSSettings.TermSemicolons =
CssSettings.TermSemicolons = true;
break;
// end backward-compatible section
default:
ndx = OnUnknownParameter(args, ndx, switchPart, paramPart);
break;
}
}
else
{
// not a switch -- it's an unknown parameter
ndx = OnUnknownParameter(args, ndx, null, null);
}
}
}
}
#endregion
#region event handler overrides
protected virtual int OnUnknownParameter(IList<string> arguments, int index, string switchPart, string parameterPart)
{
if (UnknownParameter != null)
{
// create our event args that we'll pass to the listeners and read the index field back from
var ea = new UnknownParameterEventArgs(arguments)
{
Index = index,
SwitchPart = switchPart,
ParameterPart = parameterPart,
};
// fire the event
UnknownParameter(this, ea);
// get the index from the event args, in case the listeners changed it
// BUT ONLY if it's become greater. Can go backwards and get into an infinite loop.
if (ea.Index > index)
{
index = ea.Index;
}
}
return index;
}
protected virtual void OnInvalidSwitch(string switchPart, string parameterPart)
{
if (InvalidSwitch != null)
{
InvalidSwitch(this, new InvalidSwitchEventArgs() { SwitchPart = switchPart, ParameterPart = parameterPart });
}
}
protected virtual void OnJSOnlyParameter()
{
if (JSOnlyParameter != null)
{
JSOnlyParameter(this, new EventArgs());
}
}
protected virtual void OnCssOnlyParameter()
{
if (CssOnlyParameter != null)
{
CssOnlyParameter(this, new EventArgs());
}
}
#endregion
#region helper methods
private static bool TryCreateCultureInfo(string name, out CultureInfo cultureInfo)
{
try
{
cultureInfo = CultureInfo.GetCultureInfo(name);
return true;
}
#if NET_20 || NET_35
catch (ArgumentException)
#else
catch (CultureNotFoundException)
#endif
{
// nope
cultureInfo = null;
return false;
}
}
private static void AlignDebugDefine(bool stripDebugStatements, IDictionary<string, string> defines)
{
// if we are setting the debug switch on, then make sure we
// add the DEBUG value to the defines
if (stripDebugStatements)
{
// we are turning debug off.
// make sure we DON'T have the DEBUG define in the list
if (defines.ContainsKey("DEBUG"))
{
defines.Remove("DEBUG");
}
}
else if (!defines.ContainsKey("DEBUG"))
{
// turning debug on, we have already created the list,
// and debug is not already in it -- add it now.
defines.Add("debug", string.Empty);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification="duly noted")]
public static bool BooleanSwitch(string booleanText, bool defaultValue, out bool booleanValue)
{
// assume it's valid unless proven otherwise
var isValid = true;
switch (booleanText)
{
case "Y":
case "YES":
case "T":
case "TRUE":
case "ON":
case "1":
booleanValue = true;
break;
case "N":
case "NO":
case "NONE":
case "F":
case "FALSE":
case "OFF":
case "0":
booleanValue = false;
break;
case "":
case null:
booleanValue = defaultValue;
break;
default:
// not a valid value
booleanValue = defaultValue;
isValid = false;
break;
}
return isValid;
}
private void ResetRenamingKill(bool killSpecified)
{
// Reset the LocalRenaming kill bit IF the kill switch hadn't been specified
// and it's also not zero. If that's the case, that's because we set it to something
// automatically based on other switched, but now we're explcitly turning ON renaming,
// so we need to reset that switch so renaming will occur. Of course, might be overridden
// later with an explcit kill switch.
if (!killSpecified && JSSettings.KillSwitch != 0)
{
JSSettings.KillSwitch &= ~((long)TreeModifications.LocalRenaming);
}
}
#endregion
}
}
| 51.707306 | 161 | 0.344226 | [
"MIT"
] | 4vz/jovice | Aphysoft.Share/External/AjaxMin/SwitchParser.cs | 111,123 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cat.Ereza.Customactivityoncrash")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cat.Ereza.Customactivityoncrash")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 34.62963 | 77 | 0.757219 | [
"Apache-2.0"
] | ZeroGachis/xamarin-caoc | Cat.Ereza.Customactivityoncrash/Properties/AssemblyInfo.cs | 938 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Kernel.BareMetal.Extension;
using Mosa.Runtime.x86;
using System;
namespace Mosa.Kernel.BareMetal.x86
{
/// <summary>
/// Page Table
/// </summary>
internal static class PageTable
{
public static IntPtr PageDirectory;
public static IntPtr PageTables;
public static void Setup()
{
PageDirectory = new IntPtr(Address.PageDirectory); // 12MB [Size=4KB]
PageTables = new IntPtr(Address.PageTables); // 16MB [Size=4MB]
}
public static void Initialize()
{
// Setup Page Directory
for (int index = 0; index < 1024; index++)
{
PageDirectory.Store32(index << 2, (uint)(PageTables.ToInt32() + (index * 4096) | 0x04 | 0x02 | 0x01));
}
// TODO: Clear all the page table entries
// Set CR3 register on processor - sets page directory
Native.SetCR3((uint)PageDirectory.ToInt32());
// Set CR0 register on processor - turns on virtual memory
Native.SetCR0(Native.GetCR0() | 0x80000000);
}
public static void MapVirtualAddressToPhysical(uint virtualAddress, uint physicalAddress, bool present = true)
{
//FUTURE: traverse page directory from CR3 --- do not assume page table is linearly allocated
//Native.Set32(Address.PageTable + ((virtualAddress & 0xFFC00000u) >> 10), physicalAddress & 0xFFC00000u | 0x04u | 0x02u | (present ? 0x1u : 0x0u));
PageTables.Store32((virtualAddress & 0xFFFFF000u) >> 10, physicalAddress & 0xFFFFF000u | 0x04u | 0x02u | (present ? 0x1u : 0x0u));
}
public static IntPtr GetPhysicalAddressFromVirtual(IntPtr virtualAddress)
{
//FUTURE: traverse page directory from CR3 --- do not assume page table is linearly allocated
var offset = (((uint)virtualAddress.ToInt32() & 0xFFFFF000u) >> 10) + ((uint)virtualAddress.ToInt32() & 0xFFFu);
return PageTables.LoadPointer(offset);
}
}
}
| 32.789474 | 151 | 0.70626 | [
"BSD-3-Clause"
] | TekuSP/MOSA-Project | Source/Mosa.Kernel.BareMetal.x86/PageTable.cs | 1,871 | C# |
using System;
using System.Diagnostics;
namespace ProtoBuf.Internal.Serializers
{
internal sealed class TimeSpanSerializer : IRuntimeProtoSerializerNode
{
private static TimeSpanSerializer s_Legacy, s_Duration;
private static readonly Type expectedType = typeof(TimeSpan);
private readonly bool _useDuration;
public static TimeSpanSerializer Create(CompatibilityLevel compatibilityLevel)
=> compatibilityLevel >= CompatibilityLevel.Level240
? s_Duration ??= new TimeSpanSerializer(true)
: s_Legacy ??= new TimeSpanSerializer(false);
private TimeSpanSerializer(bool useDuration)
=> _useDuration = useDuration;
public Type ExpectedType => expectedType;
bool IRuntimeProtoSerializerNode.RequiresOldValue => false;
bool IRuntimeProtoSerializerNode.ReturnsValue => true;
public object Read(ref ProtoReader.State state, object value)
{
if (_useDuration)
{
return BclHelpers.ReadDuration(ref state);
}
else
{
Debug.Assert(value is null); // since replaces
return BclHelpers.ReadTimeSpan(ref state);
}
}
public void Write(ref ProtoWriter.State state, object value)
{
if (_useDuration)
{
BclHelpers.WriteDuration(ref state, (TimeSpan)value);
}
else
{
BclHelpers.WriteTimeSpan(ref state, (TimeSpan)value);
}
}
void IRuntimeProtoSerializerNode.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitStateBasedWrite(
_useDuration ? nameof(BclHelpers.WriteDuration) : nameof(BclHelpers.WriteTimeSpan), valueFrom, typeof(BclHelpers));
}
void IRuntimeProtoSerializerNode.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity)
{
if (_useDuration) ctx.LoadValue(entity);
ctx.EmitStateBasedRead(typeof(BclHelpers),
_useDuration ? nameof(BclHelpers.ReadDuration) : nameof(BclHelpers.ReadTimeSpan),
ExpectedType);
}
}
} | 35.390625 | 131 | 0.624724 | [
"Apache-2.0"
] | AlexMihalev/protobuf-net | src/protobuf-net/Internal/Serializers/TimeSpanSerializer.cs | 2,267 | C# |
// (c) 2010-2015 IndiegameGarden.com. Distributed under the FreeBSD license in LICENSE.txt
using System.IO;
using MyDownloader.Core;
using IndiegameGarden.Base;
namespace IndiegameGarden.Download
{
/**
* a downloader to download a game file such as .zip / .rar / .exe but also .ogg (for music tracks)
* If file already exists, this ITask finishes successfully.
*/
public class GameDownloader: BaseDownloader
{
protected GardenItem game;
public GameDownloader(GardenItem game): base()
{
this.game= game;
this.segmentsUsedInDownload = 1;
}
protected override void StartInternal()
{
status = ITaskStatus.RUNNING;
string fn = game.PackedFileName;
string toLocalFolder = game.PackedFileFolder;
string filePath = Path.Combine(toLocalFolder , fn);
if (File.Exists(filePath))
{
// skip download step
status = ITaskStatus.SUCCESS;
}
else
{
MaxRetries = 3;
InternalDoDownload_MirrorRetry(game.PackedFileURL, fn, toLocalFolder, false, game.PackedFileMirrors);
}
}
}
}
| 29.255814 | 117 | 0.591415 | [
"BSD-2-Clause"
] | IndiegameGarden/IndieGig | Game1/Game1/Download/GameDownloader.cs | 1,260 | C# |
using Chat.DAL.Interfaces;
using Chat.DAL.Models;
using Microsoft.EntityFrameworkCore;
namespace Chat.DAL.Implementations
{
public class ChatDbContext : DbContext, IChatDbContext
{
public ChatDbContext(DbContextOptions<ChatDbContext> options)
: base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<ChatEntity> Chats { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<ChatUser> ChatUsers { get; set; }
}
}
| 24.47619 | 70 | 0.663424 | [
"MIT"
] | FominVlad/MobileDevApp | MobileDevApp/Chat.DAL/Implementations/ChatDbContext.cs | 516 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("zlzforever@163.com;")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyCopyrightAttribute("Copyright 2018 Lewis Zou")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("DotnetSpider, a .NET Standard web crawling library. It is lightweight, efficient " +
"and fast high-level web crawling & scraping framework")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("5.0.9.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("5.0.9")]
[assembly: System.Reflection.AssemblyProductAttribute("DotnetSpider.Agent")]
[assembly: System.Reflection.AssemblyTitleAttribute("DotnetSpider.Agent")]
[assembly: System.Reflection.AssemblyVersionAttribute("5.0.9.0")]
[assembly: System.Reflection.AssemblyMetadataAttribute("RepositoryUrl", "https://github.com/dotnetcore/DotnetSpider")]
// Generated by the MSBuild WriteCodeFragment class.
| 50.962963 | 143 | 0.696948 | [
"MIT"
] | ROKT/dotnet-spider | src/DotnetSpider.Agent/obj/Debug/net5.0/DotnetSpider.Agent.AssemblyInfo.cs | 1,376 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.