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.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("13 Vowel or Digit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("13 Vowel or Digit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("556ec229-a3ee-461b-8327-7c40490be44d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.742715 | [
"MIT"
] | Bullsized/Assignments-Fundamentals-Normal | 10 - 12 Data Types and Var/2017-06-02/13 Vowel or Digit/Properties/AssemblyInfo.cs | 1,410 | C# |
using UnityEngine;
using Unity.Collections;
using System.Collections.Generic;
public class ChunkSaver
{
private Dictionary<Vector3Int, ChunkSave> chunks;
public ChunkSaver()
{
chunks = new Dictionary<Vector3Int, ChunkSave>();
}
~ChunkSaver() =>
SaveAllAndUnload();
public ChunkSave FindOrCreateChunk(Vector3Int chunkPos)
{
ChunkSave chunk;
if (!chunks.TryGetValue(chunkPos, out chunk))
{
chunk = new ChunkSave();
chunks.Add(chunkPos, chunk);
}
return chunk;
}
public ChunkSave TryFindChunk(Vector3Int chunkPos)
{
ChunkSave chunk;
chunks.TryGetValue(chunkPos, out chunk);
return chunk;
}
public bool TryFindChunk(Vector3Int chunkPos, out ChunkSave chunk)
{
return chunks.TryGetValue(chunkPos, out chunk);
}
public void SaveAllAndUnload()
{
foreach (var chunk in chunks.Values)
chunk.Dispose();
chunks.Clear();
}
}
public class ChunkSave
{
public NativeArray<float> noiseMap;
public NativeArray<uint> groundTypeMap;
public bool initialized = false;
public ChunkSave()
{
noiseMap = new NativeArray<float>(Utility.Cube(Chunk.noiseMapWidth), Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
groundTypeMap = new NativeArray<uint>(Utility.Cube(Chunk.noiseMapWidth), Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
}
~ChunkSave() =>
Dispose();
public void Dispose()
{
noiseMap.Dispose();
groundTypeMap.Dispose();
}
public ChunkSave(ChunkSave previous)
{
Debug.LogError("ChunkSave copied. Not allowed");
}
} | 23.72973 | 143 | 0.64123 | [
"MIT"
] | roopekt/MiningGame | Assets/Terrain/ChunkSaver.cs | 1,756 | C# |
using GitHubIssues;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.GitHubIssues.Services.Configuration
{
public interface IConfigurationService
{
Task<IEnumerable<RepositoryConfiguration>> GetRepositoryConfigurationsAsync();
Task<string> GetGitHubPersonalAccessTokenAsync();
Task<string> GetFromAddressAsync();
Task<string> GetSendGridTokenAsync();
}
}
| 27.941176 | 86 | 0.76 | [
"MIT"
] | AlexGhiondea/azure-sdk-tools | tools/github-issues/Azure.Sdk.Tools.GitHubIssues/Services/Configuration/IConfigurationService.cs | 477 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using GitTrends.Shared;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
namespace GitTrends
{
public class App : Xamarin.Forms.Application
{
readonly static WeakEventManager _resumedEventManager = new();
readonly IAnalyticsService _analyticsService;
readonly NotificationService _notificationService;
readonly AppInitializationService _appInitializationService;
public App(LanguageService languageService,
SplashScreenPage splashScreenPage,
IAnalyticsService analyticsService,
NotificationService notificationService,
AppInitializationService appInitializationService)
{
_analyticsService = analyticsService;
_notificationService = notificationService;
_appInitializationService = appInitializationService;
analyticsService.Track("App Initialized", new Dictionary<string, string>
{
{ nameof(LanguageService.PreferredLanguage), languageService.PreferredLanguage ?? "default" },
{ nameof(CultureInfo.CurrentUICulture), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName }
});
MainPage = splashScreenPage;
On<iOS>().SetHandleControlUpdatesOnMainThread(true);
}
public static event EventHandler Resumed
{
add => _resumedEventManager.AddEventHandler(value);
remove => _resumedEventManager.RemoveEventHandler(value);
}
protected override async void OnStart()
{
base.OnStart();
_analyticsService.Track("App Started");
await ClearBageNotifications();
var appInitializationCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));
await _appInitializationService.InitializeApp(appInitializationCancellationTokenSource.Token);
}
protected override async void OnResume()
{
base.OnResume();
OnResumed();
_analyticsService.Track("App Resumed");
await ClearBageNotifications();
}
protected override void OnSleep()
{
base.OnSleep();
_analyticsService.Track("App Backgrounded");
}
ValueTask ClearBageNotifications() => _notificationService.SetAppBadgeCount(0);
void OnResumed() => _resumedEventManager.RaiseEvent(this, EventArgs.Empty, nameof(Resumed));
}
} | 28.463415 | 104 | 0.787918 | [
"MIT"
] | Tiamat-Tech/GitTrends | GitTrends/App.cs | 2,336 | C# |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com
*/
using System;
namespace Pablo
{
/// <summary>
/// Represents an error that occured during the execution of
/// HierarchicalProperty extended functionalities.
/// </summary>
public sealed class PropertyException : Exception
{
/// <summary>
/// The faulted property.
/// </summary>
public HierarchicalProperty TargetProperty { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PropertyException"/> class.
/// </summary>
internal PropertyException(string message, Exception innerException, HierarchicalProperty targetProperty)
: base(message, innerException)
{
TargetProperty = targetProperty;
}
}
}
| 29.742857 | 113 | 0.638809 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | pabloengine/pablo | Pablo/HierarchyInfrastructure/PropertyException.cs | 1,043 | C# |
namespace ClassLib105
{
public class Class076
{
public static string Property => "ClassLib105";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib105/Class076.cs | 120 | C# |
namespace Miningcore.Blockchain.Cryptonote.StratumResponses;
public class CryptonoteResponseBase
{
public string Status { get; set; } = "OK";
}
| 21.285714 | 60 | 0.765101 | [
"MIT"
] | BitWizJason/miningcore | src/Miningcore/Blockchain/Cryptonote/StratumResponses/CryptonoteResponseBase.cs | 149 | C# |
namespace Microsoft.eShopOnDapr.Services.Catalog.API.Infrastructure.EntityConfigurations;
public class CatalogTypeEntityTypeConfiguration : IEntityTypeConfiguration<CatalogType>
{
public void Configure(EntityTypeBuilder<CatalogType> builder)
{
builder.ToTable("CatalogType");
builder.HasKey(type => type.Id);
builder.Property(type => type.Id)
.UseHiLo("catalog_type_hilo")
.IsRequired();
builder.Property(type => type.Name)
.IsRequired()
.HasMaxLength(100);
builder.HasData(
new CatalogType(1, "Cap"),
new CatalogType(2, "Mug"),
new CatalogType(3, "Pin"),
new CatalogType(4, "Sticker"),
new CatalogType(5, "T-Shirt"));
}
}
| 29.222222 | 90 | 0.614702 | [
"MIT"
] | CJ99/eShopOnDapr | src/Services/Catalog/Catalog.API/Infrastructure/EntityConfigurations/CatalogTypeEntityTypeConfiguration.cs | 791 | C# |
#region Using
using System;
using OpenGL;
#endregion
namespace Emotion.Graphics.Objects
{
/// <summary>
/// A buffer holding vertex indices.
/// </summary>
public sealed class IndexBuffer : DataBuffer
{
/// <summary>
/// The bound index buffer.
/// </summary>
public new static uint Bound
{
get => DataBuffer.Bound[BufferTarget.ElementArrayBuffer];
set => DataBuffer.Bound[BufferTarget.ElementArrayBuffer] = value;
}
public IndexBuffer(uint byteSize = 0, BufferUsage usage = BufferUsage.StaticDraw) : base(BufferTarget.ElementArrayBuffer, byteSize, usage)
{
}
/// <summary>
/// Ensures the provided pointer is the currently bound index buffer.
/// </summary>
/// <param name="pointer">The pointer to ensure is bound.</param>
public static void EnsureBound(uint pointer)
{
EnsureBound(pointer, BufferTarget.ElementArrayBuffer);
}
public static void FillQuadIndices(Span<ushort> indices, int offset)
{
for (var i = 0; i < indices.Length; i += 6)
{
indices[i] = (ushort) (offset + 0);
indices[i + 1] = (ushort) (offset + 1);
indices[i + 2] = (ushort) (offset + 2);
indices[i + 3] = (ushort) (offset + 2);
indices[i + 4] = (ushort) (offset + 3);
indices[i + 5] = (ushort) (offset + 0);
offset += 4;
}
}
}
} | 30.192308 | 146 | 0.53758 | [
"Apache-2.0",
"MIT"
] | Cryru/Emotion | Emotion/Graphics/Objects/IndexBuffer.cs | 1,572 | C# |
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace VRLabs.ToonyStandardRebuild.ModularShaderSystem.UI
{
[CustomEditor(typeof(TemplateAsset))]
public class TemplateAssetEditor : Editor
{
public override VisualElement CreateInspectorGUI()
{
CodeViewElement element = new CodeViewElement();
element.Text = serializedObject.FindProperty("Template").stringValue;
element.style.minHeight = 600;
return element;
}
}
} | 27.45 | 81 | 0.677596 | [
"MIT"
] | VRLabs/Toony-Standard-Rebuild | Dependencies/Editor/ModularShaderSystem/Editors/Inspectors/TemplateAssetEditor.cs | 549 | C# |
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Paseto.Tests")] | 79 | 79 | 0.835443 | [
"MIT"
] | daviddesmet/paseto-dotnet | src/Paseto.Cryptography/AssemblyInfo.cs | 81 | C# |
using Catalog.API.Entities;
using Catalog.API.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Catalog.API.Controllers
{
[ApiController]
[Route("api/v1/{controller}")]
public class CatalogController:ControllerBase
{
private readonly IProductRepository _repository;
private readonly ILogger<CatalogController> _logger;
public CatalogController(IProductRepository repository,ILogger<CatalogController> logger)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
var products = await _repository.GetProducts();
return Ok(products);
}
[HttpGet("{id:length(24)}", Name = "GetProduct")]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProductById(string id)
{
var product = await _repository.GetProduct(id);
if(product==null)
{
_logger.LogError($"product with id {id}, not found");
return NotFound();
}
return Ok(product);
}
[Route("[action]/{category}", Name = "GetProductByCategory")]
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(string category)
{
if(string.IsNullOrEmpty(category))
{
_logger.LogError($"the category parameter cannot be null or empty");
return NotFound();
}
var products = await _repository.GetProductByCategory(category);
return Ok(products);
}
[HttpPost]
[ProducesResponseType(typeof(Product),(int)HttpStatusCode.Created)]
public async Task<ActionResult<Product>> CreateProduct([FromBody]Product product)
{
await _repository.CreateProduct(product);
return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
}
[HttpPut]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<IActionResult> UpdateProduct([FromBody] Product product)
{
return Ok(await _repository.UpdateProduct(product));
}
[HttpDelete("{id:length(24)}", Name = "DeleteProduct")]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<ActionResult<Product>> DeleteProduct(string id)
{
return Ok(await _repository.DeleteProduct(id));
}
}
}
| 35.83908 | 99 | 0.637267 | [
"MIT"
] | thelostfrayman/AspNetMicroServices | src/Catalog/Catalog.API/Controllers/CatalogController.cs | 3,120 | C# |
using LinCms.Cms.Admins;
namespace LinCms.Cms.Users
{
public class ChangePasswordDto: ResetPasswordDto
{
// [Required(ErrorMessage = "原密码不可为空")]
public string OldPassword { get; set; }
}
}
| 18.333333 | 52 | 0.65 | [
"MIT"
] | KribKing/lin-cms-dotnetcore | src/LinCms.Application.Contracts/Cms/Users/ChangePasswordDto.cs | 236 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Luckshot.FSM
{
[DefaultExecutionOrder(300)]
public class StateMachineState : MonoBehaviour
{
protected StateMachine stateMachine = null;
protected StateMachine StateMachine
{ get { return stateMachine; } }
public K GetState<K>() where K : StateMachineState
{ return stateMachine.GetState<K>(); }
public void ChangeState<K>(StateParams stateParams = null) where K : StateMachineState
{ stateMachine.ChangeState<K>(stateParams); }
public void SetStateMachine(StateMachine inStateMachine)
{ stateMachine = inStateMachine; }
private float enterStateTime = 0f;
public float EnterStateTime
{ get { return enterStateTime; } }
protected float lastTimeInState = 0f;
public float LastTimeInState
{ get { return lastTimeInState; } }
protected bool hasAwoken = false;
public bool HasAwoken
{ get { return hasAwoken; } }
public void Awake()
{
if (hasAwoken)
return;
AwakeIfNeeded();
hasAwoken = true;
}
public virtual void AwakeIfNeeded() { }
public virtual void Enter(StateParams stateParams)
{
enterStateTime = Time.time;
lastTimeInState = Time.time;
}
public virtual void Exit()
{
lastTimeInState = Time.time;
}
public virtual void Tick()
{
lastTimeInState = Time.time;
}
public virtual void FixedTick() { }
public virtual void CollisionEnter(Collision collision) { }
public virtual void CollisionExit(Collision collision) { }
public virtual void TriggerEnter(Collider collider) { }
public virtual void TriggerExit(Collider collider) { }
}
public abstract class StateMachineState<T> : StateMachineState where T : MonoBehaviour
{
public T Owner
{ get { return stateMachine.Owner as T; } }
}
public class StateParams
{
}
} | 23.714286 | 88 | 0.726177 | [
"MIT"
] | cjacobwade/BigHopsTools | BigHopsTools/Assets/Plugins/Luckshot/Scripts/StateMachine/StateMachineState.cs | 1,828 | C# |
namespace Telerik.UI.Xaml.Controls.Map
{
/// <summary>
/// Defines the available modes to process user input that affects the <see cref="RadMap.ZoomLevel"/> property.
/// </summary>
public enum MapZoomMode
{
/// <summary>
/// The map is zoomed to the contact point with the primary pointer that triggered the input.
/// </summary>
ZoomToPoint,
/// <summary>
/// The map is zoomed its center regardless of the primary pointer that triggered the input.
/// </summary>
ZoomToCenter,
/// <summary>
/// The map may not be zoomed through user input.
/// </summary>
None
}
}
| 28.791667 | 115 | 0.586107 | [
"Apache-2.0"
] | ChristianGutman/UI-For-UWP | Controls/Map/Map.UWP/Behaviors/PanAndZoom/MapZoomMode.cs | 693 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreMoney : MonoBehaviour {
public int money = 1000000;
public Text moneyText;
public Text healthText;
void Update()
{
moneyText.text = "Gold: " + money.ToString();
healthText.text = "Health: " + CoreBehaviour.getHealth();
}
}
| 19.647059 | 65 | 0.694611 | [
"MIT"
] | aaronr4043/Pirate-In-Barrels | Assets/Scripts/ScoreMoney.cs | 336 | C# |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text.RegularExpressions;
#if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
#endif
namespace Sabresaurus.SabreCSG
{
public static class EditorHelper
{
// Threshold for raycasting vertex clicks, in screen space (should match half the icon dimensions)
const float CLICK_THRESHOLD = 15;
// Used for offseting mouse position
const int TOOLBAR_HEIGHT = 37;
public static bool HasDelegate (System.Delegate mainDelegate, System.Delegate targetListener)
{
if (mainDelegate != null)
{
if (mainDelegate.GetInvocationList().Contains(targetListener))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static bool SceneViewHasDelegate(SceneView.OnSceneFunc targetDelegate)
{
return HasDelegate(SceneView.onSceneGUIDelegate, targetDelegate);
}
public enum SceneViewCamera { Top, Bottom, Left, Right, Front, Back, Other };
public static SceneViewCamera GetSceneViewCamera(SceneView sceneView)
{
return GetSceneViewCamera(sceneView.camera);
}
public static SceneViewCamera GetSceneViewCamera(Camera camera)
{
Vector3 cameraForward = camera.transform.forward;
if (cameraForward == new Vector3(0, -1, 0))
{
return SceneViewCamera.Top;
}
else if (cameraForward == new Vector3(0, 1, 0))
{
return SceneViewCamera.Bottom;
}
else if (cameraForward == new Vector3(1, 0, 0))
{
return SceneViewCamera.Left;
}
else if (cameraForward == new Vector3(-1, 0, 0))
{
return SceneViewCamera.Right;
}
else if (cameraForward == new Vector3(0, 0, -1))
{
return SceneViewCamera.Front;
}
else if (cameraForward == new Vector3(0, 0, 1))
{
return SceneViewCamera.Back;
}
else
{
return SceneViewCamera.Other;
}
}
/// <summary>
/// Whether the mouse position is within the bounds of the axis snapping gizmo that appears in the top right
/// </summary>
public static bool IsMousePositionNearSceneGizmo(Vector2 mousePosition)
{
float scale = 1;
#if UNITY_5_4_OR_NEWER
mousePosition = EditorGUIUtility.PointsToPixels(mousePosition);
scale = EditorGUIUtility.pixelsPerPoint;
#endif
mousePosition.x = Screen.width - mousePosition.x;
if (mousePosition.x > 14 * scale
&& mousePosition.x < 89 * scale
&& mousePosition.y > 14 * scale
&& mousePosition.y < 105 * scale)
{
return true;
}
else
{
return false;
}
}
public static Vector2 ConvertMousePointPosition(Vector2 sourceMousePosition, bool convertPointsToPixels = true)
{
#if UNITY_5_4_OR_NEWER
if(convertPointsToPixels)
{
sourceMousePosition = EditorGUIUtility.PointsToPixels(sourceMousePosition);
}
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - (TOOLBAR_HEIGHT * EditorGUIUtility.pixelsPerPoint);
#else
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - TOOLBAR_HEIGHT;
#endif
return sourceMousePosition;
}
public static Vector2 ConvertMousePixelPosition(Vector2 sourceMousePosition, bool convertPixelsToPoints = true)
{
#if UNITY_5_4_OR_NEWER
if(convertPixelsToPoints)
{
sourceMousePosition = EditorGUIUtility.PixelsToPoints(sourceMousePosition);
}
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = (Screen.height / EditorGUIUtility.pixelsPerPoint) - sourceMousePosition.y - (TOOLBAR_HEIGHT);
#else
// Flip the direction of Y and remove the Scene View top toolbar's height
sourceMousePosition.y = Screen.height - sourceMousePosition.y - TOOLBAR_HEIGHT;
#endif
return sourceMousePosition;
}
public static bool IsMousePositionInIMGUIRect(Vector2 mousePosition, Rect rect)
{
// This works in point space, not pixel space
mousePosition += new Vector2(0, EditorStyles.toolbar.fixedHeight);
return rect.Contains(mousePosition);
}
public static bool InClickZone(Vector2 mousePosition, Vector3 worldPosition)
{
mousePosition = ConvertMousePointPosition(mousePosition);
Vector3 targetScreenPosition = Camera.current.WorldToScreenPoint(worldPosition);
if (targetScreenPosition.z < 0)
{
return false;
}
float distance = Vector2.Distance(mousePosition, targetScreenPosition);
float depthDistance = targetScreenPosition.z;
//#if UNITY_5_4_OR_NEWER
// depthDistance *= EditorGUIUtility.pixelsPerPoint;
//#endif
// When z is 6 then click threshold is 15
// when z is 20 then click threshold is 5
float threshold;
// if(CurrentSettings.ReducedHandleThreshold)
// {
// threshold = Mathf.Lerp(5, 2, Mathf.InverseLerp(6,20,depthDistance));
// }
// else
{
threshold = Mathf.Lerp(15, 5, Mathf.InverseLerp(6,20,depthDistance));
}
#if UNITY_5_4_OR_NEWER
threshold *= EditorGUIUtility.pixelsPerPoint;
#endif
if (distance <= threshold)
{
return true;
}
else
{
return false;
}
}
public static bool InClickRect(Vector2 mousePosition, Vector3 worldPosition1, Vector3 worldPosition2)
{
mousePosition = ConvertMousePointPosition(mousePosition);
Vector3 targetScreenPosition1 = Camera.current.WorldToScreenPoint(worldPosition1);
Vector3 targetScreenPosition2 = Camera.current.WorldToScreenPoint(worldPosition2);
if (targetScreenPosition1.z < 0)
{
return false;
}
// When z is 6 then click threshold is 15
// when z is 20 then click threshold is 5
float threshold = Mathf.Lerp(15, 5, Mathf.InverseLerp(6,20,targetScreenPosition1.z));
#if UNITY_5_4_OR_NEWER
threshold *= EditorGUIUtility.pixelsPerPoint;
#endif
Vector3 closestPoint = MathHelper.ProjectPointOnLineSegment(targetScreenPosition1, targetScreenPosition2, mousePosition);
closestPoint.z = 0;
if(Vector3.Distance(closestPoint, mousePosition) < threshold)
// if(mousePosition.y > Mathf.Min(targetScreenPosition1.y, targetScreenPosition2.y - threshold)
// && mousePosition.y < Mathf.Max(targetScreenPosition1.y, targetScreenPosition2.y) + threshold
// && mousePosition.x > Mathf.Min(targetScreenPosition1.x, targetScreenPosition2.x - threshold)
// && mousePosition.x < Mathf.Max(targetScreenPosition1.x, targetScreenPosition2.x) + threshold)
{
return true;
}
else
{
return false;
}
}
public static Vector3 CalculateWorldPoint(SceneView sceneView, Vector3 screenPoint)
{
screenPoint = ConvertMousePointPosition(screenPoint);
return sceneView.camera.ScreenToWorldPoint(screenPoint);
}
// public static string GetCurrentSceneGUID()
// {
// string currentScenePath = EditorApplication.currentScene;
// if(!string.IsNullOrEmpty(currentScenePath))
// {
// return AssetDatabase.AssetPathToGUID(currentScenePath);
// }
// else
// {
// // Scene hasn't been saved
// return null;
// }
// }
public static void SetDirty(Object targetObject)
{
if(!Application.isPlaying)
{
EditorUtility.SetDirty(targetObject);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
// As of Unity 5, SetDirty no longer marks the scene as dirty. Need to use the new call for that.
EditorApplication.MarkSceneDirty();
#else // 5.3 and above introduce multiple scene management via EditorSceneManager
Scene activeScene = EditorSceneManager.GetActiveScene();
EditorSceneManager.MarkSceneDirty(activeScene);
#endif
}
}
public static void IsoAlignSceneView(Vector3 direction)
{
SceneView sceneView = SceneView.lastActiveSceneView;
SceneView.lastActiveSceneView.LookAt(sceneView.pivot, Quaternion.LookRotation(direction));
// Mark the camera as iso (orthographic)
sceneView.orthographic = true;
}
public static void IsoAlignSceneViewToNearest()
{
SceneView sceneView = SceneView.lastActiveSceneView;
Vector3 cameraForward = sceneView.camera.transform.forward;
Vector3 newForward = Vector3.up;
float bestDot = -1;
Vector3 testDirection;
float dot;
// Find out of the six axis directions the closest direction to the camera
for (int i = 0; i < 3; i++)
{
testDirection = Vector3.zero;
testDirection[i] = 1;
dot = Vector3.Dot(testDirection, cameraForward);
if(dot > bestDot)
{
bestDot = dot;
newForward = testDirection;
}
testDirection[i] = -1;
dot = Vector3.Dot(testDirection, cameraForward);
if(dot > bestDot)
{
bestDot = dot;
newForward = testDirection;
}
}
IsoAlignSceneView(newForward);
}
/// <summary>
/// Overrides the built in selection duplication to maintain sibling order of the selection. But only if at least one of the selection is under a CSG Model.
/// </summary>
/// <returns><c>true</c>, if our custom duplication took place (and one of the selection was under a CSG Model), <c>false</c> otherwise in which case the duplication event should not be consumed so that Unity will duplicate for us.</returns>
public static bool DuplicateSelection()
{
List<Transform> selectedTransforms = Selection.transforms.ToList();
// Whether any of the selection objects are under a CSG Model
bool shouldCustomDuplicationOccur = false;
for (int i = 0; i < selectedTransforms.Count; i++)
{
if(selectedTransforms[i].GetComponentInParent<CSGModel>() != null)
{
shouldCustomDuplicationOccur = true;
}
}
if(shouldCustomDuplicationOccur) // Some of the objects are under a CSG Model, so peform our special duplication override
{
// Sort the selected transforms in order of sibling index
selectedTransforms.Sort((x,y) => x.GetSiblingIndex().CompareTo(y.GetSiblingIndex()));
GameObject[] newObjects = new GameObject[Selection.gameObjects.Length];
// Walk through each selected object in the correct order, duplicating them one by one
for (int i = 0; i < selectedTransforms.Count; i++)
{
// Temporarily set the selection to the single entry
Selection.activeGameObject = selectedTransforms[i].gameObject;
// Duplicate the single entry
Unsupported.DuplicateGameObjectsUsingPasteboard();
// Cache the new entry, so when we're done we reselect all new objects
newObjects[i] = Selection.activeGameObject;
}
// Finished duplicating, select all new objects
Selection.objects = newObjects;
}
// Whether custom duplication took place and whether the Duplicate event should be consumed
return shouldCustomDuplicationOccur;
}
public class TransformIndexComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Transform) x).GetSiblingIndex().CompareTo(((Transform) y).GetSiblingIndex());
}
}
}
}
#endif | 31.070845 | 243 | 0.694116 | [
"MIT"
] | BentouDev/SenseiJam2017 | Assets/SabreCSG/Scripts/Extensions/EditorHelper.cs | 11,403 | C# |
using Thegioisticker.Data.Repositories;
using System.Threading.Tasks;
using System.Web.Http;
namespace Thegioisticker.API.Controllers
{
[RoutePrefix("api/RefreshTokens")]
public class RefreshTokensController : ApiController
{
private AuthRepository _repo = null;
public RefreshTokensController()
{
_repo = new AuthRepository();
}
[Authorize(Users="Admin")]
[Route("")]
public IHttpActionResult Get()
{
return Ok(_repo.GetAllRefreshTokens());
}
//[Authorize(Users = "Admin")]
[AllowAnonymous]
[Route("")]
public async Task<IHttpActionResult> Delete(string tokenId)
{
var result = await _repo.RemoveRefreshToken(tokenId);
if (result)
{
return Ok();
}
return BadRequest("Token Id does not exist");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_repo.Dispose();
}
base.Dispose(disposing);
}
}
}
| 23.18 | 67 | 0.534944 | [
"MIT"
] | quocbaouit/Thegioisticker | Thegioisticker/ApiControllers/RefreshTokensController.cs | 1,161 | C# |
// Copyright (c) 2010-2013 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.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyProduct("SharpDX.DXGI")]
[assembly: AssemblyTitle("SharpDX.DXGI")]
[assembly: AssemblyDescription("Assembly providing DirectX - DXGI 1.0, 1.1 and 1.2 managed API")]
#if SHARPDX_SIGNED
[assembly: InternalsVisibleTo("SharpDX.Direct3D10,PublicKey=00240000048000009400000006020000002400005253413100040000010001000941e9108cca1ea51fbd8d3c1a834aab15d98ee7dbee30b31b2c5a8e399fe012d91e5b849ca36812696ee573283399eb487822154971496b06304fd02637ef8e9026904ab2632bd5c9f6f6e13c2bf449157ae79d4a12871e7743404f8f40dbd66dca7321fc507f6a25eb87f5c52d7f5e6145e4172092eecca14425714dc5609a")]
[assembly: InternalsVisibleTo("SharpDX.Direct3D11,PublicKey=00240000048000009400000006020000002400005253413100040000010001000941e9108cca1ea51fbd8d3c1a834aab15d98ee7dbee30b31b2c5a8e399fe012d91e5b849ca36812696ee573283399eb487822154971496b06304fd02637ef8e9026904ab2632bd5c9f6f6e13c2bf449157ae79d4a12871e7743404f8f40dbd66dca7321fc507f6a25eb87f5c52d7f5e6145e4172092eecca14425714dc5609a")]
#else
// Make internals SharpDX visible to all SharpDX assemblies
[assembly: InternalsVisibleTo("SharpDX.Direct3D10")]
[assembly: InternalsVisibleTo("SharpDX.Direct3D11")]
#endif
| 64.486486 | 384 | 0.823135 | [
"MIT"
] | shoelzer/SharpDX | Source/SharpDX.DXGI/Properties/AssemblyInfo.cs | 2,388 | C# |
//-----------------------------------------------------------------------------
// Author(s):
// Aaron Clauson
//
// History:
//
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.Extensions.Logging;
using SIPSorcery.Sys;
using Xunit;
namespace SIPSorcery.Net.UnitTests
{
[Trait("Category", "unit")]
public class STUNUnitTest
{
private Microsoft.Extensions.Logging.ILogger logger = null;
public STUNUnitTest(Xunit.Abstractions.ITestOutputHelper output)
{
logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
}
/// <summary>
/// Parse a STUN request received from the Chrome browser's WebRTC stack.
/// </summary>
[Fact]
public void ParseWebRTCSTUNRequestTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] stunReq = new byte[]{ 0x00, 0x01, 0x00, 0x60, 0x21, 0x12, 0xa4, 0x42, 0x66, 0x55, 0x55, 0x43, 0x4b, 0x48, 0x74, 0x73, 0x68, 0x4e, 0x71, 0x56,
// Att1:
0x00, 0x06, 0x00, 0x21,
0x6d, 0x30, 0x71, 0x47, 0x77, 0x53, 0x71, 0x2f, 0x48, 0x56, 0x48, 0x71, 0x41, 0x62, 0x4b, 0x62, 0x3a, 0x73, 0x64, 0x43,
0x48, 0x59, 0x6b, 0x35, 0x6e, 0x46, 0x34, 0x79, 0x44, 0x77, 0x55, 0x39, 0x53, 0x00, 0x00, 0x00,
// Att2
0x80, 0x2a, 0x00, 0x08,
0xa0, 0x36, 0xc9, 0x6c, 0x30, 0xc6, 0x2f, 0xd2, 0x00, 0x25, 0x00, 0x00, 0x00, 0x24, 0x00, 0x04,
0x6e, 0x7f, 0x1e, 0xff, 0x00, 0x08, 0x00, 0x14, 0x81, 0x4a, 0x4f, 0xaf, 0x3d, 0x99, 0x30, 0x67,
0x66, 0xb9, 0x48, 0x67, 0x83, 0x72, 0xd5, 0xa0, 0x7a, 0x87, 0xb5, 0x3f, 0x80, 0x28, 0x00, 0x04,
0x49, 0x7e, 0x51, 0x17 };
STUNMessage stunMessage = STUNMessage.ParseSTUNMessage(stunReq, stunReq.Length);
STUNHeader stunHeader = stunMessage.Header;
logger.LogDebug("Request type = " + stunHeader.MessageType + ".");
logger.LogDebug("Length = " + stunHeader.MessageLength + ".");
logger.LogDebug("Transaction ID = " + BitConverter.ToString(stunHeader.TransactionId) + ".");
Assert.Equal(STUNMessageTypesEnum.BindingRequest, stunHeader.MessageType);
Assert.Equal(96, stunHeader.MessageLength);
Assert.Equal(6, stunMessage.Attributes.Count);
}
/// <summary>
/// Tests that a binding request with a username attribute is correctly output to a byte array.
/// </summary>
[Fact]
public void BindingRequestWithUsernameToBytesUnitTest()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
STUNMessage initMessage = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
initMessage.AddUsernameAttribute("someusernamex");
byte[] stunMessageBytes = initMessage.ToByteBuffer(null, false);
logger.LogDebug(BitConverter.ToString(stunMessageBytes));
Assert.True(stunMessageBytes.Length % 4 == 0);
}
/// <summary>
/// Parse a STUN response received from the Chrome browser's WebRTC stack.
/// </summary>
[Fact]
public void ParseWebRTCSTUNResponseTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] stunResp = new byte[]{ 0x01, 0x01, 0x00, 0x2c, 0x21, 0x12, 0xa4, 0x42, 0x6a, 0x45, 0x38, 0x2b, 0x4e, 0x5a, 0x4b, 0x50,
0x64, 0x31, 0x70, 0x38, 0x00, 0x20, 0x00, 0x08, 0x00, 0x01, 0xe0, 0xda, 0xe1, 0xba, 0x85, 0x3f,
0x00, 0x08, 0x00, 0x14, 0x24, 0x37, 0x24, 0xa0, 0x05, 0x2d, 0x88, 0x97, 0xce, 0xa6, 0x4e, 0x90,
0x69, 0xf6, 0x39, 0x07, 0x7d, 0xb1, 0x6e, 0x71, 0x80, 0x28, 0x00, 0x04, 0xde, 0x6a, 0x05, 0xac};
STUNMessage stunMessage = STUNMessage.ParseSTUNMessage(stunResp, stunResp.Length);
STUNHeader stunHeader = stunMessage.Header;
logger.LogDebug("Request type = " + stunHeader.MessageType + ".");
logger.LogDebug("Length = " + stunHeader.MessageLength + ".");
logger.LogDebug("Transaction ID = " + BitConverter.ToString(stunHeader.TransactionId) + ".");
foreach (STUNAttribute attribute in stunMessage.Attributes)
{
if (attribute.AttributeType == STUNAttributeTypesEnum.Username)
{
logger.LogDebug(" " + attribute.AttributeType + " " + Encoding.UTF8.GetString(attribute.Value) + ".");
}
else
{
logger.LogDebug(" " + attribute.AttributeType + " " + attribute.Value + ".");
}
}
Assert.Equal(STUNMessageTypesEnum.BindingSuccessResponse, stunHeader.MessageType);
Assert.Equal(44, stunHeader.MessageLength);
Assert.Equal(3, stunMessage.Attributes.Count);
}
/// <summary>
/// Tests that parsing an XOR-MAPPED-ADDRESS attribute correctly extracts the IP Address and Port.
/// </summary>
[Fact]
public void ParseXORMappedAddressAttributeTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] stunAttribute = new byte[] { 0x00, 0x01, 0xe0, 0xda, 0xe1, 0xba, 0x85, 0x3f };
STUNXORAddressAttribute xorAddressAttribute = new STUNXORAddressAttribute(STUNAttributeTypesEnum.XORMappedAddress, stunAttribute);
Assert.Equal(49608, xorAddressAttribute.Port);
Assert.Equal("192.168.33.125", xorAddressAttribute.Address.ToString());
}
/// <summary>
/// Tests that putting an XOR-MAPPED-ADDRESS attribute to a byte buffer works correctly.
/// </summary>
[Fact]
public void PutXORMappedAddressAttributeToBufferTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
STUNXORAddressAttribute xorAddressAttribute = new STUNXORAddressAttribute(STUNAttributeTypesEnum.XORMappedAddress, 49608, IPAddress.Parse("192.168.33.125"));
byte[] buffer = new byte[12];
xorAddressAttribute.ToByteBuffer(buffer, 0);
Assert.Equal(0x00, buffer[0]);
Assert.Equal(0x20, buffer[1]);
Assert.Equal(0x00, buffer[2]);
Assert.Equal(0x08, buffer[3]);
Assert.Equal(0x00, buffer[4]);
Assert.Equal(0x01, buffer[5]);
Assert.Equal(0xe0, buffer[6]);
Assert.Equal(0xda, buffer[7]);
Assert.Equal(0xe1, buffer[8]);
Assert.Equal(0xba, buffer[9]);
Assert.Equal(0x85, buffer[10]);
Assert.Equal(0x3f, buffer[11]);
}
/// <summary>
/// Tests that putting a STUN response to a byte buffer works correctly.
/// </summary>
[Fact]
public void PutResponseToBufferTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
STUNMessage stunResponse = new STUNMessage(STUNMessageTypesEnum.BindingSuccessResponse);
stunResponse.Header.TransactionId = Guid.NewGuid().ToByteArray().Take(12).ToArray();
//stunResponse.AddFingerPrintAttribute();
stunResponse.AddXORMappedAddressAttribute(IPAddress.Parse("127.0.0.1"), 1234);
byte[] buffer = stunResponse.ToByteBuffer(null, true);
}
/// <summary>
/// Tests that the message integrity attribute is being correctly generated. The original STUN request packet
/// was capture on the wire from the Google Chrome WebRTC stack.
/// </summary>
[Fact]
public void TestMessageIntegrityAttributeForBindingRequest()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] stunReq = new byte[]{
0x00, 0x01, 0x00, 0x60, 0x21, 0x12, 0xa4, 0x42, 0x69, 0x64, 0x38, 0x2b, 0x4c, 0x45, 0x44, 0x57,
0x4d, 0x31, 0x64, 0x30, 0x00, 0x06, 0x00, 0x21, 0x75, 0x4f, 0x35, 0x73, 0x69, 0x31, 0x75, 0x61,
0x37, 0x63, 0x59, 0x34, 0x74, 0x38, 0x4d, 0x4d, 0x3a, 0x4c, 0x77, 0x38, 0x2f, 0x30, 0x43, 0x31,
0x43, 0x72, 0x76, 0x68, 0x5a, 0x43, 0x31, 0x67, 0x62, 0x00, 0x00, 0x00, 0x80, 0x2a, 0x00, 0x08,
0xc0, 0x3d, 0xf5, 0x13, 0x40, 0xf4, 0x22, 0x46, 0x00, 0x25, 0x00, 0x00, 0x00, 0x24, 0x00, 0x04,
0x6e, 0x7f, 0x1e, 0xff, 0x00, 0x08, 0x00, 0x14, 0x55, 0x82, 0x69, 0xde, 0x17, 0x55, 0xcc, 0x66,
0x29, 0x23, 0xe6, 0x7d, 0xec, 0x87, 0x6c, 0x07, 0x3a, 0xd6, 0x78, 0x15, 0x80, 0x28, 0x00, 0x04,
0x1c, 0xae, 0x89, 0x2e};
STUNMessage stunMessage = STUNMessage.ParseSTUNMessage(stunReq, stunReq.Length);
STUNHeader stunHeader = stunMessage.Header;
logger.LogDebug("Request type = " + stunHeader.MessageType + ".");
logger.LogDebug("Length = " + stunHeader.MessageLength + ".");
logger.LogDebug("Transaction ID = " + BitConverter.ToString(stunHeader.TransactionId) + ".");
Assert.Equal(STUNMessageTypesEnum.BindingRequest, stunHeader.MessageType);
Assert.Equal(96, stunHeader.MessageLength);
Assert.Equal(6, stunMessage.Attributes.Count);
Assert.Equal("69-64-38-2B-4C-45-44-57-4D-31-64-30", BitConverter.ToString(stunMessage.Header.TransactionId));
stunMessage.Attributes.Remove(stunMessage.Attributes.Where(x => x.AttributeType == STUNAttributeTypesEnum.MessageIntegrity).Single());
stunMessage.Attributes.Remove(stunMessage.Attributes.Where(x => x.AttributeType == STUNAttributeTypesEnum.FingerPrint).Single());
byte[] buffer = stunMessage.ToByteBufferStringKey("r89XhWC9k2kW4Pns75vmwHIa", true);
Assert.Equal(BitConverter.ToString(stunReq), BitConverter.ToString(buffer));
}
/// <summary>
/// Parse a STUN response received from the Coturn TURN server.
/// </summary>
[Fact]
public void ParseCoturnSTUNResponseTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] stunResp = new byte[]{ 0x01, 0x01, 0x00, 0x44, 0x21, 0x12, 0xa4, 0x42, 0x6b, 0x4c, 0xf3, 0x18, 0xd0, 0xa7, 0xf5, 0x40,
0x97, 0x30, 0x3a, 0x27, 0x00, 0x20, 0x00, 0x08, 0x00, 0x01, 0x9e, 0x90, 0x1a, 0xb5, 0x08, 0xf3,
0x00, 0x01, 0x00, 0x08, 0x00, 0x01, 0xbf, 0x82, 0x3b, 0xa7, 0xac, 0xb1, 0x80, 0x2b, 0x00, 0x08,
0x00, 0x01, 0x0d, 0x96, 0x67, 0x1d, 0x42, 0xf3, 0x80, 0x22, 0x00, 0x1a, 0x43, 0x6f, 0x74, 0x75,
0x72, 0x6e, 0x2d, 0x34, 0x2e, 0x35, 0x2e, 0x30, 0x2e, 0x33, 0x20, 0x27, 0x64, 0x61, 0x6e, 0x20,
0x45, 0x69, 0x64, 0x65, 0x72, 0x27, 0x77, 0x75};
STUNMessage stunMessage = STUNMessage.ParseSTUNMessage(stunResp, stunResp.Length);
STUNHeader stunHeader = stunMessage.Header;
logger.LogDebug("Request type = " + stunHeader.MessageType + ".");
logger.LogDebug("Length = " + stunHeader.MessageLength + ".");
logger.LogDebug("Transaction ID = " + BitConverter.ToString(stunHeader.TransactionId) + ".");
foreach (STUNAttribute attribute in stunMessage.Attributes)
{
if (attribute.AttributeType == STUNAttributeTypesEnum.MappedAddress)
{
STUNAddressAttribute addressAttribute = new STUNAddressAttribute(attribute.Value);
logger.LogDebug(" " + attribute.AttributeType + " " + addressAttribute.Address + ":" + addressAttribute.Port + ".");
Assert.Equal("59.167.172.177", addressAttribute.Address.ToString());
Assert.Equal(49026, addressAttribute.Port);
}
else if (attribute.AttributeType == STUNAttributeTypesEnum.XORMappedAddress)
{
STUNXORAddressAttribute xorAddressAttribute = new STUNXORAddressAttribute(STUNAttributeTypesEnum.XORMappedAddress, attribute.Value);
logger.LogDebug(" " + attribute.AttributeType + " " + xorAddressAttribute.Address + ":" + xorAddressAttribute.Port + ".");
Assert.Equal("59.167.172.177", xorAddressAttribute.Address.ToString());
Assert.Equal(49026, xorAddressAttribute.Port);
}
else
{
logger.LogDebug(" " + attribute.AttributeType + " " + attribute.Value + ".");
}
}
Assert.Equal(STUNMessageTypesEnum.BindingSuccessResponse, stunHeader.MessageType);
}
/// <summary>
/// Tests that the fingerprint and hmac attributes get generated correctly.
/// </summary>
[Fact]
public void GenerateHmacAndFingerprintTestMethod()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
string icePassword = "SKYKPPYLTZOAVCLTGHDUODANRKSPOVQVKXJULOGG";
STUNMessage msg = new STUNMessage(STUNMessageTypesEnum.BindingSuccessResponse);
msg.Header.TransactionId = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
msg.AddXORMappedAddressAttribute(IPAddress.Loopback, 55477);
var buffer = msg.ToByteBufferStringKey(icePassword, true);
string hmac = "HMAC: ";
for (int i = 36; i < 56; i++)
{
hmac += $"{buffer[i]:X2} ";
}
logger.LogDebug(hmac);
logger.LogDebug($"Fingerprint: {buffer[buffer.Length - 4]:X2} {buffer[buffer.Length - 3]:X2} {buffer[buffer.Length - 2]:X2} {buffer[buffer.Length - 1]:X2}.");
}
/// <summary>
/// Tests that the STUN header class type is correctly determined from the message type.
/// </summary>
[Fact]
public void CheckCLassForSTUNMessageTypeUnitTest()
{
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.BindingRequest).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.Allocate).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.Refresh).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.Send).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.Data).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.CreatePermission).MessageClass));
Assert.Equal(STUNClassTypesEnum.Request, (new STUNHeader(STUNMessageTypesEnum.ChannelBind).MessageClass));
Assert.Equal(STUNClassTypesEnum.SuccessResponse, (new STUNHeader(STUNMessageTypesEnum.BindingSuccessResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.SuccessResponse, (new STUNHeader(STUNMessageTypesEnum.AllocateSuccessResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.SuccessResponse, (new STUNHeader(STUNMessageTypesEnum.CreatePermissionSuccessResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.ErrorResponse, (new STUNHeader(STUNMessageTypesEnum.BindingErrorResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.ErrorResponse, (new STUNHeader(STUNMessageTypesEnum.AllocateErrorResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.ErrorResponse, (new STUNHeader(STUNMessageTypesEnum.CreatePermissionErrorResponse).MessageClass));
Assert.Equal(STUNClassTypesEnum.Indication, (new STUNHeader(STUNMessageTypesEnum.DataIndication).MessageClass));
Assert.Equal(STUNClassTypesEnum.Indication, (new STUNHeader(STUNMessageTypesEnum.SendIndication).MessageClass));
}
/// <summary>
/// Tests that a locally signed STUN request can be verified.
/// </summary>
[Fact]
public void IntegrityCheckUnitTest()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
string icePassword = "SKYKPPYLTZOAVCLTGHDUODANRKSPOVQVKXJULOGG";
STUNMessage stunRequest = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
stunRequest.Header.TransactionId = Encoding.ASCII.GetBytes(Crypto.GetRandomString(STUNHeader.TRANSACTION_ID_LENGTH));
stunRequest.AddUsernameAttribute("xxxx:yyyy");
stunRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Priority, BitConverter.GetBytes(1)));
var buffer = stunRequest.ToByteBufferStringKey(icePassword, true);
//logger.LogDebug($"HMAC: {buffer.Skip(buffer.Length - ).Take(20).ToArray().HexStr()}.");
//logger.LogDebug($"Fingerprint: {buffer.Skip(buffer.Length -4).ToArray().HexStr()}.");
STUNMessage rndTripReq = STUNMessage.ParseSTUNMessage(buffer, buffer.Length);
Assert.True(rndTripReq.isFingerprintValid);
Assert.True(rndTripReq.CheckIntegrity(System.Text.Encoding.UTF8.GetBytes(icePassword)));
}
/// <summary>
/// Tests that a known STUN request can be verified.
/// </summary>
[Fact]
public void KnownSTUNBindingRequestIntegrityCheckUnitTest()
{
logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);
string icePassword = "DVJSBHBUIBFSZFKVECMPRISQ";
byte[] buffer = TypeExtensions.ParseHexStr(
"0001003C2112A4424A5655444B44544753454455000600095A4C45423A4554454F00000000240" +
"008CC3A28000000000000080014B295EDA4BC88A0BC885D745644D36E51FE3CBD1880280004EDF60FF7");
STUNMessage stunRequest = STUNMessage.ParseSTUNMessage(buffer, buffer.Length);
Assert.True(stunRequest.isFingerprintValid);
Assert.True(stunRequest.CheckIntegrity(System.Text.Encoding.UTF8.GetBytes(icePassword)));
}
/// <summary>
/// Checks that the length of the PRIORITY attribute is correct after round tripping.
/// </summary>
[Fact]
public void CheckPriorityAttributeLengthUnitTest()
{
STUNMessage stunRequest = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
stunRequest.AddUsernameAttribute("dummy:dummy");
stunRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Priority, BitConverter.GetBytes(1234U)));
stunRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.UseCandidate, null));
byte[] stunReqBytes = stunRequest.ToByteBufferStringKey("dummy", true);
var stunReq = STUNMessage.ParseSTUNMessage(stunReqBytes, stunReqBytes.Length);
Assert.Equal(4, stunReq.Attributes.Single(x => x.AttributeType == STUNAttributeTypesEnum.Priority).Value.Length);
}
/// <summary>
/// Checks that a STUN binding request with an ICE-CONTROLLED attribute can be
/// parsed correctly.
/// </summary>
[Fact]
public void ParseBindingRequestWithIceControlledAttribute()
{
var buffer = new byte[]
{
0x00, 0x01, 0x00, 0x50, 0x21, 0x12, 0xa4, 0x42, 0x0c, 0x66, 0x64, 0x5a, 0xf7, 0xe9, 0xe6, 0x57,
0x3f, 0x53, 0x2b, 0x33, 0x00, 0x24, 0x00, 0x04, 0x6e, 0x7f, 0xff, 0xff, 0x80, 0x29, 0x00, 0x08,
0x27, 0xff, 0x2a, 0x17, 0x1b, 0x88, 0x8f, 0xfe, 0x80, 0x22, 0x00, 0x08, 0x6c, 0x69, 0x62, 0x6a,
0x75, 0x69, 0x63, 0x65, 0x00, 0x06, 0x00, 0x09, 0x4e, 0x4f, 0x43, 0x47, 0x3a, 0x6b, 0x57, 0x55,
0x48, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x14, 0x23, 0x7e, 0x24, 0x6c, 0x44, 0x12, 0xbc, 0x43,
0xfc, 0x63, 0x01, 0xf4, 0xda, 0x36, 0x73, 0xdf, 0x84, 0xb8, 0x23, 0xd6, 0x80, 0x28, 0x00, 0x04,
0x07, 0x8a, 0x49, 0x2e
};
var stunReq = STUNMessage.ParseSTUNMessage(buffer, buffer.Length);
Assert.NotNull(stunReq);
Assert.Equal(1853882367U,
NetConvert.ParseUInt32(stunReq.Attributes.Single(x => x.AttributeType == STUNAttributeTypesEnum.Priority).Value, 0));
Assert.Equal(8, stunReq.Attributes.Single(x => x.AttributeType == STUNAttributeTypesEnum.IceControlled).PaddedLength);
Assert.Equal(0x27ff2a171b888ffeU,
NetConvert.ParseUInt64(stunReq.Attributes.Single(x => x.AttributeType == STUNAttributeTypesEnum.IceControlled).Value, 0));
}
}
}
| 53.222749 | 170 | 0.621817 | [
"Apache-2.0"
] | Ali-Russell/sipsorcery | test/unit/net/STUN/STUNUnitTest.cs | 22,462 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets.ExpTools;
using UnityEngine.UI;
using Assets.Keyboards;
using System.Timers;
using System.IO;
//Edit -> Project setting -> Player -> other setting -> ".Net 2.0" 으로 설정 후 reimport
using System.IO.Ports;
using System.Net.Sockets;
using System.Media;
using System.Threading;
namespace Assets.Keyboards
{
public class KeyboardBasic : MonoBehaviour
{
Vector2 tempGpos;
public float gxScale = 2, gyScale = 2, gxOffset = 0, gyOffset = 0;
public bool isCalibUse = false;
const int calibPoint = 9;
Matrix4x4 T1, T2, T3, T4;
Vector2[] gazeRef;
Vector2[] markerPos;
//Marker
public GameObject[] markers;
public string[] markerLayout;
public float markerWidth;
public float markerHeight;
public float markerGap;
//Marker
public AudioSource audio;
public AudioClip click;
public int startTrial = 0, startBlock = 0;
public int participant = 0;
public AverageFilter filterX, filterY;
public FoveInterfaceBase foveInterface;
private Collider my_collider;
public const int SWIPE_BOTTOM_LEFT = 1;
public const int SWIPE_LEFT = 2;
public const int SWIPE_TOP_LEFT = 3;
public const int SWIPE_TOP = 4;
public const int SWIPE_BOTTOM = 8;
public const int SWIPE_BOTTOM_RIGHT = 7;
public const int SWIPE_RIGHT = 6;
public const int SWIPE_TOP_RIGHT = 5;
public const int GESTURE_CIRCLE = 9;
public const int TOUCH_UP = 10;
public const int TOUCH_UP_GESTURE = 13;
public const int TOUCH_MOVE = 11;
public const int TOUCH_DOWN = 12;
float interRecordingInterval = 0.05f;
float memorizeInterval = 15;
float interTaskInterval = 5;//30
float interBlockInterval = 10;//60
bool isEyeClosed = false;
public GazeTouchEvent gtEvent;
public bool enableTyping;
public bool isWindowActivated = false;
public int activatedWindow = -1;
public bool isRecording = false;
public bool isKeyDown = false;
public bool gazeMovable = true;
protected Text exampleBox, inputBox, resultBox;
protected string inputed = "";
public ExperimentManager experimentManager;
public string whichKeyboard = "";
GameObject DC;
public bool malInputCheck = false;
GameObject[] eyeCursors;
MeshFilter[] eyeCursorMeshes;
public MeshFilter integratedEyeCursor;
public Vector3[] eyeCursorsLocalPositionOnKeyboard;
public Vector3 integratedEyeCursorPosition;
public float[] integratedEyeCursor_yPoses;
public int wtx, wty; //watch touch x,y
private SerialPort watchConnector;
string watchPacket;
public bool isDynamicCascading = false;
public float gRatioX, gRatioY;
public int adjusterX = 11;
// Use this for initialization
void Start()
{
}
protected void initExperiment()
{
tempGpos = new Vector2();
gRatioX = 1;
gRatioY = 1;
if (isDynamicCascading)
{
DC = GameObject.Find("Eye_only");
}
filterX = new AverageFilter();
filterY = new AverageFilter();
audio = gameObject.GetComponentInChildren<AudioSource>();
eyeCursorsLocalPositionOnKeyboard = new Vector3[2];
eyeCursors = new GameObject[2];
eyeCursors= GameObject.FindGameObjectsWithTag("eyecursor");
eyeCursorMeshes = new MeshFilter[2];
eyeCursorMeshes[0] = eyeCursors[0].GetComponent<MeshFilter>();
eyeCursorMeshes[1] = eyeCursors[1].GetComponent<MeshFilter>();
integratedEyeCursor = gameObject.GetComponentsInChildren<MeshFilter>()[1];
integratedEyeCursorPosition = integratedEyeCursor.transform.localPosition;
my_collider = GetComponent<Collider>();
// 파일 열려있으면 죽음
experimentManager = new ExperimentManager(participant, startTrial, startBlock, ExperimentManager.maxBlockDefault, ExperimentManager.maxTrialDefault, whichKeyboard);
Text[] temp = gameObject.GetComponentsInChildren<Text>();
foreach (Text t in temp)
{
if (t.tag.CompareTo("example") == 0)
{
exampleBox = t;
}
else if (t.tag.CompareTo("inputed") == 0)
{
inputBox = t;
}
else if (t.tag.CompareTo("resultView") == 0)
{
resultBox = t;
}
}
exampleBox.text = experimentManager.getPhrase();
exampleBox.color = Color.green;
inputBox.text = "_";
resultBox.text = "-";
enableTyping = true;
gazeMovable = true;
hideEyeCursors();
StartCoroutine("recordGazeCursor");
}
public void hideEyeCursors()
{
eyeCursors[0].GetComponentInChildren<MeshFilter>().GetComponent<MeshRenderer>().material.color = Color.clear;
eyeCursors[1].GetComponentInChildren<MeshFilter>().GetComponent<MeshRenderer>().material.color = Color.clear;
}
public void keyActivatedRecording(char k)
{
gtEvent.eventTime = TimeUtils.currentTimeMillis();
gtEvent.eventLabel = 'w';
gtEvent.selected = k;
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
}
public void keyDeactivatedRecording(char k)
{
gtEvent.eventTime = TimeUtils.currentTimeMillis();
gtEvent.eventLabel = 'w';
gtEvent.selected = (char)(k-32); //upper
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
}
public void keyEntered(char k)
{
if (enableTyping && !malInputCheck)
{
malInputCheck = true;
StartCoroutine("malInputChecker");
gtEvent.eventTime = TimeUtils.currentTimeMillis();
gtEvent.eventLabel = '?';
if (k >= Key.A && k <= Key.Z)
{
gtEvent.eventLabel = 'k';
audio.Play();
experimentManager.updateInput(k, inputed);
gtEvent.selected = k;
inputed += k;
inputBox.text = inputed + "_";
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
gazeMovable = true;
}
else
{
switch (k)
{
case Key.backspace:
gtEvent.eventLabel = 'k';
audio.Play();
experimentManager.updateInput(k, inputed);
gtEvent.selected = k;
int inputNum = inputed.Length;
if (inputNum > 0)
{
inputed = inputed.Substring(0, inputNum - 1);
}
inputBox.text = inputed + "_";
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
gazeMovable = true;
break;
case Key.space:
gtEvent.eventLabel = 'k';
audio.Play();
experimentManager.updateInput(k, inputed);
gtEvent.selected = k;
inputed += " ";
inputBox.text = inputed + "_";
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
gazeMovable = true;
break;
case Key.Enter:
enableTyping = false;
gazeMovable = false;
gtEvent.eventLabel = 'x';
gtEvent.selected = '~';
doneTask();
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
exampleBox.text = "(RECORDING RESULTS...)";
audio.Play();
exampleBox.color = Color.red;
gazeMovable = true;
StartCoroutine("delayForRecording");
break;
case Key.Plus:
gtEvent.eventLabel = 'd';
gtEvent.selected = k;
gtEvent.state = getDwellTime();
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
audio.Play();
gazeMovable = true;
Dynamic_cascade.baseDwell_int = adjustDwell(true);
if (Dynamic_cascade.baseDwell_int >= Dynamic_cascade.maxDwell)
{
Dynamic_cascade.baseDwell_int = Dynamic_cascade.maxDwell;
}
DC.GetComponent<Dynamic_cascade>().updateDwell();
break;
case Key.Minus:
gtEvent.eventLabel = 'd';
gtEvent.selected = k;
gtEvent.state = getDwellTime();
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
audio.Play();
gazeMovable = true;
Dynamic_cascade.baseDwell_int = adjustDwell(false);
if (Dynamic_cascade.baseDwell_int <= Dynamic_cascade.minDwell)
{
Dynamic_cascade.baseDwell_int = Dynamic_cascade.minDwell;
}
DC.GetComponent<Dynamic_cascade>().updateDwell();
break;
case Key.Start:
audio.Play();
gtEvent.eventLabel = 's';
gtEvent.selected = k;
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
DC.GetComponent<Dynamic_cascade>().adjustDwellPhaseDone();
gazeMovable = true;
StartCoroutine("delayInterTask");
break;
default:
gtEvent.eventLabel = 'w';
switch (k)
{
case Key.D1:
case Key.D2:
case Key.D3:
case Key.D4:
case Key.D5:
case Key.D6:
case Key.D7:
case Key.D8:
case Key.D9:
gtEvent.selected = k;
activatedWindow = gtEvent.selected - '1';
isWindowActivated = true;
break;
case Key.F1:
case Key.F2:
case Key.F3:
case Key.F4:
case Key.F5:
case Key.F6:
case Key.F7:
case Key.F8:
case Key.F9:
gtEvent.selected = k;
isWindowActivated = false;
activatedWindow = -1;
break;
default:
gtEvent.eventLabel = '?';
break;
}
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
gazeMovable = true;
break;
}
}
}
//setWordOntheKeyboard(); //for GAT
}
public IEnumerator malInputChecker()
{
yield return new WaitForSecondsRealtime(0.05f);
malInputCheck = false;
}
public int adjustDwell(bool isPlus)
{
if (isPlus)
{
adjusterX++;
if (adjusterX > 24) adjusterX = 24;
}
else
{
adjusterX--;
if (adjusterX <0) adjusterX = 0;
}
return getDwellTime();
}
public int getDwellTime()
{
return (int)((Mathf.Exp((float)adjusterX / 12) * 300 - 150));
}
// Update is called once per frame
void Update()
{
}
protected void updateGazeCursor()
{
if (foveInterface.Gazecast(my_collider))
{
//foveInterface.
eyeCursorsLocalPositionOnKeyboard[0] = transform.InverseTransformPoint(eyeCursorMeshes[0].transform.position);
eyeCursorsLocalPositionOnKeyboard[1] = transform.InverseTransformPoint(eyeCursorMeshes[1].transform.position);
tempGpos.x = filterX.updateData((eyeCursorsLocalPositionOnKeyboard[0].x + eyeCursorsLocalPositionOnKeyboard[1].x) / gxScale + gxOffset);
tempGpos.y = filterY.updateData((eyeCursorsLocalPositionOnKeyboard[0].y + eyeCursorsLocalPositionOnKeyboard[1].y) / gyScale + gyOffset);
if (isCalibUse)
{
tempGpos = getCalibratedPos(tempGpos);
}
gtEvent.xGazePos = tempGpos.x;
gtEvent.yGazePos = tempGpos.y;
}
//gtEvent.eyeOpen = (int)FoveInterface.CheckEyesClosed();
}
public void doneTask()
{
/*
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].inputTouch(TOUCH_UP_GESTURE, 0, 0);
}*/
experimentManager.taskDone(inputed);
resultBox.text = experimentManager.getResultInString();
//resultBox.text = result;
inputed = "";
inputBox.text = inputed + "_";
}
void UI_update()
{
gazeMovable = false;
int block = experimentManager.getBlock();
int trial = experimentManager.getTrial();
if (trial == 1)
{
if (block > experimentManager.maxBlock)
{
exampleBox.text = "Experiment is done! Thanks!";
exampleBox.color = Color.green;
}
else
{
exampleBox.text = "READY for next Block: block " + experimentManager.getBlock() + " / " + experimentManager.maxBlock;
exampleBox.color = Color.green;
}
}
else
{
exampleBox.text = "(READY) Next: Block " + experimentManager.getBlock() + " - Trial: " + experimentManager.getTrial() + " / " + experimentManager.maxTrial;
exampleBox.color = Color.yellow;
}
}
private IEnumerator delayInterTask()
{
experimentManager.provideNext();
UI_update();
bool inInterval = true;
while (inInterval)
{
yield return new WaitForSecondsRealtime(interTaskInterval);
inInterval = false;
experimentManager.setEnableLogging();
audio.Play();
exampleBox.text = experimentManager.getPhrase();
exampleBox.color = Color.green;
inputBox.text = "Please MEMORIZE the phrase...";
StartCoroutine("delayForMemorize");
gazeMovable = true;
}
}
private IEnumerator delayForRecording()
{
bool inInterval = true;
experimentManager.recordResults();
while (inInterval)
{
yield return new WaitForSecondsRealtime(interRecordingInterval);
inInterval = false;
if (!isDynamicCascading)
{
StartCoroutine("delayInterTask");
}
else
{
if (experimentManager.getBlock() > 0)
{
DC.GetComponent<Dynamic_cascade>().adjustDwellPhaseStart();
}
else
{
gtEvent.eventLabel = 's';
gtEvent.selected = Key.Start;
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
DC.GetComponent<Dynamic_cascade>().adjustDwellPhaseDone();
StartCoroutine("delayInterTask");
}
}
}
}
private IEnumerator delayForMemorize()
{
bool inInterval = true;
while (inInterval)
{
yield return new WaitForSecondsRealtime(memorizeInterval);
inInterval = false;
enableTyping = true;
audio.Play();
exampleBox.color = Color.black;
inputBox.text = "_";
}
}
virtual public char keyInputed(char raw) { return (char)0; }
virtual public char keyDown(char raw) { return (char)0; }
public void checkRawKeyInput()
{
char rawKey = (char)0;
if (isKeyDown)
{
rawKey = (char)0;
if (Input.GetKeyUp(KeyCode.Keypad7))
{
rawKey = 'Q';
}
else if (Input.GetKeyUp(KeyCode.Keypad8))
{
rawKey = 'W';
}
else if (Input.GetKeyUp(KeyCode.Keypad9))
{
rawKey = 'E';
}
else if (Input.GetKeyUp(KeyCode.Keypad4))
{
rawKey = 'A';
}
else if (Input.GetKeyUp(KeyCode.Keypad5))
{
rawKey = 'S';
}
else if (Input.GetKeyUp(KeyCode.Keypad6))
{
rawKey = 'D';
}
else if (Input.GetKeyUp(KeyCode.Keypad1))
{
rawKey = 'Z';
}
else if (Input.GetKeyUp(KeyCode.Keypad2))
{
rawKey = 'X';
}
else if (Input.GetKeyUp(KeyCode.Keypad3))
{
rawKey = 'C';
}
if (rawKey > (char)0)
{
keyEntered(keyInputed(rawKey));
}
else if (Input.GetKeyUp(KeyCode.Return))
{
rawKey = Key.Enter;
keyEntered(rawKey);
}
}
else
{
if (Input.GetKeyDown(KeyCode.Keypad7))
{
rawKey = 'Q';
}
else if (Input.GetKeyDown(KeyCode.Keypad8))
{
rawKey = 'W';
}
else if (Input.GetKeyDown(KeyCode.Keypad9))
{
rawKey = 'E';
}
else if (Input.GetKeyDown(KeyCode.Keypad4))
{
rawKey = 'A';
}
else if (Input.GetKeyDown(KeyCode.Keypad5))
{
rawKey = 'S';
}
else if (Input.GetKeyDown(KeyCode.Keypad6))
{
rawKey = 'D';
}
else if (Input.GetKeyDown(KeyCode.Keypad1))
{
rawKey = 'Z';
}
else if (Input.GetKeyDown(KeyCode.Keypad2))
{
rawKey = 'X';
}
else if (Input.GetKeyDown(KeyCode.Keypad3))
{
rawKey = 'C';
}
else if (Input.GetKeyDown(KeyCode.Return))
{
rawKey = Key.Enter;
}
if (rawKey > (char)0)
{
keyDown(rawKey);
}
}
}
private void OnApplicationQuit()
{
serialPortClose();
}
void serialPortClose()
{
if(watchConnector != null)
{
if (watchConnector.IsOpen) watchConnector.Close();
}
}
public void initTouchPad()
{
watchConnector = new SerialPort("\\\\.\\COM13", 115200);//google glass, in unity, port# over 9 should follow this format
watchConnector.ReadTimeout = 1;
watchConnector.Open();
print("Touch connecting: " + watchConnector.IsOpen);
StartCoroutine("watchProcessing");
}
IEnumerator watchProcessing()
{
while (watchConnector.IsOpen)
{
yield return new WaitForSecondsRealtime(0.02f); //10ms interval
watchInputCheck();
}
}
public void watchInputCheck()
{
try
{
watchPacket = watchConnector.ReadLine();
}
catch (System.TimeoutException e)
{
//print("timeout @ read BT");
}
if (enableTyping)
{
try
{
if (watchPacket != null)
{
string[] temp = watchPacket.Split(' ');
if (temp[0] == "d")
{
gazeMovable = true;
}
else
{
interpretPacket(temp);
}
}
}
catch (System.NullReferenceException e) { }
}
}
virtual public void interpretPacket(string[] splitedPacket) { }
IEnumerator recordGazeCursor()
{
while (true)
{
gtEvent.eventTime = TimeUtils.currentTimeMillis();
gtEvent.eventLabel = 'g';
experimentManager.appendGazeTouchEvent(gtEvent);
yield return new WaitForSecondsRealtime(0.03f);
}
}
virtual public void setWordOntheKeyboard(int where, bool mustUpdate) { }
public void initCalib()
{
gazeRef = new Vector2[calibPoint];
markerPos = new Vector2[calibPoint];
markerLayout = new string[calibPoint];
markerLayout[0] = "●";
markers = GameObject.FindGameObjectsWithTag("marker");
Vector3 basicPosition = markers[0].transform.localPosition;
markerWidth = markers[0].transform.localScale.x;
markerHeight = markers[0].transform.localScale.y;
Text text;
foreach (GameObject g in markers)
{
g.GetComponentInChildren<Text>().text = "●";
}
markers[0].GetComponent<Calib_marker>().key = 'q';
Vector3 keyPosition = new Vector3(basicPosition.x, basicPosition.y, basicPosition.z);
markers[0].transform.localPosition = keyPosition;
markers[1].GetComponent<Calib_marker>().key = 'w';
keyPosition = new Vector3(basicPosition.x + 0.055f * 4.5f, basicPosition.y, basicPosition.z);
markers[1].transform.localPosition = keyPosition;
markers[2].GetComponent<Calib_marker>().key = 'e';
keyPosition = new Vector3(basicPosition.x + 0.055f * 9, basicPosition.y, basicPosition.z);
markers[2].transform.localPosition = keyPosition;
markers[3].GetComponent<Calib_marker>().key = 'a';
keyPosition = new Vector3(basicPosition.x, basicPosition.y - 0.07f * 2, basicPosition.z);
markers[3].transform.localPosition = keyPosition;
markers[4].GetComponent<Calib_marker>().key = 's';
keyPosition = new Vector3(basicPosition.x + 0.055f * 4.5f, basicPosition.y - 0.07f * 2, basicPosition.z);
markers[4].transform.localPosition = keyPosition;
markers[5].GetComponent<Calib_marker>().key = 'd';
keyPosition = new Vector3(basicPosition.x + 0.055f * 9, basicPosition.y - 0.07f * 2, basicPosition.z);
markers[5].transform.localPosition = keyPosition;
markers[6].GetComponent<Calib_marker>().key = 'z';
keyPosition = new Vector3(basicPosition.x, basicPosition.y - 0.07f * 4, basicPosition.z);
markers[6].transform.localPosition = keyPosition;
markers[7].GetComponent<Calib_marker>().key = 'x';
keyPosition = new Vector3(basicPosition.x + 0.055f * 4.5f, basicPosition.y - 0.07f * 4, basicPosition.z);
markers[7].transform.localPosition = keyPosition;
markers[8].GetComponent<Calib_marker>().key = 'c';
keyPosition = new Vector3(basicPosition.x + 0.055f * 9, basicPosition.y - 0.07f * 4, basicPosition.z);
markers[8].transform.localPosition = keyPosition;
int i = 0;
foreach (GameObject g in markers)
{
//should match input plane transform
gazeRef[i] = new Vector2();
markerPos[i] = transform.InverseTransformPoint(g.transform.position);
i++;
}
}
public void getPositionAt(int which)
{
audio.Play();
gazeRef[which].x = gtEvent.xGazePos;
gazeRef[which].y = gtEvent.yGazePos;
markers[which].GetComponent<Calib_marker>().set("O");
}
public void calculateMat()
{
audio.Play();
T1 = calcurateTransformMatrixAt(0, 1, 3, 4);
T2 = calcurateTransformMatrixAt(1, 2, 4, 5);
T3 = calcurateTransformMatrixAt(3, 4, 6, 7);
T4 = calcurateTransformMatrixAt(4, 5, 7, 8);
foreach (GameObject g in markers)
{
g.GetComponent<Calib_marker>().set("O");
}
audio.Play();
}
public Matrix4x4 calcurateTransformMatrixAt(int refTL, int refTR, int refBL, int refBR)
{
Matrix4x4 mat, screenMat, pupilMat;
mat = new Matrix4x4();
screenMat = new Matrix4x4();
pupilMat = new Matrix4x4();
screenMat.m00 = markerPos[refTL].x;
screenMat.m01 = markerPos[refTR].x;
screenMat.m02 = markerPos[refBL].x;
screenMat.m03 = markerPos[refBR].x;
screenMat.m10 = markerPos[refTL].y;
screenMat.m11 = markerPos[refTR].y;
screenMat.m12 = markerPos[refBL].y;
screenMat.m13 = markerPos[refBR].y;
screenMat.m20 = 0;
screenMat.m21 = 0;
screenMat.m22 = 0;
screenMat.m23 = 0;
screenMat.m30 = 0;
screenMat.m31 = 0;
screenMat.m32 = 0;
screenMat.m33 = 0;
pupilMat.m00 = gazeRef[refTL].x;
pupilMat.m01 = gazeRef[refTR].x;
pupilMat.m02 = gazeRef[refBL].x;
pupilMat.m03 = gazeRef[refBR].x;
pupilMat.m10 = gazeRef[refTL].y;
pupilMat.m11 = gazeRef[refTR].y;
pupilMat.m12 = gazeRef[refBL].y;
pupilMat.m13 = gazeRef[refBR].y;
pupilMat.m20 = gazeRef[refTL].x * gazeRef[refTL].y;
pupilMat.m21 = gazeRef[refTR].x * gazeRef[refTR].y;
pupilMat.m22 = gazeRef[refBL].x * gazeRef[refBL].y;
pupilMat.m23 = gazeRef[refBR].x * gazeRef[refBR].y;
pupilMat.m30 = 1;
pupilMat.m31 = 1;
pupilMat.m32 = 1;
pupilMat.m33 = 1;
/*
screenMat.m00 = markerPos[refTL].x;
screenMat.m10 = markerPos[refTR].x;
screenMat.m20 = markerPos[refBL].x;
screenMat.m30 = markerPos[refBR].x;
screenMat.m01 = markerPos[refTL].y;
screenMat.m11 = markerPos[refTR].y;
screenMat.m21 = markerPos[refBL].y;
screenMat.m31 = markerPos[refBR].y;
screenMat.m02 = 0;
screenMat.m12 = 0;
screenMat.m22 = 0;
screenMat.m32 = 0;
screenMat.m03 = 0;
screenMat.m13 = 0;
screenMat.m23 = 0;
screenMat.m33 = 0;
pupilMat.m00 = gazeRef[refTL].x;
pupilMat.m10 = gazeRef[refTR].x;
pupilMat.m20 = gazeRef[refBL].x;
pupilMat.m30 = gazeRef[refBR].x;
pupilMat.m01 = gazeRef[refTL].y;
pupilMat.m11 = gazeRef[refTR].y;
pupilMat.m21 = gazeRef[refBL].y;
pupilMat.m31 = gazeRef[refBR].y;
pupilMat.m02 = gazeRef[refTL].x * gazeRef[refTL].y;
pupilMat.m12 = gazeRef[refTR].x * gazeRef[refTR].y;
pupilMat.m22 = gazeRef[refBL].x * gazeRef[refBL].y;
pupilMat.m32 = gazeRef[refBR].x * gazeRef[refBR].y;
pupilMat.m03 = 1;
pupilMat.m13 = 1;
pupilMat.m23 = 1;
pupilMat.m33 = 1;*/
return screenMat * pupilMat.inverse;
}
virtual public void calibReady() { }
virtual public void calibDone() { }
public void calibReadyKeyInput()
{
if (Input.GetKeyUp(KeyCode.O))
{
calibReady();
}
if (Input.GetKeyUp(KeyCode.Q))
{
getPositionAt(0);
}
if (Input.GetKeyUp(KeyCode.W))
{
getPositionAt(1);
}
if (Input.GetKeyUp(KeyCode.E))
{
getPositionAt(2);
}
if (Input.GetKeyUp(KeyCode.A))
{
getPositionAt(3);
}
if (Input.GetKeyUp(KeyCode.S))
{
getPositionAt(4);
}
if (Input.GetKeyUp(KeyCode.D))
{
getPositionAt(5);
}
if (Input.GetKeyUp(KeyCode.Z))
{
getPositionAt(6);
}
if (Input.GetKeyUp(KeyCode.X))
{
getPositionAt(7);
}
if (Input.GetKeyUp(KeyCode.C))
{
getPositionAt(8);
}
if (Input.GetKeyUp(KeyCode.P))
{
calculateMat();
calibDone();
}
if (Input.GetKeyUp(KeyCode.M))
{
isCalibUse = !isCalibUse;
}
if (Input.GetKeyUp(KeyCode.R))
{
audio.Play();
gtEvent.eventLabel = 's';
gtEvent.selected = 's';
experimentManager.appendGazeTouchEvent(gtEvent);
gtEvent.selected = (char)0;
DC.GetComponent<Dynamic_cascade>().adjustDwellPhaseDone();
gazeMovable = true;
StartCoroutine("delayInterTask");
}
}
public Vector2 getCalibratedPos(Vector2 raw)
{
int idx = getNearestCorner(raw);
return getPositionAtRegion(idx, raw);
}
private Vector2 getPositionAtRegion(int region, Vector2 raw)
{
Matrix4x4 pupilMat = new Matrix4x4();
pupilMat.m00 = raw.x;
pupilMat.m10 = raw.y;
pupilMat.m20 = raw.x * raw.y;
pupilMat.m30 = 1;
Matrix4x4 mat;
//1st order polynomial
switch (region)
{
case 1:
mat = T1 * pupilMat;
break;
case 2:
mat = T2 * pupilMat;
break;
case 3:
mat = T3 * pupilMat;
break;
case 4:
mat = T4 * pupilMat;
break;
default:
mat = new Matrix4x4();
break;
}
Vector2 rawPoint = new Vector2();
rawPoint.x = mat.m00;
rawPoint.y = mat.m10;
/*
Matrix rawPointMat = new Matrix(4,1);
rawPointMat.setValueAt(0,0,rawPoint.x);
rawPointMat.setValueAt(1,0,rawPoint.y);
rawPointMat.setValueAt(2,0,rawPoint.x * rawPoint.y);
rawPointMat.setValueAt(3,0,1);
//mat = MatrixMathematics.multiply(postT, rawPointMat);
rawPoint = new Vector2((float)mat.getValueAt(0,0), (float)mat.getValueAt(1,0));
*/
return rawPoint;
}
public int getNearestCorner(Vector2 raw)
{
float minDist = float.MaxValue;
float tempDist;
float tempX, tempY;
int id = -1;
tempX = raw.x - gazeRef[0].x;
tempY = raw.y - gazeRef[0].y;
tempDist = tempX * tempX + tempY * tempY;
if (minDist > tempDist)
{
minDist = tempDist;
id = 1;
}
tempX = raw.x - gazeRef[2].x;
tempY = raw.y - gazeRef[2].y;
tempDist = tempX * tempX + tempY * tempY;
if (minDist > tempDist)
{
minDist = tempDist;
id = 2;
}
tempX = raw.x - gazeRef[6].x;
tempY = raw.y - gazeRef[6].y;
tempDist = tempX * tempX + tempY * tempY;
if (minDist > tempDist)
{
minDist = tempDist;
id = 3;
}
tempX = raw.x - gazeRef[8].x;
tempY = raw.y - gazeRef[8].y;
tempDist = tempX * tempX + tempY * tempY;
if (minDist > tempDist)
{
minDist = tempDist;
id = 4;
}
return id;
}
}
} | 35.161951 | 176 | 0.462057 | [
"MIT"
] | suggestbot-wearable-text-entry-system/SuggestBot_GazeAssistedTyping | Assets/Keyboards/KeyboardBasic.cs | 36,075 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
using System;
using System.Windows.Markup;
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e26dd271-436d-483d-91e2-de61b3ffe0af")]
[assembly: AssemblyTitle("System.Windows.Controls")]
[assembly: AssemblyDescription("FloatableWindow Silverlight Control")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tim Heuer")]
[assembly: AssemblyProduct("FloatableWindow")]
[assembly: AssemblyCopyright("Licensed under Ms-PL")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.0.5.0")]
[assembly: AssemblyFileVersion("3.0.40624.4")]
[assembly: CLSCompliant(true)]
[assembly: XmlnsPrefix("clr-namespace:System.Windows.Controls;assembly=FloatableWindow", "windows")]
[assembly: XmlnsDefinitionAttribute("clr-namespace:System.Windows.Controls;assembly=FloatableWindow", "System.Windows.Controls")] | 47.041667 | 129 | 0.777679 | [
"Apache-2.0"
] | vasnake/cartobonus | maps.web.builder/FloatableWindow/Properties/AssemblyInfo.cs | 1,131 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KeyManagementService.Model
{
/// <summary>
/// Container for the parameters to the ConnectCustomKeyStore operation.
/// Connects or reconnects a <a href="https://docs.aws.amazon.com/kms/latest/developerguide/custom-key-store-overview.html">custom
/// key store</a> to its associated AWS CloudHSM cluster.
///
///
/// <para>
/// The custom key store must be connected before you can create customer master keys
/// (CMKs) in the key store or use the CMKs it contains. You can disconnect and reconnect
/// a custom key store at any time.
/// </para>
///
/// <para>
/// To connect a custom key store, its associated AWS CloudHSM cluster must have at least
/// one active HSM. To get the number of active HSMs in a cluster, use the <a href="https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeClusters.html">DescribeClusters</a>
/// operation. To add HSMs to the cluster, use the <a href="https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CreateHsm.html">CreateHsm</a>
/// operation. Also, the <a href="https://docs.aws.amazon.com/kms/latest/developerguide/key-store-concepts.html#concept-kmsuser">
/// <code>kmsuser</code> crypto user</a> (CU) must not be logged into the cluster. This
/// prevents AWS KMS from using this account to log in.
/// </para>
///
/// <para>
/// The connection process can take an extended amount of time to complete; up to 20 minutes.
/// This operation starts the connection process, but it does not wait for it to complete.
/// When it succeeds, this operation quickly returns an HTTP 200 response and a JSON object
/// with no properties. However, this response does not indicate that the custom key store
/// is connected. To get the connection state of the custom key store, use the <a>DescribeCustomKeyStores</a>
/// operation.
/// </para>
///
/// <para>
/// During the connection process, AWS KMS finds the AWS CloudHSM cluster that is associated
/// with the custom key store, creates the connection infrastructure, connects to the
/// cluster, logs into the AWS CloudHSM client as the <code>kmsuser</code> CU, and rotates
/// its password.
/// </para>
///
/// <para>
/// The <code>ConnectCustomKeyStore</code> operation might fail for various reasons. To
/// find the reason, use the <a>DescribeCustomKeyStores</a> operation and see the <code>ConnectionErrorCode</code>
/// in the response. For help interpreting the <code>ConnectionErrorCode</code>, see <a>CustomKeyStoresListEntry</a>.
/// </para>
///
/// <para>
/// To fix the failure, use the <a>DisconnectCustomKeyStore</a> operation to disconnect
/// the custom key store, correct the error, use the <a>UpdateCustomKeyStore</a> operation
/// if necessary, and then use <code>ConnectCustomKeyStore</code> again.
/// </para>
///
/// <para>
/// If you are having trouble connecting or disconnecting a custom key store, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html">Troubleshooting
/// a Custom Key Store</a> in the <i>AWS Key Management Service Developer Guide</i>.
/// </para>
/// </summary>
public partial class ConnectCustomKeyStoreRequest : AmazonKeyManagementServiceRequest
{
private string _customKeyStoreId;
/// <summary>
/// Gets and sets the property CustomKeyStoreId.
/// <para>
/// Enter the key store ID of the custom key store that you want to connect. To find the
/// ID of a custom key store, use the <a>DescribeCustomKeyStores</a> operation.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string CustomKeyStoreId
{
get { return this._customKeyStoreId; }
set { this._customKeyStoreId = value; }
}
// Check to see if CustomKeyStoreId property is set
internal bool IsSetCustomKeyStoreId()
{
return this._customKeyStoreId != null;
}
}
} | 45.9 | 192 | 0.67855 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/KeyManagementService/Generated/Model/ConnectCustomKeyStoreRequest.cs | 5,049 | C# |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LightBlue.MultiHost.IISExpress
{
static class IisExpressHelper
{
public static void KillIisExpressProcesses()
{
foreach (var p in Process.GetProcessesByName("iisexpress"))
{
p.Kill();
}
}
public static ProcessStartInfo BuildProcessStartInfo(WebHostArgs webHostArgs, string configurationFilePath)
{
string path = webHostArgs.Use64Bit
? Path.Combine(Environment.GetEnvironmentVariable("ProgramW6432"), @"IIS Express\iisexpress.exe")
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"IIS Express\iisexpress.exe");
var processStartInfo = new ProcessStartInfo
{
FileName = path,
Arguments = string.Format(
CultureInfo.InvariantCulture,
"/config:\"{0}\" /site:LightBlue",
configurationFilePath),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
processStartInfo.EnvironmentVariables.Add("LightBlueHost", "true");
processStartInfo.EnvironmentVariables.Add("LightBlueConfigurationPath", webHostArgs.ConfigurationPath);
processStartInfo.EnvironmentVariables.Add("LightBlueRoleName", webHostArgs.RoleName);
processStartInfo.EnvironmentVariables.Add("LightBlueUseHostedStorage", webHostArgs.UseHostedStorage.ToString());
var processId = webHostArgs.RoleName
+ "-web-"
+ Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
var temporaryDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LightBlue",
"temp",
processId);
Directory.CreateDirectory(temporaryDirectory);
processStartInfo.EnvironmentVariables["TMP"] = temporaryDirectory;
processStartInfo.EnvironmentVariables["TEMP"] = temporaryDirectory;
return processStartInfo;
}
public static void GenerateIisExpressConfigurationFile(WebHostArgs webHostArgs, string configurationFilePath)
{
var template = ObtainIisExpressConfigurationTemplate(webHostArgs);
template = template.Replace("__SITEPATH__", webHostArgs.SiteDirectory);
template = template.Replace("__PROTOCOL__", webHostArgs.UseSsl ? "https" : "http");
template = template.Replace("__PORT__", webHostArgs.Port.ToString(CultureInfo.InvariantCulture));
template = template.Replace("__HOSTNAME__", webHostArgs.Hostname);
File.WriteAllText(configurationFilePath, template);
}
private static string ObtainIisExpressConfigurationTemplate(WebHostArgs webHostArgs)
{
if (!string.IsNullOrWhiteSpace(webHostArgs.IisExpressTemplate))
{
return File.ReadAllText(webHostArgs.IisExpressTemplate);
}
var executingAssembly = Assembly.GetExecutingAssembly();
var manifestResourceStream = executingAssembly.GetManifestResourceStream("LightBlue.MultiHost.IISExpress.Configuration.template");
if (manifestResourceStream == null)
{
throw new InvalidOperationException("Unable to retrieve IIS Express configuration template.");
}
var template = new StreamReader(manifestResourceStream).ReadToEnd();
return template;
}
}
}
| 42.494505 | 142 | 0.641065 | [
"Apache-2.0"
] | ColinScott/LightBlue | LightBlue.MultiHost/IISExpress/IisExpressHelper.cs | 3,869 | C# |
using PoESkillTree.Engine.Computation.Common.Builders.Values;
using PoESkillTree.Engine.Utils;
namespace PoESkillTree.Engine.Computation.Common.Builders.Resolving
{
/// <summary>
/// Interface for objects that can be resolved using a <see cref="ResolveContext"/>.
/// </summary>
/// <typeparam name="T">The resulting type of resolving. Generally this is the type that is implementing this
/// interface.</typeparam>
public interface IResolvable<out T> where T : class
{
/// <summary>
/// Resolves this instance using the given match context.
/// </summary>
T Resolve(ResolveContext context);
}
/// <summary>
/// Class holding the context instances required for <see cref="IResolvable{T}.Resolve"/>.
/// </summary>
public class ResolveContext : ValueObject
{
public ResolveContext(
IMatchContext<IValueBuilder> valueContext, IMatchContext<IReferenceConverter> referenceContext)
{
ValueContext = valueContext;
ReferenceContext = referenceContext;
}
/// <summary>
/// Gets the context holding the resolved values.
/// </summary>
public IMatchContext<IValueBuilder> ValueContext { get; }
/// <summary>
/// Gets the context holding the resolved references.
/// </summary>
public IMatchContext<IReferenceConverter> ReferenceContext { get; }
protected override object ToTuple() => (ValueContext, ReferenceContext);
}
} | 35.744186 | 113 | 0.651919 | [
"MIT"
] | BlazesRus/PoESkillTreeBlazesRusBranch.Engine | PoESkillTree.Engine.Computation.Common/Builders/Resolving/IResolvable.cs | 1,539 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace cloudscribe.Core.IdentityServer.EFCore
{
public class EfConstants
{
public class TableNames
{
//public const string Scope = "csids_Scopes";
//public const string ScopeClaim = "csids_ScopeClaims";
//public const string ScopeSecrets = "csids_ScopeSecrets";
public const string IdentityResource = "csids_IdentityResources";
public const string IdentityClaim = "csids_IdentityClaims";
public const string ApiResource = "csids_ApiResources";
public const string ApiSecret = "csids_ApiSecrets";
public const string ApiClaim = "csids_ApiClaims";
public const string ApiScope = "csids_ApiScopes";
public const string ApiScopeClaim = "csids_ApiScopeClaims";
public const string PersistedGrant = "csids_PersistedGrants";
public const string Client = "csids_Clients";
public const string ClientGrantType = "csids_ClientGrantTypes";
public const string ClientRedirectUri = "csids_ClientRedirectUris";
public const string ClientPostLogoutRedirectUri = "csids_ClientPostLogoutRedirectUris";
public const string ClientScopes = "csids_ClientScopes";
public const string ClientSecret = "csids_ClientSecrets";
public const string ClientProps = "csids_ClientProps";
public const string ClientClaim = "csids_ClientClaims";
public const string ClientIdPRestriction = "csids_ClientIdPRestrictions";
public const string ClientCorsOrigin = "csids_ClientCorsOrigins";
}
}
} | 49.72973 | 107 | 0.682065 | [
"Apache-2.0"
] | 4L4M1N/cloudscribe | src/cloudscribe.Core.IdentityServer.EFCore.Common/EfConstants.cs | 1,842 | C# |
using IntegrationController.Model;
using System;
using System.IO;
namespace IntegrationController.Interface
{
public interface IFileIntegration : IFileValidator
{
FileIntegrationType FileIntegrationType { get; }
DateTime AsOfDate { get; }
FileInfo File { get; }
}
}
| 17.4375 | 51 | 0.767025 | [
"MIT"
] | iAvinashVarma/Runner | Reflector/IntegrationController/Interface/IFileIntegration.cs | 281 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentAssertions;
using FluentAssertions.Extensions;
using NUnit.Framework;
using Vostok.Commons.Testing.Observable;
using Vostok.Configuration.Abstractions.SettingsTree;
using Vostok.Configuration.Sources.Object;
namespace Vostok.Configuration.Sources.Tests
{
[TestFixture]
internal class ObjectSource_Tests
{
[Test]
public void Should_return_null_settings_node_for_null_object()
{
Observe(null).Should().BeNull();
}
[Test]
public void Should_return_empty_object_node_for_empty_object()
{
Observe(new object()).Should().Be(new ObjectNode(Array.Empty<ISettingsNode>()));
}
[Test]
public void Should_return_empty_array_node_for_empty_sequence()
{
Observe(Array.Empty<int>()).Should().Be(new ArrayNode(Array.Empty<ISettingsNode>()));
Observe(new List<string>()).Should().Be(new ArrayNode(new List<ISettingsNode>()));
}
[Test]
public void Should_return_value_node_for_value_object()
{
Observe("string").Should().Be(new ValueNode("string"));
Observe(Guid.Empty).Should().Be(new ValueNode(Guid.Empty.ToString()));
Observe(100).Should().Be(new ValueNode("100"));
Observe(Encoding.Unicode).Should().Be(new ValueNode(Encoding.Unicode.WebName));
}
[Test]
public void Should_handle_dictionaries()
{
var dictionary1 = new Dictionary<string, TimeSpan>
{
{"1", TimeSpan.Zero},
{"2", TimeSpan.MinValue},
{"3", TimeSpan.MaxValue}
};
Observe(dictionary1)
.Should()
.Be(
new ObjectNode(
new[]
{
new ValueNode("1", TimeSpan.Zero.ToString()),
new ValueNode("2", TimeSpan.MinValue.ToString()),
new ValueNode("3", TimeSpan.MaxValue.ToString())
}));
var dictionary2 = new Dictionary<int, string>
{
{1, "2"},
{3, "4"},
{5, "6"}
};
Observe(dictionary2)
.Should()
.Be(
new ObjectNode(
new[]
{
new ValueNode("1", "2"),
new ValueNode("3", "4"),
new ValueNode("5", "6")
}));
}
[Test]
public void Should_handle_sequences()
{
Observe(Enumerable.Range(1, 5).ToArray())
.Should()
.Be(new ArrayNode(Enumerable.Range(1, 5).Select(i => new ValueNode(i.ToString())).ToArray()));
Observe(Enumerable.Range(1, 10).ToList())
.Should()
.Be(new ArrayNode(Enumerable.Range(1, 10).Select(i => new ValueNode(i.ToString())).ToArray()));
Observe(Enumerable.Repeat(Guid.Empty, 1).ToArray())
.Should()
.Be(new ArrayNode(Enumerable.Repeat(Guid.Empty, 1).Select(i => new ValueNode(i.ToString())).ToArray()));
}
[Test]
public void Should_handle_objects_with_null_properties()
{
var johnDoe = new Person
{
Name = "John Doe",
Age = 65
};
Observe(johnDoe)
.Should()
.Be(
new ObjectNode(
new ISettingsNode[]
{
new ValueNode("Age", "65"),
new ValueNode("Name", "John Doe")
}));
}
[Test]
public void Should_handle_complex_objects()
{
var johnDoe = new Person("John Doe", 65);
var judyDoe = new Person("Judy Doe", 22);
var jamesDoe = new Person {Name = "James Doe", Age = 40};
johnDoe.Children.Add(judyDoe);
johnDoe.Children.Add(jamesDoe);
johnDoe.Info.Add(PersonInfo.BirthDayDate, "Date");
judyDoe.Info.Add(PersonInfo.SocialSecurityNumber, "Number");
Observe(johnDoe)
.Should()
.Be(
new ObjectNode(
new ISettingsNode[]
{
new ValueNode("Age", "65"),
new ValueNode("Name", "John Doe"),
new ArrayNode(
"Children",
new ISettingsNode[]
{
new ObjectNode(
new ISettingsNode[]
{
new ValueNode("Age", "22"),
new ValueNode("Name", "Judy Doe"),
new ArrayNode("Children", Array.Empty<ISettingsNode>()),
new ObjectNode(
"Info",
new ISettingsNode[]
{
new ValueNode("SocialSecurityNumber", "Number")
})
}),
new ObjectNode(
new ISettingsNode[]
{
new ValueNode("Age", "40"),
new ValueNode("Name", "James Doe")
})
}),
new ObjectNode(
"Info",
new ISettingsNode[]
{
new ValueNode("BirthDayDate", "Date")
})
}));
}
[Test]
public void Should_handle_sequence_of_dictionaries()
{
var arrayOfDictionaries = new[]
{
new Dictionary<string, int>
{
{"100", 100},
{"200", 200}
},
new Dictionary<string, int>
{
{"1000", 1000}
}
};
Observe(arrayOfDictionaries)
.Should()
.Be(
new ArrayNode(
null,
new ISettingsNode[]
{
new ObjectNode(
null,
new List<ISettingsNode>
{
new ValueNode("100", "100"),
new ValueNode("200", "200")
}),
new ObjectNode(
null,
new List<ISettingsNode>
{
new ValueNode("1000", "1000")
})
}));
}
[Test]
public void Should_handle_dictionary_of_objects()
{
var dictionaryOfPersons = new Dictionary<string, Person>
{
["Father"] = new Person("John Doe", 65),
["Daughter"] = new Person("Judy Doe", 22),
["Son"] = new Person("James Doe", 40)
};
Observe(dictionaryOfPersons)
.Should()
.Be(
new ObjectNode(
new ISettingsNode[]
{
new ObjectNode(
"Father",
new ISettingsNode[]
{
new ValueNode("Age", "65"),
new ValueNode("Name", "John Doe"),
new ArrayNode("Children", Array.Empty<ISettingsNode>()),
new ObjectNode("Info", Array.Empty<ISettingsNode>())
}),
new ObjectNode(
"Daughter",
new ISettingsNode[]
{
new ValueNode("Age", "22"),
new ValueNode("Name", "Judy Doe"),
new ArrayNode("Children", Array.Empty<ISettingsNode>()),
new ObjectNode("Info", Array.Empty<ISettingsNode>())
}),
new ObjectNode(
"Son",
new ISettingsNode[]
{
new ValueNode("Age", "40"),
new ValueNode("Name", "James Doe"),
new ArrayNode("Children", Array.Empty<ISettingsNode>()),
new ObjectNode("Info", Array.Empty<ISettingsNode>())
})
}));
}
[Test]
public void Should_error_on_cyclic_dependency()
{
var johnDoe = new Person("John Doe", 65);
var judyDoe = new Person("Judy Doe", 22);
var jamesDoe = new Person("James Doe", 40);
johnDoe.Children.Add(judyDoe);
judyDoe.Children.Add(jamesDoe);
jamesDoe.Children.Add(johnDoe);
var error = new ObjectSource(johnDoe).Observe().WaitFirstValue(1.Seconds()).error;
error.Should().NotBeNull().And.BeOfType<ArgumentException>();
}
[Test]
public void Should_handle_objects_with_repeated_elements()
{
var listOfInts = new List<int> {1, 2, 3};
var dictionaryOfLists = new Dictionary<string, IList<int>>
{
["First"] = listOfInts,
["Second"] = listOfInts,
["Third"] = listOfInts
};
Observe(dictionaryOfLists)
.Should()
.Be(
new ObjectNode(
null,
new ISettingsNode[]
{
new ArrayNode(
"First",
new List<ISettingsNode>
{
new ValueNode("1"), new ValueNode("2"), new ValueNode("3")
}),
new ArrayNode(
"Second",
new List<ISettingsNode>
{
new ValueNode("1"), new ValueNode("2"), new ValueNode("3")
}),
new ArrayNode(
"Third",
new List<ISettingsNode>
{
new ValueNode("1"), new ValueNode("2"), new ValueNode("3")
})
}));
}
[Test]
public void Should_include_fields_and_properties_with_null_value()
{
var johnDoe = new Person
{
Name = "John Doe",
Age = 65
};
var settings = new ObjectSourceSettings
{
IgnoreFieldsWithNullValue = false
};
Observe(johnDoe, settings)
.Should()
.Be(
new ObjectNode(
new ISettingsNode[]
{
new ValueNode("Name", "John Doe"),
new ValueNode("Age", "65"),
new ValueNode("Children", null),
new ValueNode("Info", null)
}));
}
private static ISettingsNode Observe(object obj, ObjectSourceSettings settings = null)
{
return new ObjectSource(obj, settings).Observe().WaitFirstValue(1.Seconds()).settings;
}
private enum PersonInfo
{
BirthDayDate,
SocialSecurityNumber
}
private class Person
{
public int Age;
public Person()
{
}
public Person(string name, int age)
{
Name = name;
Age = age;
Children = new List<Person>();
Info = new Dictionary<PersonInfo, string>();
}
public string Name { get; set; }
public ICollection<Person> Children { get; set; }
public IDictionary<PersonInfo, string> Info;
}
}
} | 37.154472 | 120 | 0.380817 | [
"MIT"
] | vostok/configuration.sources | Vostok.Configuration.Sources.Tests/ObjectSource_Tests.cs | 13,712 | C# |
namespace JMW.Google.OnHub.Model
{
public class RouterConfig
{
public string UpnpEnabled { get; set; }
public string BridgeModeEnabled { get; set; }
public string TrafficAcceleration { get; set; }
public string RouterIpAddress { get; set; }
public string RouterNetMask { get; set; }
}
} | 30.818182 | 55 | 0.637168 | [
"MIT"
] | walljm/googlewifionhub | src/JMW.Google.OnHub/Model/RouterConfig.cs | 341 | C# |
using System.Collections.Generic;
class Test
{
static U[] Foo<T, U> (T[] arg) where T : class, U
{
return arg;
}
static void TestByRef<T> ()
{
T[] array = new T[10];
PassByRef (ref array[0]);
}
static void PassByRef<T> (ref T t)
{
t = default (T);
}
public static int Main ()
{
foreach (var e in Foo<string, object> (new string[] { "as" })) {
}
TestByRef<byte> ();
return 0;
}
}
| 13.322581 | 66 | 0.57385 | [
"Apache-2.0"
] | 121468615/mono | mcs/tests/gtest-557.cs | 413 | C# |
using System;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Logging;
class SomeCommandHandler :
IHandleMessages<SomeCommand>
{
static ILog log = LogManager.GetLogger<SomeCommandHandler>();
static Random random = new Random();
public async Task Handle(SomeCommand message, IMessageHandlerContext context)
{
await Task.Delay(random.Next(50, 250))
.ConfigureAwait(false);
if (random.Next(10) <= 1)
{
throw new Exception("Random 10% chaos!");
}
log.Info("Hello from SomeCommandHandler");
}
} | 26 | 82 | 0.634615 | [
"Apache-2.0"
] | Cogax/docs.particular.net | samples/logging/application-insights/Metrics_3/Endpoint/SomeCommandHandler.cs | 603 | C# |
using DCISDBManager.objLib.Certificate;
using DCISDBManager.trnLib.CertificateManagement;
using DCISDBManager.trnLib.ParameterManagement;
using DCISDBManager.trnLib.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DCISDBManager.objLib.Usr;
using DCISDBManager.trnLib.CheckAuth;
using System.Transactions;
using DCISDBManager.trnLib.MasterMaintainance;
using DCISDBManager.trnLib.SupportDocumentSignManagement;
using DCISDBManager.trnLib.MasterDataManagement;
using System.Net;
using DCISDBManager.trnLib.CustomerRequestManagement;
using DCISDBManager.objLib.Email;
using DCISDBManager.trnLib.EmailManager;
namespace DSCMS.Views.Certificate
{
public partial class CertificateBulkSign : System.Web.UI.Page
{
CertificateRequestHeader CRHeader = new CertificateRequestHeader();
CertificateRequestManager CRManager = new CertificateRequestManager();
CertificateSignManagment CSMan = new CertificateSignManagment();
SupportingDocumentManagement SDManager = new SupportingDocumentManagement();
SDocSignRequsetManager SDsign = new SDocSignRequsetManager();
List<EmailRequest> ERlist = new List<EmailRequest>();
MailSendManager SendManger = new MailSendManager();
List<CertificateRequestDetail> CRDetails = new List<CertificateRequestDetail>();
List<SupportingDocUpload> SupList = new List<SupportingDocUpload>();
CertificateRequestDetail CRD = new CertificateRequestDetail();
UserSession userSession;
CheckAuthManager authorized;
string ExpireDays = System.Configuration.ConfigurationManager.AppSettings["CertificateExpire"];
string HSCODEHAS = System.Configuration.ConfigurationManager.AppSettings["HSCODEHAS"];
string GOLOBALTMP = System.Configuration.ConfigurationManager.AppSettings["GOLOBALTMP"];
string MASSACTIVE = System.Configuration.ConfigurationManager.AppSettings["MASSACTIVE"];
string NINDROTMP = System.Configuration.ConfigurationManager.AppSettings["NINDROTMP"];
string ROWWITHOUTHS = System.Configuration.ConfigurationManager.AppSettings["ROWWITHOUTHS"];
string ROWWITH_HS = System.Configuration.ConfigurationManager.AppSettings["ROWWITH_HS"];
string COLUMNWITHOUTHS = System.Configuration.ConfigurationManager.AppSettings["COLUMNWITHOUTHS"];
string COLUMNWITHOUTHS2 = System.Configuration.ConfigurationManager.AppSettings["COLUMNWITHOUTHS2"];
string CertificateLOGO = System.Configuration.ConfigurationManager.AppSettings["CertificateLOGO"];
string CertificateSEAL = System.Configuration.ConfigurationManager.AppSettings["CertificateSEAL"];
protected void Page_Load(object sender, EventArgs e)
{
userSession = new UserSession();
authorized = new CheckAuthManager();
ERlist = SendManger.getSendPendingMailSendingCertificates("%","%");
if (userSession.User_Id == "")
{
Response.Redirect("~/Views/Home/Logout.aspx");
}
bool resutl = authorized.IsUserGroupAuthorised(userSession.User_Group, "BULKS");
if (resutl == false)
{
Response.Redirect("~/Views/Home/Forbidden.aspx");
}
if (!this.IsPostBack)
{
getCustomer();
getPendingCRequest("%");
getRejectResons();
}
// btnSendApproval.Text = "Pending Emails (" + ERlist.Count() +")";
}
private void getPendingCRequest(string CustomerID)
{
try
{
gvPendigCR.DataSource = CRManager.GetAllPendingCertificates(CustomerID).AllPendingCertificate_List;
gvPendigCR.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError("getPendingCRequest() @ PendingCertificate.aspx", Ex);
}
}
protected void getCustomer()
{
try
{
CustomerDetailManager cm = new CustomerDetailManager();
drpCustomer.DataSource = cm.getAllCustomer("Y");
drpCustomer.DataValueField = "CustomerId1";
drpCustomer.DataTextField = "CustomerName1";
drpCustomer.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
private void getRejectResons()
{
RejectResonManagment ReM = new RejectResonManagment();
drpRejectReason.DataSource = ReM.getCertificaterRejectResons();
drpRejectReason.DataTextField = "Reason_";
drpRejectReason.DataValueField = "Reason_Code";
drpRejectReason.DataBind();
}
private void getSupportingDOC(string id)
{
SupList = CRManager.getSupportingDOCfRequest(id);
gvSupportingDOc.DataSource = SupList;
gvSupportingDOc.DataBind();
}
private void getUSupportingDOC(string id)
{
SupList = CRManager.getSupportingDOCfUploadBRequest(id);
gvSupportingDOc.DataSource = SupList;
gvSupportingDOc.DataBind();
}
protected void btnBulkSign_Click(object sender, EventArgs e)
{
try
{
if (userSession.C_Password.Equals(""))
{
lblError.Text = string.Empty;
mp1.Show();
}
else
{
bool result = false;
foreach (GridViewRow row in gvPendigCR.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = ((CheckBox)row.FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblTemplateID = (Label)row.FindControl("lblTemplateID");
Label lblUploadPath = (Label)row.FindControl("lblUploadPath");
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
Label lblRequestType = (Label)row.FindControl("lblCertificateType");
Label lblSealRequired = (Label)row.FindControl("lblSealRequired");
string RequestID = lblRequestID.Text;
string TemplateID = lblTemplateID.Text;
string CustomerID = lblCustomerID.Text;
string UploadPath = lblUploadPath.Text;
bool SealNeeded = Convert.ToBoolean(lblSealRequired.Text);
if (lblRequestType.Text.Equals("W"))
{
CRHeader = CRManager.getRequestByID(RequestID);
if (CRHeader.TemplateId1.Equals(ROWWITH_HS) || CRHeader.TemplateId1.Equals(ROWWITHOUTHS))
{
CRD = CRManager.getROWbasedCertificateRequestDetails(RequestID);
}
else { CRDetails = CRManager.getReqDetailByReqID(RequestID, true); }
SupList = CRManager.getSupportingDOCfRequest(RequestID);
result = CreateCertificate(TemplateID);
}
else
{
getUSupportingDOC(RequestID);
result = ApproveCertificateRequest(CustomerID, RequestID, UploadPath, SealNeeded);
}
if (!result)
{
getPendingCRequest(drpCustomer.SelectedValue);
return;
}
}
}
// Thread.Sleep(100);
}
getPendingCRequest(drpCustomer.SelectedValue);
}
}
catch (Exception Ex)
{
ErrorLog.LogError("PendingCertificates.asp. BulkSign", Ex);
}
}
protected bool CreateCertificate(string Template)
{
using (TransactionScope transactionScope = new TransactionScope())
{
try
{
bool Created = false;
SequenceManager seqmanager = new SequenceManager();
string Certificate_No = "CE" + seqmanager.getNextSequence("CertificateSign").ToString();
CRHeader.CertificateId1 = Certificate_No;
string LogoPath = Server.MapPath(CertificateLOGO); // NCE Certificate logo Image path
string DirectoryPath = "~/Documents/" + DateTime.Now.ToString("yyyy")
+ "/Issued_Certificates/" + DateTime.Now.ToString("yyyy_MM_dd")
+ "/" + Certificate_No + "_Certificate";
//DirectoryPath which will save the NOT singed PDF File as NOT_Signed.pdf in the given Path
if (!Directory.Exists(Server.MapPath(DirectoryPath)))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath));
}
/**PDF Cerator
* Parameters
* Certificate Reques Header Detail Object
* Certificate Request Item Details Object List
* Document Save Path
*
*/
if (Template.Equals(ROWWITH_HS))
{
PDFCreator.RowWithHSTemplate Certificate =
new PDFCreator.RowWithHSTemplate(CRHeader,
CRD, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"),userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(ROWWITHOUTHS))
{
PDFCreator.RowWithoutHSTemplate Certificate =
new PDFCreator.RowWithoutHSTemplate(CRHeader,
CRD, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(GOLOBALTMP))
{
PDFCreator.OrientGlobalCertificateTemplate Certificate =
new PDFCreator.OrientGlobalCertificateTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(MASSACTIVE))
{
PDFCreator.MassActiveCertificateTemplate Certificate =
new PDFCreator.MassActiveCertificateTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(NINDROTMP))
{
PDFCreator.NidroCertificateTemplate Certificate =
new PDFCreator.NidroCertificateTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(COLUMNWITHOUTHS))
{
PDFCreator.ColumnWithoutHSTemplate Certificate =
new PDFCreator.ColumnWithoutHSTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(COLUMNWITHOUTHS2))
{
PDFCreator.ColumnWithoutHSTemplate Certificate =
new PDFCreator.ColumnWithoutHSTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
else
{
PDFCreator.ColumnWithHSTemplate Certificate =
new PDFCreator.ColumnWithHSTemplate(CRHeader,
CRDetails, LogoPath,
Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"), userSession.Person_Name, DateTime.Now.ToString("yyyy/MM/dd"));
Created = Certificate.CreateCertificate("");
}
CRDetails.Clear();
//if (Created)
//{
// CRManager.setWebBasedCertificateCreation(CRHeader.RequestId1,
// DirectoryPath + "/" + CRHeader.RequestId1 + "_Not_Signed.pdf",
// CRHeader.RequestId1 + "_Not_Signed.pdf");
//}
string Sealed = Server.MapPath(DirectoryPath + "/_Not_Signed.pdf");
string NotSigned = Server.MapPath(DirectoryPath + "/_Not_Signed.pdf"); ;
string Signed = Server.MapPath(DirectoryPath + "/" + Certificate_No + "_Certificate.pdf");
string pathe = Server.MapPath(userSession.PFX_path);//From DB
// string pathe = Server.MapPath("~/Signature/Samitha/Samitha.pfx");//From DB
string SignatureIMG = Server.MapPath(userSession.SignatureIMG_Path);// From DB
// string SignatureIMG = Server.MapPath("~/Signature/Samitha/sign.JPG");// From DB
var PFX = new FileStream(pathe, FileMode.OpenOrCreate);
PDFCreator.Signature SignCertificate = new PDFCreator.Signature();
if (Convert.ToBoolean(CRHeader.Seal_Required))
{
SignCertificate.AddSeal(Sealed, Server.MapPath(userSession.SignatureIMG_Path));
NotSigned = Server.MapPath(DirectoryPath + "/_Not_Signed_S.pdf");
}
bool singed = SignCertificate.signCertificate(NotSigned, Signed,
PFX, userSession.C_Password);
if (!singed)
{
PFX.Close();
//mp1.Show();
//lblError.Text = "Wrong password or Corrupted Certificate file.";
userSession.C_Password = "";
return false;
}
CertificateApproval Approve = new CertificateApproval();
Approve.Certificate_Name = Certificate_No + "_Certificate.pdf";
Approve.Certificate_Path = DirectoryPath + "/" + Certificate_No + "_Certificate.pdf";
// Approve.Created_By = "SAMITHA";
Approve.Created_By = userSession.User_Id;
Approve.Expiry_Date = DateTime.Today.AddDays(Convert.ToInt64(ExpireDays));
Approve.Is_Downloaded = "N";
Approve.Is_Valid = "Y";
Approve.Request_Id = CRHeader.RequestId1;
Approve.Certificate_Id = Certificate_No;
bool result = CSMan.ApproveCertificate(Approve);
for (int i = 0; i < SupList.Count(); i++)
{
if (SupList[i]._Remarks.Equals("NCE_Certification"))
{
string DocPath = Server.MapPath(DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name);
string SealedPath = Server.MapPath(DirectoryPath + "/Supporting-Doc/Temp/" + SupList[i].Document_Name);
if (!Directory.Exists(Server.MapPath(DirectoryPath + "/Supporting-Doc")))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath + "/Supporting-Doc/Temp"));
}
PDFCreator.Signature SignDoc = new PDFCreator.Signature();
SignDoc.AddSealSD(Server.MapPath(SupList[i].Uploaded_Path),SealedPath,Server.MapPath(userSession.SignatureIMG_Path));
var PFX2 = new FileStream(pathe, FileMode.OpenOrCreate);
bool Sign = SignDoc.signSupportingDoc(Certificate_No,
SealedPath,
DocPath,
PFX2, userSession.C_Password);
if (!Sign)
{
PFX.Close();
PFX2.Close();
//lblError.Text = "Corrupted Supporting Document file @ " + SupList[i].Request_Ref_No + ":" + SupList[i].Document_Id + ". Signature Placement Failed !";
//mp1.Show();
userSession.C_Password = "";
return false;
}
SupList[i].Certified_Doc_Path = DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name;
SupList[i].Status_ = "A";
SupList[i].Customer_ID = CRHeader.CustomerId1;
SupList[i].Approved_By = userSession.User_Id;
SupList[i].Expire_Date = DateTime.Today.AddDays(Convert.ToInt64(ExpireDays)).ToString();
SDsign.setSupportingDocSignRequestINCertRequest(SupList[i]);
SupList[i].Uploaded_Path = DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name;
CRManager.UpdateSupportingDocCertified(SupList[i]);
}
}
transactionScope.Complete();
transactionScope.Dispose();
return true;
}
catch (TransactionAbortedException Ex)
{
transactionScope.Dispose();
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! (Transaction) </strong>Ether The Certificate Is Approved By another Signatory Or The Database Transaction Has Faild</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
this.getPendingCRequest(drpCustomer.SelectedValue);
return false;
}
catch (FileNotFoundException Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Certificate File Not Found ! Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
this.getPendingCRequest(drpCustomer.SelectedValue);
return false;
}
catch (FieldAccessException Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Cannot Access the Certificate Files Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
this.getPendingCRequest(drpCustomer.SelectedValue);
return false;
}
catch (Exception Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Cannot Access the Files Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
this.getPendingCRequest(drpCustomer.SelectedValue);
return false;
}
}
}
protected void btnCerateCertificate_Click(object sender, EventArgs e)
{
bool result = false;
userSession.C_Password = txtCertificatePass.Text;
foreach (GridViewRow row in gvPendigCR.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = ((CheckBox)row.FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblTemplateID = (Label)row.FindControl("lblTemplateID");
Label lblUploadPath = (Label)row.FindControl("lblUploadPath");
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
Label lblRequestType = (Label)row.FindControl("lblCertificateType");
Label lblSealRequired = (Label)row.FindControl("lblSealRequired");
string RequestID = lblRequestID.Text;
string TemplateID = lblTemplateID.Text;
string CustomerID = lblCustomerID.Text;
string UploadPath = lblUploadPath.Text;
if (lblRequestType.Text.Equals("W"))
{
CRHeader = CRManager.getRequestByID(RequestID);
if (CRHeader.TemplateId1.Equals(ROWWITH_HS) || CRHeader.TemplateId1.Equals(ROWWITHOUTHS))
{
CRD = CRManager.getROWbasedCertificateRequestDetails(RequestID);
}
else { CRDetails = CRManager.getReqDetailByReqID(RequestID, true); }
SupList = CRManager.getSupportingDOCfRequest(RequestID);
result = CreateCertificate(TemplateID);
}
else
{
getUSupportingDOC(RequestID);
result = ApproveCertificateRequest(CustomerID, RequestID, UploadPath,Convert.ToBoolean(lblSealRequired.Text));
}
if (!result)
{
getPendingCRequest(drpCustomer.SelectedValue);
return;
}
}
}
// Thread.Sleep(100);
}
getPendingCRequest(drpCustomer.SelectedValue);
}
protected void gvPendigCR_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("CertificateDetails.aspx?ReqstID=" + gvPendigCR.SelectedRow.Cells[0].Text, false);
}
protected void gvPendigCR_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPendigCR.PageIndex = e.NewPageIndex;
getPendingCRequest(drpCustomer.SelectedValue);
}
protected void btnApprove_Click(object sender, EventArgs e) ////
{
try
{
if (userSession.C_Password.Equals(""))
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblTemplateID = (Label)row.FindControl("lblTemplateID");
Label lblUploadPath = (Label)row.FindControl("lblUploadPath");
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
Label lblCRequestType = (Label)row.FindControl("lblCertificateType");
Label lblSealRequired = (Label)row.FindControl("lblSealRequired");
txtRequestID.Text = lblRequestID.Text;
txtTemplateID.Text = lblTemplateID.Text;
txtCustomerID.Text = lblCustomerID.Text;
txtUploadPath.Text = lblUploadPath.Text;
txtCRequestType.Text = lblCRequestType.Text;
txtSealBoolen.Text = lblSealRequired.Text;
}
LblError2.Text = string.Empty;
mp2.Show();
}
else
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblRequestType = (Label)row.FindControl("lblCertificateType");
Label lblTemplateID = (Label)row.FindControl("lblTemplateID");
Label lblUploadPath = (Label)row.FindControl("lblUploadPath");
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
Label lblSealRequired = (Label)row.FindControl("lblSealRequired");
string RequestID = lblRequestID.Text;
string TemplateID = lblTemplateID.Text;
string CustomerID = lblCustomerID.Text;
string UploadPath = lblUploadPath.Text;
if (lblRequestType.Text.Equals("W"))
{
CRHeader = CRManager.getRequestByID(RequestID);
if (CRHeader.TemplateId1.Equals(ROWWITH_HS) || CRHeader.TemplateId1.Equals(ROWWITHOUTHS))
{
CRD = CRManager.getROWbasedCertificateRequestDetails(RequestID);
}
else { CRDetails = CRManager.getReqDetailByReqID(RequestID, true); }
SupList = CRManager.getSupportingDOCfRequest(RequestID);
bool result = CreateCertificate(TemplateID);
if (!result)
{
getPendingCRequest(drpCustomer.SelectedValue);
mp2.Show();
LblError2.Text = "Wrong password or Corrupted Certificate file.";
return;
}
//else
//{
// SendApprovedCertificates(CustomerID, RequestID);
//}
}
else
{
getUSupportingDOC(RequestID);
bool result = ApproveCertificateRequest(CustomerID, RequestID, UploadPath,Convert.ToBoolean(lblSealRequired.Text));
//if (result) { SendApprovedCertificates(CustomerID, RequestID); }
}
}
getPendingCRequest(drpCustomer.SelectedValue);
}
}
catch (Exception Ex)
{
ErrorLog.LogError("PendingCertificates.aspx - Single Approval button", Ex);
}
}
protected void btnReject_Click(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblCertificateType = (Label)row.FindControl("lblCertificateType");
Label lblCEmail = (Label)row.FindControl("lblCEmail");
lblRejectRequestID.Text = lblRequestID.Text;
lblRCertificateType.Text = lblCertificateType.Text;
lblCUSEmail.Text = lblCEmail.Text;
}
lblRejectError.Text = string.Empty;
mp3.Show();
}
protected void btnApproveCertificate_Click(object sender, EventArgs e)
{
userSession.C_Password = txtCpassword.Text;
if (txtCRequestType.Text.Equals("W"))
{
CRHeader = CRManager.getRequestByID(txtRequestID.Text);
if (CRHeader.TemplateId1.Equals(ROWWITH_HS) || CRHeader.TemplateId1.Equals(ROWWITHOUTHS))
{
CRD = CRManager.getROWbasedCertificateRequestDetails(txtRequestID.Text);
}
else { CRDetails = CRManager.getReqDetailByReqID(txtRequestID.Text, true); }
SupList = CRManager.getSupportingDOCfRequest(txtRequestID.Text);
bool result = CreateCertificate(txtTemplateID.Text);
if (!result)
{
mp2.Show();
LblError2.Text = "Wrong password or Corrupted Certificate file.";
return;
}
//else
//{
// SendApprovedCertificates(txtCustomerID.Text, txtRequestID.Text);
//}
}
else
{
getUSupportingDOC(txtRequestID.Text);
bool result = ApproveCertificateRequest(txtCustomerID.Text, txtRequestID.Text, txtUploadPath.Text,Convert.ToBoolean(txtSealBoolen.Text));
//if (result) { SendApprovedCertificates(txtCustomerID.Text, txtRequestID.Text); }
}
getPendingCRequest(drpCustomer.SelectedValue);
}
protected void likViewSupportingDoc_Click(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label lblCertificateType = (Label)row.FindControl("lblCertificateType");
if (lblCertificateType.Text.Equals("W"))
{
getSupportingDOC(lblRequestID.Text);
lblCType.Text = "W";
}
else
{
getUSupportingDOC(lblRequestID.Text);
lblCType.Text = "U";
}
mpSD.Show();
}
}
protected void linkDownloadSD_Click(object sender, EventArgs e)
{
try
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblDocName = (Label)row.FindControl("lblDocName");
Label lblSDUppathe = (Label)row.FindControl("lblSDUppathe");
Label lblRefNo = (Label)row.FindControl("lblRefNo");
Session["PDFUrl"] = lblSDUppathe.Text;
string pageurl = "PdfView.aspx?ID=" + lblRefNo.Text + "&DN=" + lblDocName.Text;
// Response.Write("<script> window.open('" + pageurl + "','_blank'); </script>");
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('" + pageurl + "','_blank');", true);
if (lblCType.Text.Equals("W"))
{
getSupportingDOC(lblRefNo.Text);
lblCType.Text = "W";
}
else
{
getUSupportingDOC(lblRefNo.Text);
lblCType.Text = "U";
}
mpSD.Show();
}
}
catch (Exception Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong> Unable To Download The File....</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
}
}
protected void btnRejectCertificateReq_Click(object sender, EventArgs e)
{
if (drpRejectReason.SelectedIndex == 0)
{
lblRejectError.Text = "Please Select a Reject Reson First.";
mp3.Show();
return;
}
try
{
bool result = false;
if (lblRCertificateType.Text.Equals("W"))
{
result = CSMan.RejectCertificate(lblRejectRequestID.Text, userSession.User_Id, drpRejectReason.SelectedValue);
}
else
{
result = CSMan.RejectUBCertificate(lblRejectRequestID.Text, userSession.User_Id, drpRejectReason.SelectedValue);
}
if (result)
{
SendManger.SendEmail(lblCUSEmail.Text,
"Certificate Rejected",
"<h2 align=\"center\" style=\"color:#0178d8;\">National Chamber of Exporters of Sri Lanka</h2>" +
"<h3 align=\"center\">National Chamber of Exporters of Sri Lanka</h3><br>" +
"<p>This is to inform your request (Doc. No " + lblRejectRequestID.Text + " )has been Rejected by the NCE.</p>" +
"Rejected Reason : " + drpRejectReason.SelectedItem.Text + "</p>"
+ "<p>For further clarifications, please contact Mr. Susantha Rupathunga on 4344218 or nce.dco@gmail.com</p>", "");
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-success\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " Request Rejected.";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
}
else
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Server Error Please Contact the Administrator.";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div>";
ErrorMessage.InnerHtml = qu;
}
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
try
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblPath = (Label)row.FindControl("lblUploadPath");
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Session["PDFUrl"] = lblPath.Text;
string pageurl = "PdfView.aspx?ID=" + lblRequestID.Text + "&DN=" + lblRequestID.Text + ".pdf";
// Response.Write("<script> window.open('" + pageurl + "','_blank'); </script>");
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('" + pageurl + "','_blank');", true);
}
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
protected void btnByCustomer_Click(object sender, EventArgs e)
{
getPendingCRequest(drpCustomer.SelectedValue);
}
private bool ApproveCertificateRequest(string CustomerID, string RequestID, string CerificatePath,bool SealReqired)
{
using (TransactionScope transactionScope = new TransactionScope())
{
try
{
SequenceManager seqmanager = new SequenceManager();
string Certificate_No = "CE" + seqmanager.getNextSequence("CertificateSign").ToString();
string DirectoryPath = "~/Documents/" + DateTime.Now.ToString("yyyy")
+ "/Issued_Certificates/" + DateTime.Now.ToString("yyyy_MM_dd") + "/"
+ Certificate_No + "_Certificate";
//DirectoryPath which will save the NOT singed PDF File as NOT_Signed.pdf in the given Path
if (!Directory.Exists(Server.MapPath(DirectoryPath)))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath));
}
PDFCreator.Signature SignCertificate = new PDFCreator.Signature();
string NotSigned = Server.MapPath(CerificatePath);
string CertificateID_Added = Server.MapPath(DirectoryPath + "/" + "Not_Signed" + "_Certificate.pdf");
/* Method Which Create a New Document Withe Printed Certificate ID
* Point is the Certificate ID Placement Area Object
*/
System.Drawing.Point Point = new System.Drawing.Point();
Point.X = 350;
Point.Y = 55;
SignCertificate.AddTextToPdf(NotSigned, CertificateID_Added, Certificate_No, Point, Server.MapPath(userSession.SignatureIMG_Path), SealReqired,userSession.Person_Name);
// string NotSigned = Server.MapPath(CerificatePath);
string Signed = Server.MapPath(DirectoryPath + "/" + Certificate_No + "_Certificate.pdf");
string pathe = Server.MapPath(userSession.PFX_path);//From DB
//string pathe = Server.MapPath("~/Signature/Samitha/Samitha.pfx");//From DB
string SignatureIMG = Server.MapPath(userSession.SignatureIMG_Path);// From DB
//string SignatureIMG = Server.MapPath("~/Signature/Samitha/Chernenko_Signature.png");// From DB
var PFX = new FileStream(pathe, FileMode.OpenOrCreate);
// PDFCreator.Signature SignCertificate = new PDFCreator.Signature();
bool singed = SignCertificate.signCertificate(CertificateID_Added, Signed, PFX, userSession.C_Password);
if (!singed)
{
PFX.Close();
lblError.Text = "Wrong password or Corrupted Certificate file.";
userSession.C_Password = "";
mp2.Show();
return false;
}
CertificateApproval Approve = new CertificateApproval();
Approve.Certificate_Name = Certificate_No + "_Certificate.pdf";
Approve.Certificate_Path = DirectoryPath + "/" + Certificate_No + "_Certificate.pdf";
// Approve.Created_By = "SAMITHA";
Approve.Created_By = userSession.User_Id;
Approve.Expiry_Date = DateTime.Today.AddDays(Convert.ToInt64(ExpireDays));
Approve.Is_Downloaded = "N";
Approve.Is_Valid = "Y";
Approve.Request_Id = RequestID;
Approve.Certificate_Id = Certificate_No;
bool result = CSMan.ApproveCertificate(Approve);
bool result2 = CRManager.UpdateUploadBCertifcateRequest(Approve);
for (int i = 0; i < SupList.Count(); i++)
{
if (SupList[i]._Remarks.Equals("NCE_Certification"))
{
string DocPath = Server.MapPath(DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name);
string SealedPath = Server.MapPath(DirectoryPath + "/Supporting-Doc/Temp/" + SupList[i].Document_Name);
if (!Directory.Exists(Server.MapPath(DirectoryPath + "/Supporting-Doc")))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath + "/Supporting-Doc/Temp"));
}
PDFCreator.Signature SignDoc = new PDFCreator.Signature();
SignDoc.AddSealSD(Server.MapPath(SupList[i].Uploaded_Path), SealedPath, Server.MapPath(userSession.SignatureIMG_Path));
var PFX2 = new FileStream(pathe, FileMode.OpenOrCreate);
bool Sign = SignDoc.signSupportingDoc(Certificate_No,
SealedPath,
DocPath,
PFX2, userSession.C_Password);
if (!Sign)
{
PFX.Close();
PFX2.Close();
userSession.C_Password = "";
lblError.Text = "Corrupted Supporting Document file. Signature Placement Failed !";
mp2.Show();
return false;
}
SupList[i].Certified_Doc_Path = DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name;
SupList[i].Status_ = "A";
SupList[i].Customer_ID = CustomerID;
SupList[i].Approved_By = userSession.User_Id;
SupList[i].Expire_Date = DateTime.Today.AddDays(Convert.ToInt64(ExpireDays)).ToString();
SDsign.setSupportingDocSignRequestINCertRequest(SupList[i]);
SupList[i].Uploaded_Path = DirectoryPath + "/Supporting-Doc/" + SupList[i].Document_Name;
CRManager.UpdateSupportingDocCertified(SupList[i]);
}
}
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-success\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " Certificate Approval Successful..";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button></div>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
transactionScope.Complete();
transactionScope.Dispose();
return true;
}
catch (TransactionAbortedException Ex)
{
transactionScope.Dispose();
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! (Transaction) </strong>Ether The Certificate Is Approved By another Signatory Or The Database Transaction Has Faild !</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
ErrorLog.LogError(Ex);
return false;
}
catch (FileNotFoundException Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Certificate File Not Found ! Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
ErrorLog.LogError(Ex);
return false;
}
catch (FieldAccessException Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Cannot Access the Files Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
ErrorLog.LogError(Ex);
return false;
}
catch (Exception Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Cannot Access the Files Please Contact the Administrator</div>";
qu += "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
ErrorMessage.InnerHtml = qu;
getPendingCRequest(drpCustomer.SelectedValue);
ErrorLog.LogError(Ex);
return false;
}
}
}
protected void SendApprovedCertificates(string Cid,string Rid)
{
ERlist = SendManger.getSendPendingMailSendingCertificates(Cid,Rid);
if (ERlist.Count != 0)
{
for (int x = 0; x < ERlist.Count(); x++)
{
try
{
int Send = 0;
//Send = SendManger.SendEmail(ERlist[x].Email_,
// "Certificate Approved",
// "Your Certificate Request Under Ref No : "
// +ERlist[x].Request_ID +" Has Been Approved. You can Download it Under "
// + "Certificate-Id : " + ERlist[x].Certificate_Id,"");
Send = SendManger.SendEmail(ERlist[x].Email_,
"Certificate Approved",
"<h2 align=\"center\" style=\"color:#0178d8;\">National Chamber of Exporters of Sri Lanka</h2>" +
//"<h3 align=\"center\">National Chamber of Exporters of Sri Lanka</h3><br>" +
"<p>Thank you for placing the request of the Certificate of Origin from the National Chamber of Exporters of Sri Lanka.</p>"+
"<p>This is to confirm your request (Doc. No " + ERlist[x].Request_ID + " )has been approved by the NCE.</p>" +
"<p>You can Download it Under "
+ "Reference No : " + ERlist[x].Certificate_Id +"</p>"
+ "<p>For further clarifications, please contact Mr. Susantha Rupathunga on 4344218 or nce.dco@gmail.com", "");
if (Send == 1)
{
SendManger.UpdateApprovalMailsend(ERlist[x].Certificate_Id);
}
else if (Send == 2)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " There is No Internet Connection.</div>";
ErrorMessage.InnerHtml = qu;
}
else
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += "Confirmation Email Send Faild.</div>";
ErrorMessage.InnerHtml = qu;
}
}
catch (Exception Ex)
{
ErrorLog.LogError("Email Sending Fail", Ex);
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " Confirmation Email Send Faild.</div>";
ErrorMessage.InnerHtml = qu;
}
}
}
}
protected void btnSendApproval_Click(object sender, EventArgs e)
{
SendApprovedCertificates("%","%");
}
}
} | 49.986928 | 188 | 0.498431 | [
"Apache-2.0"
] | Ruke45/DManagement | DSCMS/DSCMS/Views/Certificate/PendingCertificates.aspx.cs | 53,538 | C# |
using System;
using HotChocolate.Language;
namespace HotChocolate.Types
{
public abstract class ScalarType
: INamedOutputType
, INamedInputType
, ISerializableType
{
protected ScalarType(string name)
: this(name, null)
{
}
protected ScalarType(string name, string description)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
Name = name;
Description = description;
}
public TypeKind Kind { get; } = TypeKind.Scalar;
public string Name { get; }
public virtual string Description { get; }
public abstract Type NativeType { get; }
public abstract bool IsInstanceOfType(IValueNode literal);
public abstract object ParseLiteral(IValueNode literal);
public abstract IValueNode ParseValue(object value);
public abstract object Serialize(object value);
}
}
| 23.477273 | 66 | 0.603098 | [
"MIT"
] | gmiserez/hotchocolate | src/Types/Types/Scalars/ScalarType.cs | 1,033 | C# |
namespace OctopusSamples.OctoPetShop
{
public class AppSettings
{
public string AppVersion { get; set; }
public string EnvironmentName { get; set; }
public string ProductServiceBaseUrl { get; set; }
public string ShoppingCartServiceBaseUrl { get; set; }
}
}
| 27.454545 | 62 | 0.662252 | [
"Apache-2.0"
] | DamovisaInc/SarahOctoPet | OctopusSamples.OctoPetShop.Web/AppSettings.cs | 302 | C# |
namespace NServiceBus.Unicast.Queuing
{
using System;
[Serializable]
public class FailedToSendMessageException : Exception
{
public FailedToSendMessageException() { }
public FailedToSendMessageException( string message ) : base( message ) { }
public FailedToSendMessageException( string message, Exception inner ) : base( message, inner ) { }
protected FailedToSendMessageException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context ) : base( info, context ) { }
}
}
| 37.25 | 106 | 0.708054 | [
"Apache-2.0",
"MIT"
] | abombss/NServiceBus | src/NServiceBus.Core/Unicast/Queuing/FailedToSendMessageException.cs | 581 | C# |
using UnityEngine;
public class Goal : MonoBehaviour
{
public float positionRange;
public float minScale, maxScale;
[HideInInspector] public HaulerAgent agent;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("target"))
{
agent.MarkTaskDone(TaskEndReason.Finished);
}
}
public void Reset(Vector3 targetLocation)
{
float scale = Random.Range(minScale, maxScale);
Vector3 newPos;
do
{
newPos = new Vector3(Random.Range(-1f, 1f) * positionRange, transform.localPosition.y, Random.Range(-1f, 1f) * positionRange);
}
while (Vector3.Distance(newPos, targetLocation) < 5 || Physics.OverlapSphere(transform.position, 2f, 2).Length >= 1);
transform.localPosition = newPos;
transform.localScale = new Vector3(scale, transform.localScale.y, scale);
}
}
| 29.451613 | 138 | 0.645126 | [
"MIT"
] | damasioj/Hauler | Assets/World/Scripts/Goal/Goal.cs | 915 | C# |
namespace Yoga.Parser
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class NodeRenderer<T> : INodeRenderer
{
public NodeRenderer(IYogaParser parser, string name = null)
{
this.parser = parser;
if (name == null)
{
var typename = typeof(T).Name;
if (typename.StartsWith("I", StringComparison.Ordinal))
typename = typename.Substring(1);
name = typename;
}
this.Type = typeof(T);
this.Name = name;
}
private IYogaParser parser;
#region Property renderers
private List<IPropertyRenderer> propertyRenderers = new List<IPropertyRenderer>();
public void RegisterPropertyRenderer(IPropertyRenderer renderer)
{
var existing = this.propertyRenderers.FindIndex(x => x.Name == renderer.Name);
if (existing >= 0) propertyRenderers.RemoveAt(existing);
propertyRenderers.Add(renderer);
}
protected void RenderProperty(object instance, string name, object value)
{
var renderer = this.propertyRenderers.FirstOrDefault(x => x.Name == name);
if(renderer != null)
{
var v = parser.ConvertValue(value, renderer.Type);
renderer.Render(instance, v);
}
}
#endregion
public string Name { get; }
public Type Type { get; }
#region Rendering
public virtual T Render(INode node)
{
var result = (T)Activator.CreateInstance(typeof(T));
foreach (var prop in node.Properties)
{
this.RenderProperty(result, prop.Key, prop.Value);
}
return result;
}
object INodeRenderer.Render(INode node) => this.Render(node);
#endregion
}
public class NodeRenderer<T, TImpl> : NodeRenderer<T> where TImpl : T
{
public NodeRenderer(IYogaParser parser, string name = null) : base(parser, name)
{
}
public override T Render(INode node)
{
var result = (T)Activator.CreateInstance(typeof(TImpl));
foreach (var prop in node.Properties)
{
this.RenderProperty(result, prop.Key, prop.Value);
}
return result;
}
}
}
| 21.297872 | 84 | 0.688312 | [
"MIT"
] | aloisdeniel/Yoga.Parser | Sources/Yoga.Parser.Xml/NodeRenderers/NodeRenderer.cs | 2,004 | C# |
using System.Collections.Generic;
using System.Linq;
namespace NuGetGallery
{
public class PackageSearchResults
{
public IQueryable<Package> Packages { get; set; }
public IEnumerable<int> RankedKeys { get; set; }
}
} | 20.583333 | 57 | 0.684211 | [
"ECL-2.0",
"Apache-2.0"
] | JetBrains/ReSharperGallery | src/NuGetGallery/Services/PackageSearchResults.cs | 249 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Samples.Gps
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LogsPage : ContentPage
{
public LogsPage()
{
InitializeComponent();
}
}
} | 19.3 | 53 | 0.689119 | [
"MIT"
] | DanielCauser/shiny | Samples/Samples/Gps/LogsPage.xaml.cs | 388 | C# |
//------------------------------------------------------------------------------
// <copyright file="CaptureTests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// </copyright>
//------------------------------------------------------------------------------
using System;
using Microsoft.Azure.Kinect.Sensor.Test.StubGenerator;
using NUnit.Framework;
namespace Microsoft.Azure.Kinect.Sensor.UnitTests
{
/// <summary>
/// Tests that validate the Capture object.
/// </summary>
public class CaptureTests
{
private readonly StubbedModule nativeK4a;
/// <summary>
/// Initializes a new instance of the <see cref="CaptureTests"/> class.
/// </summary>
public CaptureTests()
{
this.nativeK4a = StubbedModule.Get("k4a");
if (this.nativeK4a == null)
{
NativeInterface k4ainterface = NativeInterface.Create(
EnvironmentInfo.CalculateFileLocation(@"k4a\k4a.dll"),
EnvironmentInfo.CalculateFileLocation(@"k4a\k4a.h"));
this.nativeK4a = StubbedModule.Create("k4a", k4ainterface);
}
}
/// <summary>
/// Called before test methods.
/// </summary>
[SetUp]
public void Setup()
{
// Don't hook the native allocator
Microsoft.Azure.Kinect.Sensor.Allocator.Singleton.UseManagedAllocator = false;
}
/// <summary>
/// Validate that garbage collection closes all references to the capture.
/// </summary>
[Test]
public void CaptureGarbageCollection()
{
this.nativeK4a.SetImplementation(@"
k4a_result_t k4a_capture_create(k4a_capture_t* capture_handle)
{
STUB_ASSERT(capture_handle != NULL);
*capture_handle = (k4a_capture_t)0x0C001234;
return K4A_RESULT_SUCCEEDED;
}
void k4a_capture_release(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle == (k4a_capture_t)0x0C001234);
}
k4a_result_t k4a_set_debug_message_handler(
k4a_logging_message_cb_t *message_cb,
void *message_cb_context,
k4a_log_level_t min_level)
{
STUB_ASSERT(message_cb != NULL);
return K4A_RESULT_SUCCEEDED;
}
");
CallCount count = this.nativeK4a.CountCalls();
Assert.AreEqual(0, count.Calls("k4a_capture_create"));
Assert.AreEqual(0, count.Calls("k4a_capture_release"));
WeakReference capture = this.CreateWithWeakReference(() =>
{
Capture c = new Capture();
// The reference should still exist and we should have not seen close called
Assert.AreEqual(1, count.Calls("k4a_capture_create"));
Assert.AreEqual(0, count.Calls("k4a_capture_release"));
return c;
});
// The reference to the Capture object is no longer on the stack, and therefore is free to be garbage collected
// At this point capture.IsAlive is likely to be true, but not guaranteed to be
// Force garbage collection
GC.Collect(0, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
Assert.AreEqual(false, capture.IsAlive);
// k4a_capture_release should have been called automatically
Assert.AreEqual(1, count.Calls("k4a_capture_create"));
Assert.AreEqual(1, count.Calls("k4a_capture_release"));
}
/// <summary>
/// Validate the Capture.Temperature property.
/// </summary>
[Test]
public void Temperature()
{
this.SetCaptureReleaseImplementation();
this.nativeK4a.SetImplementation(@"
float k4a_capture_get_temperature_c(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle == (k4a_capture_t)0x0C001234);
return 2.5f;
}
void k4a_capture_set_temperature_c(k4a_capture_t capture_handle, float value)
{
STUB_ASSERT(capture_handle == (k4a_capture_t)0x0C001234);
STUB_ASSERT(value == 3.5f);
}
");
CallCount count = this.nativeK4a.CountCalls();
using (Capture c = new Capture())
{
// Temperature values should not be cached, so every access should call the
// native layer
Assert.AreEqual(0, count.Calls("k4a_capture_get_temperature_c"));
Assert.AreEqual(2.5f, c.Temperature);
Assert.AreEqual(1, count.Calls("k4a_capture_get_temperature_c"));
Assert.AreEqual(2.5f, c.Temperature);
Assert.AreEqual(2, count.Calls("k4a_capture_get_temperature_c"));
// Verify writes
Assert.AreEqual(0, count.Calls("k4a_capture_set_temperature_c"));
c.Temperature = 3.5f;
Assert.AreEqual(1, count.Calls("k4a_capture_set_temperature_c"));
// Verify the write is being marshaled correctly
_ = Assert.Throws(typeof(NativeFailureException), () =>
{
c.Temperature = 4.0f;
});
c.Dispose();
// Verify disposed behavior
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
c.Temperature = 4.0f;
});
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
float x = c.Temperature;
});
}
}
/// <summary>
/// Verify that methods throw ObjectDisposedException after the Capture is disposed
/// </summary>
[Test]
public void DisposeBehavior()
{
this.SetCaptureReleaseImplementation();
Capture c = new Capture();
c.Dispose();
// Verify disposed behavior
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
c.Color = null;
});
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
Image image = c.Color;
});
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
_ = c.Reference();
});
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
_ = c.DangerousGetHandle();
});
}
/// <summary>
/// Verify the Equals operator.
/// </summary>
[Test]
public void EqualsBehavior()
{
this.SetCaptureReleaseImplementation();
// Mock an implementation that allows for multiple captures
this.nativeK4a.SetImplementation(@"
#include <malloc.h>
typedef struct
{
int refcount;
} mock_capture_t;
k4a_result_t k4a_capture_create(k4a_capture_t* capture_handle)
{
mock_capture_t* capture = (mock_capture_t*)malloc(sizeof(mock_capture_t));
capture->refcount = 1;
*capture_handle = (k4a_capture_t)capture;
return K4A_RESULT_SUCCEEDED;
}
void k4a_capture_reference(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle != NULL);
mock_capture_t* capture = (mock_capture_t*)capture_handle;
capture->refcount++;
}
void k4a_capture_release(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle != NULL);
mock_capture_t* capture = (mock_capture_t*)capture_handle;
capture->refcount--;
STUB_ASSERT(capture->refcount >= 0);
}
");
Capture c1 = new Capture();
Capture c2 = new Capture();
Capture c1_ref = c1.Reference();
Capture c2_ref = c2.Reference();
// Verify the IntPtr values directly
IntPtr c1_native = c1.DangerousGetHandle().DangerousGetHandle();
IntPtr c1_ref_native = c1_ref.DangerousGetHandle().DangerousGetHandle();
IntPtr c2_native = c2.DangerousGetHandle().DangerousGetHandle();
IntPtr c2_ref_native = c2_ref.DangerousGetHandle().DangerousGetHandle();
Assert.AreNotEqual(c1_native, c2_native);
Assert.AreEqual(c1_native, c1_ref_native);
Assert.AreEqual(c2_native, c2_ref_native);
// References to each other should be equal
Assert.IsTrue(c1.NativeEquals(c1_ref));
Assert.IsTrue(c2.NativeEquals(c2_ref));
// All others are not
Assert.IsFalse(c1.NativeEquals(c2));
Assert.IsFalse(c1_ref.NativeEquals(c2_ref));
Assert.IsFalse(c1.NativeEquals(c2_ref));
Assert.IsFalse(c2_ref.NativeEquals(c1));
// Verify post dispose behavior
c1.Dispose();
Assert.IsFalse(c1.NativeEquals(c1_ref));
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
_ = c1.DangerousGetHandle();
});
c1.Dispose();
c2.Dispose();
c1_ref.Dispose();
c2_ref.Dispose();
}
/// <summary>
/// Validate the logic behind the Image properties of the capture.
/// </summary>
[Test]
public void ImageProperties()
{
this.SetCaptureReleaseImplementation();
this.SetImageMockImplementation();
this.nativeK4a.SetImplementation(@"
k4a_image_t color = 0;
k4a_image_t depth = 0;
k4a_image_t ir = 0;
k4a_image_t k4a_capture_get_color_image(k4a_capture_t capture_handle)
{
return color;
}
void k4a_capture_set_color_image(k4a_capture_t capture_handle, k4a_image_t image)
{
color = image;
}
k4a_image_t k4a_capture_get_depth_image(k4a_capture_t capture_handle)
{
return depth;
}
void k4a_capture_set_depth_image(k4a_capture_t capture_handle, k4a_image_t image)
{
depth = image;
}
k4a_image_t k4a_capture_get_ir_image(k4a_capture_t capture_handle)
{
return ir;
}
void k4a_capture_set_ir_image(k4a_capture_t capture_handle, k4a_image_t image)
{
ir = image;
}
");
CallCount count = this.nativeK4a.CountCalls();
// Verify we can create and destroy using the default constructor
using (Capture c = new Capture())
{
}
using (Capture c = new Capture())
{
using (Capture captureReference = c.Reference())
{
// Verify we have two capture objects that represent the same
// native object
Assert.IsTrue(c.NativeEquals(captureReference));
Assert.AreNotSame(c, captureReference);
Image image1 = new Image(ImageFormat.ColorBGRA32, 10, 10);
Image image1_reference = image1.Reference();
Image image2 = new Image(ImageFormat.ColorBGRA32, 10, 10);
Image image2_reference = image2.Reference();
Assert.IsFalse(image1.NativeEquals(image2));
Assert.AreNotSame(image1, image2);
// Verify our images represent the same native object, but are not the same managed wrapper
Assert.IsTrue(image1.NativeEquals(image1_reference));
Assert.AreNotSame(image1, image1_reference);
Assert.IsTrue(image2.NativeEquals(image2_reference));
Assert.AreNotSame(image2, image2_reference);
Assert.IsNull(c.Color);
// Assign image1 to the capture, it is now owned by the capture object
c.Color = image1;
// both captures should refer to the same image
Assert.IsTrue(image1.NativeEquals(c.Color));
Assert.IsFalse(image2.NativeEquals(c.Color));
Assert.IsTrue(image1.NativeEquals(captureReference.Color));
Assert.IsFalse(image2.NativeEquals(captureReference.Color));
// The reference should have its own wrapper that represents
// the same native image
Assert.IsTrue(c.Color.NativeEquals(captureReference.Color));
Assert.AreNotSame(c.Color, captureReference.Color);
c.Color = image2;
// By re-assigning the image, the capture will dispose the original image
_ = Assert.Throws(typeof(ObjectDisposedException), () =>
{
_ = image1.Size;
});
// Verify that the capture is now referring to image2.
Assert.IsTrue(image2.NativeEquals(c.Color));
Assert.AreSame(image2, c.Color);
// Verify that the reference to the capture also is updated to the same new image
Assert.IsFalse(image1_reference.NativeEquals(captureReference.Color));
Assert.IsTrue(image2.NativeEquals(captureReference.Color));
// The second capture will have its own wrapper
Assert.AreNotSame(image2, captureReference.Color);
// Assign the depth and IR properties to the same image
c.Depth = image2;
c.IR = image2;
Assert.AreSame(image2, c.Depth);
Assert.AreSame(image2, c.IR);
}
}
}
private WeakReference CreateWithWeakReference<T>(Func<T> factory)
{
return new WeakReference(factory());
}
// Helper to create basic capture create/release implementation
private void SetCaptureReleaseImplementation()
{
this.nativeK4a.SetImplementation(@"
static int captureRefCount = 0;
k4a_result_t k4a_capture_create(k4a_capture_t* capture_handle)
{
STUB_ASSERT(capture_handle != NULL);
STUB_ASSERT(captureRefCount == 0);
*capture_handle = (k4a_capture_t)0x0C001234;
captureRefCount = 1;
return K4A_RESULT_SUCCEEDED;
}
void k4a_capture_reference(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle == (k4a_capture_t)0x0C001234);
captureRefCount++;
}
void k4a_capture_release(k4a_capture_t capture_handle)
{
STUB_ASSERT(capture_handle == (k4a_capture_t)0x0C001234);
captureRefCount--;
}
k4a_result_t k4a_set_debug_message_handler(
k4a_logging_message_cb_t *message_cb,
void *message_cb_context,
k4a_log_level_t min_level)
{
STUB_ASSERT(message_cb != NULL);
return K4A_RESULT_SUCCEEDED;
}
");
}
// Helper to create basic capture create/release implementation
private void SetImageMockImplementation()
{
this.nativeK4a.SetImplementation(@"
#include <malloc.h>
typedef struct
{
int refcount;
} mock_image_t;
k4a_result_t k4a_image_create(k4a_image_format_t format,
int width_pixels,
int height_pixels,
int stride_bytes,
k4a_image_t *image_handle)
{
mock_image_t* image = (mock_image_t*)malloc(sizeof(mock_image_t));
image->refcount = 1;
*image_handle = (k4a_image_t)image;
return K4A_RESULT_SUCCEEDED;
}
void k4a_image_reference(k4a_image_t image_handle)
{
mock_image_t* image = (mock_image_t*)image_handle;
image->refcount++;
}
void k4a_image_release(k4a_image_t image_handle)
{
mock_image_t* image = (mock_image_t*)image_handle;
image->refcount--;
// Refcounts will go below zero since the mock doesn't properly
// implement the references that k4a_capture_get_*_image should add.
// STUB_ASSERT(image->refcount >= 0);
}
");
}
}
}
| 31.480237 | 123 | 0.589554 | [
"MIT"
] | 3nfinite/Azure-Kinect-Sensor-SDK | src/csharp/Tests/UnitTests/CaptureTests.cs | 15,931 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
namespace NuGet.VisualStudio.Common
{
/// <summary>
/// Add/Remove warnings/errors from the error list.
/// This persists messages once they are added.
/// </summary>
[Export(typeof(INuGetErrorList))]
[PartCreationPolicy(CreationPolicy.Shared)]
public sealed class ErrorListTableDataSource : INuGetErrorList, ITableDataSource, IDisposable
{
private readonly object _initLockObj = new object();
private readonly object _subscribeLockObj = new object();
private readonly IAsyncServiceProvider _asyncServiceProvider = AsyncServiceProvider.GlobalProvider;
private IReadOnlyList<TableSubscription> _subscriptions = new List<TableSubscription>();
private readonly List<ErrorListTableEntry> _entries = new List<ErrorListTableEntry>();
public string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource;
public string Identifier => "NuGetRestoreManagerListTable";
public string DisplayName => "NuGet_Restore_Manager_Table_Data_Source";
private IErrorList _errorList;
private ITableManager _tableManager;
private bool _initialized;
/// <summary>
/// Internal, used by tests.
/// </summary>
public ErrorListTableDataSource(IErrorList errorList, ITableManager tableManager)
{
if (errorList == null)
{
throw new ArgumentNullException(nameof(errorList));
}
if (tableManager == null)
{
throw new ArgumentNullException(nameof(tableManager));
}
_initialized = true;
_errorList = errorList;
_tableManager = tableManager;
}
public ErrorListTableDataSource()
{
}
/// <summary>
/// This method is called by the TableManager during the call to EnsureInitialized().
/// Locks should be careful to avoid a deadlock here due to this flow.
/// </summary>
public IDisposable Subscribe(ITableDataSink sink)
{
TableSubscription subscription = null;
lock (_entries)
{
subscription = new TableSubscription(sink);
if (_entries.Count > 0)
{
subscription.RunWithLock((s) =>
{
// Add all existing entries to the new sink
s.AddEntries(_entries.ToList(), removeAllEntries: false);
});
}
}
lock (_subscribeLockObj)
{
// Add valid subscriptions to the new list to start
var updatedSubscriptions = new List<TableSubscription>(_subscriptions.Where(e => !e.Disposed))
{
// Add the new subscription
subscription
};
// Apply changes
_subscriptions = updatedSubscriptions;
}
return subscription;
}
/// <summary>
/// Clear only nuget entries.
/// </summary>
public void ClearNuGetEntries()
{
if (_initialized)
{
lock (_entries)
{
// Clear all entries
_entries.Clear();
}
var subscriptions = _subscriptions;
foreach (var subscription in subscriptions)
{
if (!subscription.Disposed)
{
subscription.RunWithLock((sink) =>
{
// Find all entries in the sink that belong to NuGet, this ensures we won't miss any.
var entries = _errorList.TableControl.Entries.Where(IsNuGetEntry).ToArray();
// Remove all found entries.
sink.RemoveEntries(entries);
});
}
}
}
}
/// <summary>
/// Add error list entries
/// </summary>
public void AddNuGetEntries(params ErrorListTableEntry[] entries)
{
if (entries.Length > 0)
{
EnsureInitialized();
lock (_entries)
{
// Update the full set of entries
_entries.AddRange(entries);
}
// Add new entries to each sink
var subscriptions = _subscriptions;
foreach (var subscription in subscriptions)
{
if (!subscription.Disposed)
{
subscription.RunWithLock((sink) =>
{
// Copy the list we pass off
// Add everything to the sink
sink.AddEntries(entries.ToList(), removeAllEntries: false);
});
}
}
}
}
/// <summary>
/// Show error window if settings permit.
/// </summary>
public void BringToFrontIfSettingsPermit()
{
EnsureInitialized();
NuGetUIThreadHelper.JoinableTaskFactory.Run(async () =>
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
IVsShell vsShell = await _asyncServiceProvider.GetServiceAsync<IVsShell>();
object propertyShowTaskListOnBuildEnd;
int getPropertyReturnCode = vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_ShowTasklistOnBuildEnd, out propertyShowTaskListOnBuildEnd);
bool showErrorListOnBuildEnd = true;
if (getPropertyReturnCode == VSConstants.S_OK)
{
if (bool.TryParse(propertyShowTaskListOnBuildEnd?.ToString(), out bool result))
{
showErrorListOnBuildEnd = result;
}
}
if (showErrorListOnBuildEnd)
{
// Give the error list focus.
var vsErrorList = _errorList as IVsErrorList;
vsErrorList?.BringToFront();
}
});
}
// Lock before calling
private void EnsureInitialized()
{
if (!_initialized)
{
// Double check around locking since this is called often.
lock (_initLockObj)
{
if (!_initialized)
{
NuGetUIThreadHelper.JoinableTaskFactory.Run(async () =>
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Get the error list service from the UI thread
_errorList = await _asyncServiceProvider.GetServiceAsync<SVsErrorList, IErrorList>();
_tableManager = _errorList.TableControl.Manager;
_tableManager.AddSource(this);
_initialized = true;
});
}
}
}
}
/// <summary>
/// Internal use only, return all entries.
/// </summary>
/// <returns></returns>
public ErrorListTableEntry[] GetEntries()
{
lock (_entries)
{
return _entries.ToArray();
}
}
private static bool IsNuGetEntry(ITableEntryHandle entry)
{
object sourceObj;
return (entry != null
&& entry.TryGetValue(StandardTableColumnDefinitions.ErrorSource, out sourceObj)
&& StringComparer.Ordinal.Equals(ErrorListTableEntry.ErrorSouce, (sourceObj as string)));
}
public void Dispose()
{
if (_initialized)
{
// This does not need to be on the UI thread.
_tableManager.RemoveSource(this);
}
}
/// <summary>
/// Holds an ITableDataSink and lock.
/// </summary>
private class TableSubscription : IDisposable
{
private readonly object _lockObj = new object();
private ITableDataSink _sink;
/// <summary>
/// True if the TableManager has called Dipose on this.
/// </summary>
public bool Disposed { get; private set; }
public TableSubscription(ITableDataSink sink)
{
_sink = sink;
}
public void RunWithLock(Action<ITableDataSink> action)
{
lock (_lockObj)
{
if (!Disposed)
{
if (_sink != null)
{
action(_sink);
}
}
}
}
/// <summary>
/// When disposed we set the sink to null and later
/// all null sinks will be cleared out of the list.
/// Setting it to null also means that operations on this
/// will end up as a noop.
/// </summary>
public void Dispose()
{
lock (_lockObj)
{
_sink = null;
Disposed = true;
}
}
}
}
}
| 33.911475 | 151 | 0.507396 | [
"Apache-2.0"
] | KirillOsenkov/NuGet.Client | src/NuGet.Clients/NuGet.VisualStudio.Common/ErrorListTableDataSource.cs | 10,343 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace ASPNetCoreAngularApp.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 19.3 | 71 | 0.694301 | [
"MIT"
] | Preethamraj553/ASPNetCoreAngularApp | src/ASPNetCoreAngularApp.EntityFrameworkCore/Migrations/20180327105811_Initial.cs | 388 | C# |
int[] videoPart(string part, string total) {
int watchedTime = timeToSeconds(part);
int totalTime = timeToSeconds(total);
int div = gcd(watchedTime, totalTime);
return new int[]{watchedTime / div, totalTime / div};
}
int gcd(int a, int b){
if(b == 0)
return a;
else
return gcd(b, a%b);
}
int timeToSeconds(string time){
var split = time.Split(':');
int hoursInSeconds = int.Parse(split[0]) * 60 * 60;
int minutesInSeconds = int.Parse(split[1]) * 60;
int seconds = int.Parse(split[2]);
return hoursInSeconds + minutesInSeconds + seconds;
}
| 25.75 | 59 | 0.618123 | [
"Unlicense"
] | DKLynch/CodeSignal-Tasks | The Core/Time River/131. Video Part/videoPart.cs | 618 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Linq
{
/// <summary>
/// A lightweight hash set.
/// </summary>
/// <typeparam name="TElement">The type of the set's items.</typeparam>
internal sealed class Set<TElement>
{
/// <summary>
/// The comparer used to hash and compare items in the set.
/// </summary>
private readonly IEqualityComparer<TElement> _comparer;
/// <summary>
/// The hash buckets, which are used to index into the slots.
/// </summary>
private int[] _buckets;
/// <summary>
/// The slots, each of which store an item and its hash code.
/// </summary>
private Slot[] _slots;
/// <summary>
/// The number of items in this set.
/// </summary>
private int _count;
#if DEBUG
/// <summary>
/// Whether <see cref="Remove"/> has been called on this set.
/// </summary>
/// <remarks>
/// When <see cref="Remove"/> runs in debug builds, this flag is set to <c>true</c>.
/// Other methods assert that this flag is <c>false</c> in debug builds, because
/// they make optimizations that may not be correct if <see cref="Remove"/> is called
/// beforehand.
/// </remarks>
private bool _haveRemoved;
#endif
/// <summary>
/// Constructs a set that compares items with the specified comparer.
/// </summary>
/// <param name="comparer">
/// The comparer. If this is <c>null</c>, it defaults to <see cref="EqualityComparer{TElement}.Default"/>.
/// </param>
public Set(IEqualityComparer<TElement> comparer)
{
_comparer = comparer ?? EqualityComparer<TElement>.Default;
_buckets = new int[7];
_slots = new Slot[7];
}
/// <summary>
/// Attempts to add an item to this set.
/// </summary>
/// <param name="value">The item to add.</param>
/// <returns>
/// <c>true</c> if the item was not in the set; otherwise, <c>false</c>.
/// </returns>
public bool Add(TElement value)
{
#if DEBUG
Debug.Assert(!_haveRemoved, "This class is optimised for never calling Add after Remove. If your changes need to do so, undo that optimization.");
#endif
int hashCode = InternalGetHashCode(value);
for (int i = _buckets[hashCode % _buckets.Length] - 1; i >= 0; i = _slots[i]._next)
{
if (_slots[i]._hashCode == hashCode && _comparer.Equals(_slots[i]._value, value))
{
return false;
}
}
if (_count == _slots.Length)
{
Resize();
}
int index = _count;
_count++;
int bucket = hashCode % _buckets.Length;
_slots[index]._hashCode = hashCode;
_slots[index]._value = value;
_slots[index]._next = _buckets[bucket] - 1;
_buckets[bucket] = index + 1;
return true;
}
/// <summary>
/// Attempts to remove an item from this set.
/// </summary>
/// <param name="value">The item to remove.</param>
/// <returns>
/// <c>true</c> if the item was in the set; otherwise, <c>false</c>.
/// </returns>
public bool Remove(TElement value)
{
#if DEBUG
_haveRemoved = true;
#endif
int hashCode = InternalGetHashCode(value);
int bucket = hashCode % _buckets.Length;
int last = -1;
for (int i = _buckets[bucket] - 1; i >= 0; last = i, i = _slots[i]._next)
{
if (_slots[i]._hashCode == hashCode && _comparer.Equals(_slots[i]._value, value))
{
if (last < 0)
{
_buckets[bucket] = _slots[i]._next + 1;
}
else
{
_slots[last]._next = _slots[i]._next;
}
_slots[i]._hashCode = -1;
_slots[i]._value = default(TElement);
_slots[i]._next = -1;
return true;
}
}
return false;
}
/// <summary>
/// Expands the capacity of this set to double the current capacity, plus one.
/// </summary>
private void Resize()
{
int newSize = checked((_count * 2) + 1);
int[] newBuckets = new int[newSize];
Slot[] newSlots = new Slot[newSize];
Array.Copy(_slots, 0, newSlots, 0, _count);
for (int i = 0; i < _count; i++)
{
int bucket = newSlots[i]._hashCode % newSize;
newSlots[i]._next = newBuckets[bucket] - 1;
newBuckets[bucket] = i + 1;
}
_buckets = newBuckets;
_slots = newSlots;
}
/// <summary>
/// Creates an array from the items in this set.
/// </summary>
/// <returns>An array of the items in this set.</returns>
public TElement[] ToArray()
{
#if DEBUG
Debug.Assert(!_haveRemoved, "Optimised ToArray cannot be called if Remove has been called.");
#endif
TElement[] array = new TElement[_count];
for (int i = 0; i != array.Length; ++i)
{
array[i] = _slots[i]._value;
}
return array;
}
/// <summary>
/// Creates a list from the items in this set.
/// </summary>
/// <returns>A list of the items in this set.</returns>
public List<TElement> ToList()
{
#if DEBUG
Debug.Assert(!_haveRemoved, "Optimised ToList cannot be called if Remove has been called.");
#endif
int count = _count;
List<TElement> list = new List<TElement>(count);
for (int i = 0; i != count; ++i)
{
list.Add(_slots[i]._value);
}
return list;
}
/// <summary>
/// The number of items in this set.
/// </summary>
public int Count => _count;
/// <summary>
/// Unions this set with an enumerable.
/// </summary>
/// <param name="other">The enumerable.</param>
public void UnionWith(IEnumerable<TElement> other)
{
Debug.Assert(other != null);
foreach (TElement item in other)
{
Add(item);
}
}
/// <summary>
/// Gets the hash code of the provided value with its sign bit zeroed out, so that modulo has a positive result.
/// </summary>
/// <param name="value">The value to hash.</param>
/// <returns>The lower 31 bits of the value's hash code.</returns>
private int InternalGetHashCode(TElement value)
{
// Handle comparer implementations that throw when passed null
return (value == null) ? 0 : _comparer.GetHashCode(value) & 0x7FFFFFFF;
}
/// <summary>
/// An entry in the hash set.
/// </summary>
internal struct Slot
{
/// <summary>
/// The hash code of the item.
/// </summary>
internal int _hashCode;
/// <summary>
/// In the case of a hash collision, the index of the next slot to probe.
/// </summary>
internal int _next;
/// <summary>
/// The item held by this slot.
/// </summary>
internal TElement _value;
}
}
}
| 32.983673 | 158 | 0.503774 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Linq/src/System/Linq/Set.cs | 8,083 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DebuggerTesting.OpenDebug.Commands.Responses;
namespace DebuggerTesting.OpenDebug.Commands
{
public sealed class SetVariableCommandArgs
{
public string name;
public string value;
public int variablesReference;
}
public class SetVariableCommand : CommandWithResponse<SetVariableCommandArgs, SetVariableResponseValue>
{
public SetVariableCommand(int variablesReference, string name, string value) : base("setVariable")
{
Parameter.ThrowIfNullOrWhiteSpace(name, nameof(name));
Parameter.ThrowIfNullOrWhiteSpace(value, nameof(value));
this.Args.variablesReference = variablesReference;
this.Args.name = name;
this.Args.value = value;
}
public override string ToString()
{
return "{0} ({1}={2})".FormatInvariantWithArgs(base.ToString(), this.Args.name, this.Args.value);
}
}
}
| 34.4375 | 109 | 0.677858 | [
"MIT"
] | Hedges/MIEngine | test/DebuggerTesting/OpenDebug/Commands/SetVariableCommand.cs | 1,104 | C# |
using PwshKeePass.Commands.Database;
using PwshKeePass.Common.Extensions;
using PwshKeePass.Test.Mocks;
using Xunit;
namespace PwshKeePass.Test.Commands
{
[Collection("CmdletTests")]
public class GetKeePassDatabaseConfigurationTests : IClassFixture<PwshKeePassTestFixture>
{
private readonly PwshKeePassTestFixture _fixture;
private MockCommandRuntime commandRuntimeMock;
public GetKeePassDatabaseConfigurationTests(PwshKeePassTestFixture fixture)
{
_fixture = fixture;
commandRuntimeMock = new MockCommandRuntime();
}
[Fact]
public void TestGetKeePassDatabaseConfiguration()
{
var cmdlet = new NewKeePassDatabaseConfiguration
{
CommandRuntime = commandRuntimeMock,
KeyPath = _fixture.KeyPath,
MasterKey = _fixture.MasterKey.ConvertToSecureString(),
DatabasePath = _fixture.DatabasePath,
DatabaseProfileName = "TEST_GET",
Force = true
};
cmdlet.InvokeBeginProcessing();
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Empty(commandRuntimeMock.OutputPipeline);
commandRuntimeMock.OutputPipeline.Clear();
var getCmdlet = new GetKeePassDatabaseConfiguration
{
CommandRuntime = commandRuntimeMock,
DatabaseProfileName = "TEST_GET"
};
getCmdlet.InvokeBeginProcessing();
getCmdlet.ExecuteCmdlet();
getCmdlet.InvokeEndProcessing();
Assert.NotEmpty(commandRuntimeMock.OutputPipeline);
}
[Fact]
public void TestGetKeePassDatabaseConfigurationAll()
{
var cmdlet = new NewKeePassDatabaseConfiguration
{
CommandRuntime = commandRuntimeMock,
KeyPath = _fixture.KeyPath,
MasterKey = _fixture.MasterKey.ConvertToSecureString(),
DatabasePath = _fixture.DatabasePath,
DatabaseProfileName = "TEST_GET_ALL",
Force = true
};
cmdlet.InvokeBeginProcessing();
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Empty(commandRuntimeMock.OutputPipeline);
commandRuntimeMock.OutputPipeline.Clear();
var getCmdlet = new GetKeePassDatabaseConfiguration
{
CommandRuntime = commandRuntimeMock
};
getCmdlet.InvokeBeginProcessing();
getCmdlet.ExecuteCmdlet();
getCmdlet.InvokeEndProcessing();
Assert.NotEmpty(commandRuntimeMock.OutputPipeline);
}
}
} | 36.246753 | 93 | 0.613759 | [
"MIT"
] | dimitertodorov/PwshKeePass | PwshKeePass.Test/Commands/GetKeePassDatabaseConfigurationTests.cs | 2,791 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sce.Atf.VectorMath;
namespace MaterialTool.AdaptiveNodes
{
class RawMaterialStorage : AuthoringConcept.AdaptiveEditing.IDataBlock
{
public void SetInt(string label, int newValue)
{
SetValue(label, newValue.ToString() + "i");
}
public void SetFloat(string label, float newValue)
{
SetValue(label, newValue.ToString() + "f");
}
public void SetBool(string label, bool newValue)
{
SetValue(label, newValue ? "true" : "false");
}
public void SetFloat2(string label, Vec2F newValue)
{
SetValue(label, "{" + newValue.X.ToString() + "f, " + newValue.Y.ToString() + "f}");
}
public void SetFloat3(string label, Vec3F newValue)
{
SetValue(label, "{" + newValue.X.ToString() + "f, " + newValue.Y.ToString() + "f, " + newValue.Z.ToString() + "f}");
}
public void SetFloat4(string label, Vec4F newValue)
{
SetValue(label, "{" + newValue.X.ToString() + "f, " + newValue.Y.ToString() + "f, " + newValue.Z.ToString() + "f, " + newValue.W.ToString() + "f}");
}
private void SetValue(string label, string newValue)
{
foreach (var i in Material.ShaderConstants)
{
if (string.Compare(i.Name, label) == 0)
{
i.Value = newValue;
return;
}
}
Material.ShaderConstants.Add(GUILayer.RawMaterial.MakePropertyPair(label, newValue));
}
public bool GetBool(string label)
{
if (Material.TryGetConstantBool(label, out bool value))
{
return value;
}
return false;
}
public int GetInt(string label)
{
if (Material.TryGetConstantInt(label, out int value))
{
return value;
}
return 0; // default value when no existing value
}
public float GetFloat(string label)
{
if (Material.TryGetConstantFloat(label, out float value))
{
return value;
}
return 0.0f; // default value when no existing value
}
public Vec2F GetFloat2(string label)
{
float[] value = new float[2];
if (Material.TryGetConstantFloat2(label, value))
{
return new Vec2F(value[0], value[1]);
}
return new Vec2F(0.0f, 0.0f); // default value when no existing value
}
public Vec3F GetFloat3(string label)
{
float[] value = new float[3];
if (Material.TryGetConstantFloat3(label, value))
{
return new Vec3F(value[0], value[1], value[2]);
}
return new Vec3F(0.0f, 0.0f, 0.0f); // default value when no existing value
}
public Vec4F GetFloat4(string label)
{
float[] value = new float[4];
if (Material.TryGetConstantFloat4(label, value))
{
return new Vec4F(value[0], value[1], value[2], value[3]);
}
return new Vec4F(0.0f, 0.0f, 0.0f, 0.0f); // default value when no existing value
}
public bool HasValue(string label)
{
return Material.HasConstant(label);
}
public void RemoveValue(string label)
{
Material.RemoveConstant(label);
}
public string GetString(string label)
{
throw new InvalidOperationException("Strings not supported in RawMaterialStorage data blocks");
}
public void SetString(string label, string newValue)
{
throw new InvalidOperationException("Strings not supported in RawMaterialStorage data blocks");
}
public GUILayer.RawMaterial Material;
public string Identifier { get { return String.Empty; } }
public string TypeIdentifier { get { return String.Empty; } }
}
}
| 31.007299 | 160 | 0.536017 | [
"MIT"
] | djewsbury/XLE | Tools/MaterialTool/AdaptiveNodes/RawMaterialStorage.cs | 4,250 | C# |
namespace NetrixHtmlEditorDemo.Dialogs
{
partial class AboutDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonOK = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.labelLibVersion = new System.Windows.Forms.Label();
this.labelAppVersion = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonOK
//
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonOK.Location = new System.Drawing.Point(240, 184);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 0;
this.buttonOK.Text = "OK";
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 59);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 16);
this.label1.TabIndex = 1;
this.label1.Text = "NetrixHtmlEditorDemo.Windows Version:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 119);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(272, 32);
this.label2.TabIndex = 2;
this.label2.Text = "Copyright 2007, Weifen Luo";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(24, 81);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(128, 13);
this.label3.TabIndex = 3;
this.label3.Text = "DockPanel Suite Version:";
//
// labelLibVersion
//
this.labelLibVersion.Location = new System.Drawing.Point(148, 81);
this.labelLibVersion.Name = "labelLibVersion";
this.labelLibVersion.Size = new System.Drawing.Size(97, 13);
this.labelLibVersion.TabIndex = 4;
//
// labelAppVersion
//
this.labelAppVersion.Location = new System.Drawing.Point(129, 59);
this.labelAppVersion.Name = "labelAppVersion";
this.labelAppVersion.Size = new System.Drawing.Size(97, 13);
this.labelAppVersion.TabIndex = 5;
//
// AboutDialog
//
this.AcceptButton = this.buttonOK;
this.CancelButton = this.buttonOK;
this.ClientSize = new System.Drawing.Size(322, 215);
this.Controls.Add(this.labelAppVersion);
this.Controls.Add(this.labelLibVersion);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.buttonOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About";
this.Load += new System.EventHandler(this.AboutDialog_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label labelLibVersion;
private System.Windows.Forms.Label labelAppVersion;
}
} | 40.313559 | 107 | 0.571999 | [
"MIT"
] | andydunkel/netrix | NetrixDemo/NetrixHtmlEditorDemo/Dialogs/AboutDialog.Designer.cs | 4,757 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
#nullable enable
namespace Microsoft.EntityFrameworkCore.Design
{
/// <summary>
/// <para>
/// Service dependencies parameter class for <see cref="AnnotationCodeGenerator" />
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// <para>
/// Do not construct instances of this class directly from either provider or application code as the
/// constructor signature may change as new dependencies are added. Instead, use this type in
/// your constructor so that an instance will be created and injected automatically by the
/// dependency injection container. To create an instance with some dependent services replaced,
/// first resolve the object from the dependency injection container, then replace selected
/// services using the 'With...' methods. Do not call the constructor at any point in this process.
/// </para>
/// </summary>
public sealed record AnnotationCodeGeneratorDependencies
{
/// <summary>
/// <para>
/// Creates the service dependencies parameter object for a <see cref="AnnotationCodeGenerator" />.
/// </para>
/// <para>
/// Do not call this constructor directly from either provider or application code as it may change
/// as new dependencies are added. Instead, use this type in your constructor so that an instance
/// will be created and injected automatically by the dependency injection container. To create
/// an instance with some dependent services replaced, first resolve the object from the dependency
/// injection container, then replace selected services using the 'With...' methods. Do not call
/// the constructor at any point in this process.
/// </para>
/// <para>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </para>
/// </summary>
[EntityFrameworkInternal]
public AnnotationCodeGeneratorDependencies(
[NotNull] IRelationalTypeMappingSource relationalTypeMappingSource)
{
Check.NotNull(relationalTypeMappingSource, nameof(relationalTypeMappingSource));
RelationalTypeMappingSource = relationalTypeMappingSource;
}
/// <summary>
/// The type mapper.
/// </summary>
public IRelationalTypeMappingSource RelationalTypeMappingSource { get; [param: NotNull] init; }
}
}
| 52.651515 | 117 | 0.65295 | [
"Apache-2.0"
] | vitorelli/efcore | src/EFCore.Relational/Design/AnnotationCodeGeneratorDependencies.cs | 3,475 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace Microsoft.Tye.Hosting.Model
{
public class Application
{
public Application(string name, FileInfo source, int? dashboardPort, Dictionary<string, Service> services, ContainerEngine containerEngine)
{
Name = name;
Source = source.FullName;
ContextDirectory = source.DirectoryName!;
Services = services;
ContainerEngine = containerEngine;
DashboardPort = dashboardPort;
}
public string Id { get; } = Guid.NewGuid().ToString();
public string Name { get; }
public string Source { get; }
public string ContextDirectory { get; }
public ContainerEngine ContainerEngine { get; set; }
public int? DashboardPort { get; set; }
public Dictionary<string, Service> Services { get; }
public Dictionary<object, object> Items { get; } = new Dictionary<object, object>();
public string? Network { get; set; }
public string? BuildSolution { get; set; }
public void PopulateEnvironment(Service service, Action<string, string> set, string defaultHost = "localhost")
{
var bindings = ComputeBindings(service, defaultHost);
if (service.Description.Configuration != null)
{
// Inject normal configuration
foreach (var pair in service.Description.Configuration)
{
if (pair.Value is object)
{
set(pair.Name, pair.Value);
}
else if (pair.Source is object)
{
set(pair.Name, GetValueFromBinding(bindings, pair.Source));
}
}
}
// Inject dependency information
foreach (var binding in bindings)
{
SetBinding(binding);
}
static string GetValueFromBinding(List<EffectiveBinding> bindings, EnvironmentVariableSource source)
{
var binding = bindings.Where(b => b.Service == source.Service && b.Name == source.Binding).FirstOrDefault();
if (binding == null)
{
throw new InvalidOperationException($"Could not find binding '{source.Binding}' for service '{source.Service}'.");
}
if (source.Kind == EnvironmentVariableSource.SourceKind.Port && binding.Port != null)
{
return binding.Port.Value.ToString();
}
else if (source.Kind == EnvironmentVariableSource.SourceKind.Host)
{
return binding.Host;
}
else if (source.Kind == EnvironmentVariableSource.SourceKind.Url)
{
return $"{binding.Protocol ?? "http"}://{binding.Host}" + (binding.Port.HasValue ? (":" + binding.Port) : string.Empty);
}
else if (source.Kind == EnvironmentVariableSource.SourceKind.ConnectionString && binding.ConnectionString != null)
{
return binding.ConnectionString;
}
throw new InvalidOperationException($"Unable to resolve the desired value '{source.Kind}' from binding '{source.Binding}' for service '{source.Service}'.");
}
void SetBinding(EffectiveBinding binding)
{
var serviceName = binding.Service.ToUpper();
var configName = "";
var envName = "";
if (string.IsNullOrEmpty(binding.Name))
{
configName = serviceName;
envName = serviceName;
}
else
{
configName = $"{serviceName.ToUpper()}__{binding.Name.ToUpper()}";
envName = $"{serviceName.ToUpper()}_{binding.Name.ToUpper()}";
}
if (!string.IsNullOrEmpty(binding.ConnectionString))
{
// Special case for connection strings
var connectionString = TokenReplacement.ReplaceValues(binding.ConnectionString, binding, bindings);
set($"CONNECTIONSTRINGS__{configName}", connectionString);
return;
}
if (!string.IsNullOrEmpty(binding.Protocol))
{
// IConfiguration specific (double underscore ends up telling the configuration provider to use it as a separator)
set($"SERVICE__{configName}__PROTOCOL", binding.Protocol);
set($"{envName}_SERVICE_PROTOCOL", binding.Protocol);
}
if (binding.Port != null)
{
set($"SERVICE__{configName}__PORT", binding.Port.Value.ToString(CultureInfo.InvariantCulture));
set($"{envName}_SERVICE_PORT", binding.Port.Value.ToString(CultureInfo.InvariantCulture));
}
set($"SERVICE__{configName}__HOST", binding.Host);
set($"{envName}_SERVICE_HOST", binding.Host);
if (!String.IsNullOrEmpty(binding.Protocol)
&& !String.IsNullOrEmpty(binding.Host)
&& binding.Port != null)
{
set($"{envName}_SERVICE_ENDPOINT", $"{binding.Protocol}://{binding.Host}:{binding.Port}");
}
}
}
// Compute the list of bindings visible to `service`. This is contextual because details like
// whether `service` is a container or not will change the result.
private List<EffectiveBinding> ComputeBindings(Service service, string defaultHost)
{
var bindings = new List<EffectiveBinding>();
var isDockerRunInfo = service.Description.RunInfo is DockerRunInfo;
GetEffectiveBindings(isDockerRunInfo, defaultHost, bindings, service);
foreach (var serv in service.Description.Dependencies)
{
GetEffectiveBindings(isDockerRunInfo, defaultHost, bindings, Services[serv]);
}
return bindings;
}
private static void GetEffectiveBindings(bool isDockerRunInfo, string defaultHost, List<EffectiveBinding> bindings, Service service)
{
foreach (var b in service.Description.Bindings)
{
var protocol = b.Protocol;
var host = b.Host ?? defaultHost ?? (isDockerRunInfo ? service.Description.Name : "");
var port = b.Port;
bindings.Add(new EffectiveBinding(
service.Description.Name,
b.Name,
protocol,
host,
port,
b.ConnectionString,
service.Description.Configuration));
}
}
}
}
| 39.956757 | 172 | 0.54816 | [
"MIT"
] | Lu-Lucifer/tye | src/Microsoft.Tye.Hosting/Model/Application.cs | 7,394 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Loretta.CodeAnalysis.Text;
using Loretta.Utilities;
namespace Loretta.CodeAnalysis
{
/// <summary>
/// A wrapper for either a syntax node (<see cref="SyntaxNode"/>) or a syntax token (<see
/// cref="SyntaxToken"/>).
/// </summary>
/// <remarks>
/// Note that we do not store the token directly, we just store enough information to reconstruct it.
/// This allows us to reuse nodeOrToken as a token's parent.
/// </remarks>
[StructLayout(LayoutKind.Auto)]
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public readonly struct SyntaxNodeOrToken : IEquatable<SyntaxNodeOrToken>
{
// In a case if we are wrapping a SyntaxNode this is the SyntaxNode itself.
// In a case where we are wrapping a token, this is the token's parent.
private readonly SyntaxNode? _nodeOrParent;
// Green node for the token.
private readonly GreenNode? _token;
// Used in both node and token cases.
// When we have a node, _position == _nodeOrParent.Position.
private readonly int _position;
// Index of the token among parent's children.
// This field only makes sense if this is a token.
// For regular nodes it is set to -1 to distinguish from default(SyntaxToken)
private readonly int _tokenIndex;
internal SyntaxNodeOrToken(SyntaxNode node)
: this()
{
RoslynDebug.Assert(!node.Green.IsList, "node cannot be a list");
_position = node.Position;
_nodeOrParent = node;
_tokenIndex = -1;
}
internal SyntaxNodeOrToken(SyntaxNode? parent, GreenNode? token, int position, int index)
{
RoslynDebug.Assert(parent == null || !parent.Green.IsList, "parent cannot be a list");
RoslynDebug.Assert(token != null || (parent == null && position == 0 && index == 0), "parts must form a token");
RoslynDebug.Assert(token == null || token.IsToken, "token must be a token");
RoslynDebug.Assert(index >= 0, "index must not be negative");
RoslynDebug.Assert(parent == null || token != null, "null token cannot have parent");
_position = position;
_tokenIndex = index;
_nodeOrParent = parent;
_token = token;
}
internal string GetDebuggerDisplay()
{
return GetType().Name + " " + KindText + " " + ToString();
}
private string KindText
{
get
{
if (_token != null)
{
return _token.KindText;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.Green.KindText;
}
return "None";
}
}
/// <summary>
/// An integer representing the language specific kind of the underlying node or token.
/// </summary>
public int RawKind => _token?.RawKind ?? _nodeOrParent?.RawKind ?? 0;
/// <summary>
/// The language name that this node or token is syntax of.
/// </summary>
public string Language
{
get
{
if (_token != null)
{
return _token.Language;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.Language;
}
return string.Empty;
}
}
/// <summary>
/// Determines whether the underlying node or token represents a language construct that was actually parsed
/// from source code. Missing nodes and tokens are typically generated by the parser in error scenarios to
/// represent constructs that should have been present in the source code for the source code to compile
/// successfully but were actually missing.
/// </summary>
public bool IsMissing => _token?.IsMissing ?? _nodeOrParent?.IsMissing ?? false;
/// <summary>
/// The node that contains the underlying node or token in its Children collection.
/// </summary>
public SyntaxNode? Parent => _token != null ? _nodeOrParent : _nodeOrParent?.Parent;
internal GreenNode? UnderlyingNode => _token ?? _nodeOrParent?.Green;
internal int Position => _position;
internal GreenNode RequiredUnderlyingNode
{
get
{
RoslynDebug.Assert(UnderlyingNode is not null);
return UnderlyingNode;
}
}
/// <summary>
/// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a token.
/// </summary>
public bool IsToken => !IsNode;
/// <summary>
/// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a node.
/// </summary>
public bool IsNode => _tokenIndex < 0;
/// <summary>
/// Returns the underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a
/// token.
/// </summary>
/// <returns>
/// The underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a token.
/// </returns>
public SyntaxToken AsToken()
{
if (_token != null)
{
return new SyntaxToken(_nodeOrParent, _token, this.Position, _tokenIndex);
}
return default(SyntaxToken);
}
internal bool AsToken(out SyntaxToken token)
{
if (IsToken)
{
token = AsToken()!;
return true;
}
token = default;
return false;
}
/// <summary>
/// Returns the underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a
/// node.
/// </summary>
/// <returns>
/// The underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a node.
/// </returns>
public SyntaxNode? AsNode()
{
if (_token != null)
{
return null;
}
return _nodeOrParent;
}
internal bool AsNode([NotNullWhen(true)] out SyntaxNode? node)
{
if (IsNode)
{
node = _nodeOrParent;
return node is object;
}
node = null;
return false;
}
/// <summary>
/// The list of child nodes and tokens of the underlying node or token.
/// </summary>
public ChildSyntaxList ChildNodesAndTokens()
{
if (AsNode(out var node))
{
return node.ChildNodesAndTokens();
}
return default;
}
/// <summary>
/// The absolute span of the underlying node or token in characters, not including its leading and trailing
/// trivia.
/// </summary>
public TextSpan Span
{
get
{
if (_token != null)
{
return this.AsToken().Span;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.Span;
}
return default(TextSpan);
}
}
/// <summary>
/// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
/// </summary>
/// <remarks>
/// Slight performance improvement.
/// </remarks>
public int SpanStart
{
get
{
if (_token != null)
{
// PERF: Inlined "this.AsToken().SpanStart"
return _position + _token.GetLeadingTriviaWidth();
}
if (_nodeOrParent != null)
{
return _nodeOrParent.SpanStart;
}
return 0; //default(TextSpan).Start
}
}
/// <summary>
/// The absolute span of the underlying node or token in characters, including its leading and trailing trivia.
/// </summary>
public TextSpan FullSpan
{
get
{
if (_token != null)
{
return new TextSpan(Position, _token.FullWidth);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.FullSpan;
}
return default(TextSpan);
}
}
/// <summary>
/// Returns the string representation of this node or token, not including its leading and trailing
/// trivia.
/// </summary>
/// <returns>
/// The string representation of this node or token, not including its leading and trailing trivia.
/// </returns>
/// <remarks>The length of the returned string is always the same as Span.Length</remarks>
public override string ToString()
{
if (_token != null)
{
return _token.ToString();
}
if (_nodeOrParent != null)
{
return _nodeOrParent.ToString();
}
return string.Empty;
}
/// <summary>
/// Returns the full string representation of this node or token including its leading and trailing trivia.
/// </summary>
/// <returns>The full string representation of this node or token including its leading and trailing
/// trivia.</returns>
/// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks>
public string ToFullString()
{
if (_token != null)
{
return _token.ToFullString();
}
if (_nodeOrParent != null)
{
return _nodeOrParent.ToFullString();
}
return string.Empty;
}
/// <summary>
/// Writes the full text of this node or token to the specified TextWriter.
/// </summary>
public void WriteTo(System.IO.TextWriter writer)
{
if (_token != null)
{
_token.WriteTo(writer);
}
else
{
_nodeOrParent?.WriteTo(writer);
}
}
/// <summary>
/// Determines whether the underlying node or token has any leading trivia.
/// </summary>
public bool HasLeadingTrivia => this.GetLeadingTrivia().Count > 0;
/// <summary>
/// The list of trivia that appear before the underlying node or token in the source code and are attached to a
/// token that is a descendant of the underlying node or token.
/// </summary>
public SyntaxTriviaList GetLeadingTrivia()
{
if (_token != null)
{
return this.AsToken().LeadingTrivia;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.GetLeadingTrivia();
}
return default(SyntaxTriviaList);
}
/// <summary>
/// Determines whether the underlying node or token has any trailing trivia.
/// </summary>
public bool HasTrailingTrivia => this.GetTrailingTrivia().Count > 0;
/// <summary>
/// The list of trivia that appear after the underlying node or token in the source code and are attached to a
/// token that is a descendant of the underlying node or token.
/// </summary>
public SyntaxTriviaList GetTrailingTrivia()
{
if (_token != null)
{
return this.AsToken().TrailingTrivia;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.GetTrailingTrivia();
}
return default(SyntaxTriviaList);
}
public SyntaxNodeOrToken WithLeadingTrivia(IEnumerable<SyntaxTrivia> trivia)
{
if (_token != null)
{
return AsToken().WithLeadingTrivia(trivia);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.WithLeadingTrivia(trivia);
}
return this;
}
public SyntaxNodeOrToken WithLeadingTrivia(params SyntaxTrivia[] trivia)
{
return WithLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public SyntaxNodeOrToken WithTrailingTrivia(IEnumerable<SyntaxTrivia> trivia)
{
if (_token != null)
{
return AsToken().WithTrailingTrivia(trivia);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.WithTrailingTrivia(trivia);
}
return this;
}
public SyntaxNodeOrToken WithTrailingTrivia(params SyntaxTrivia[] trivia)
{
return WithTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
/// <summary>
/// Determines whether the underlying node or token or any of its descendant nodes, tokens or trivia have any
/// diagnostics on them.
/// </summary>
public bool ContainsDiagnostics
{
get
{
if (_token != null)
{
return _token.ContainsDiagnostics;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.ContainsDiagnostics;
}
return false;
}
}
/// <summary>
/// Gets a list of all the diagnostics in either the sub tree that has this node as its root or
/// associated with this token and its related trivia.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public IEnumerable<Diagnostic> GetDiagnostics()
{
if (_token != null)
{
return this.AsToken().GetDiagnostics();
}
if (_nodeOrParent != null)
{
return _nodeOrParent.GetDiagnostics();
}
return SpecializedCollections.EmptyEnumerable<Diagnostic>();
}
/// <summary>
/// Determines whether the underlying node or token has any descendant preprocessor directives.
/// </summary>
public bool ContainsDirectives
{
get
{
if (_token != null)
{
return _token.ContainsDirectives;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.ContainsDirectives;
}
return false;
}
}
#region Annotations
/// <summary>
/// Determines whether this node or token (or any sub node, token or trivia) as annotations.
/// </summary>
public bool ContainsAnnotations
{
get
{
if (_token != null)
{
return _token.ContainsAnnotations;
}
if (_nodeOrParent != null)
{
return _nodeOrParent.ContainsAnnotations;
}
return false;
}
}
/// <summary>
/// Determines whether this node or token has annotations of the specified kind.
/// </summary>
public bool HasAnnotations(string annotationKind)
{
if (_token != null)
{
return _token.HasAnnotations(annotationKind);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.HasAnnotations(annotationKind);
}
return false;
}
/// <summary>
/// Determines whether this node or token has annotations of the specified kind.
/// </summary>
public bool HasAnnotations(IEnumerable<string> annotationKinds)
{
if (_token != null)
{
return _token.HasAnnotations(annotationKinds);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.HasAnnotations(annotationKinds);
}
return false;
}
/// <summary>
/// Determines if this node or token has the specific annotation.
/// </summary>
public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation)
{
if (_token != null)
{
return _token.HasAnnotation(annotation);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.HasAnnotation(annotation);
}
return false;
}
/// <summary>
/// Gets all annotations of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind)
{
if (_token != null)
{
return _token.GetAnnotations(annotationKind);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.GetAnnotations(annotationKind);
}
return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>();
}
/// <summary>
/// Gets all annotations of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds)
{
if (_token != null)
{
return _token.GetAnnotations(annotationKinds);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.GetAnnotations(annotationKinds);
}
return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>();
}
/// <summary>
/// Creates a new node or token identical to this one with the specified annotations.
/// </summary>
public SyntaxNodeOrToken WithAdditionalAnnotations(params SyntaxAnnotation[] annotations)
{
return WithAdditionalAnnotations((IEnumerable<SyntaxAnnotation>)annotations);
}
/// <summary>
/// Creates a new node or token identical to this one with the specified annotations.
/// </summary>
public SyntaxNodeOrToken WithAdditionalAnnotations(IEnumerable<SyntaxAnnotation> annotations)
{
if (annotations == null)
{
throw new ArgumentNullException(nameof(annotations));
}
if (_token != null)
{
return this.AsToken().WithAdditionalAnnotations(annotations);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.WithAdditionalAnnotations(annotations);
}
return this;
}
/// <summary>
/// Creates a new node or token identical to this one without the specified annotations.
/// </summary>
public SyntaxNodeOrToken WithoutAnnotations(params SyntaxAnnotation[] annotations)
{
return WithoutAnnotations((IEnumerable<SyntaxAnnotation>)annotations);
}
/// <summary>
/// Creates a new node or token identical to this one without the specified annotations.
/// </summary>
public SyntaxNodeOrToken WithoutAnnotations(IEnumerable<SyntaxAnnotation> annotations)
{
if (annotations == null)
{
throw new ArgumentNullException(nameof(annotations));
}
if (_token != null)
{
return this.AsToken().WithoutAnnotations(annotations);
}
if (_nodeOrParent != null)
{
return _nodeOrParent.WithoutAnnotations(annotations);
}
return this;
}
/// <summary>
/// Creates a new node or token identical to this one without annotations of the specified kind.
/// </summary>
public SyntaxNodeOrToken WithoutAnnotations(string annotationKind)
{
if (annotationKind == null)
{
throw new ArgumentNullException(nameof(annotationKind));
}
if (this.HasAnnotations(annotationKind))
{
return this.WithoutAnnotations(this.GetAnnotations(annotationKind));
}
return this;
}
#endregion
/// <summary>
/// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this
/// <see cref="SyntaxNodeOrToken"/>.
/// </summary>
public bool Equals(SyntaxNodeOrToken other)
{
// index replaces position to ensure equality. Assert if offset affects equality.
RoslynDebug.Assert(
(_nodeOrParent == other._nodeOrParent && _token == other._token && _position == other._position && _tokenIndex == other._tokenIndex) ==
(_nodeOrParent == other._nodeOrParent && _token == other._token && _tokenIndex == other._tokenIndex));
return _nodeOrParent == other._nodeOrParent &&
_token == other._token &&
_tokenIndex == other._tokenIndex;
}
/// <summary>
/// Determines whether two <see cref="SyntaxNodeOrToken"/>s are equal.
/// </summary>
public static bool operator ==(SyntaxNodeOrToken left, SyntaxNodeOrToken right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="SyntaxNodeOrToken"/>s are unequal.
/// </summary>
public static bool operator !=(SyntaxNodeOrToken left, SyntaxNodeOrToken right)
{
return !left.Equals(right);
}
/// <summary>
/// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this
/// <see cref="SyntaxNodeOrToken"/>.
/// </summary>
public override bool Equals(object? obj)
{
return obj is SyntaxNodeOrToken token && Equals(token);
}
/// <summary>
/// Serves as hash function for <see cref="SyntaxNodeOrToken"/>.
/// </summary>
public override int GetHashCode()
{
return Hash.Combine(_nodeOrParent, Hash.Combine(_token, _tokenIndex));
}
/// <summary>
/// Determines if the two nodes or tokens are equivalent.
/// </summary>
public bool IsEquivalentTo(SyntaxNodeOrToken other)
{
if (this.IsNode != other.IsNode)
{
return false;
}
var thisUnderlying = this.UnderlyingNode;
var otherUnderlying = other.UnderlyingNode;
return (thisUnderlying == otherUnderlying) || (thisUnderlying != null && thisUnderlying.IsEquivalentTo(otherUnderlying));
}
/// <summary>
/// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied token.
/// </summary>
/// <param name="token">The input token.</param>
/// <returns>
/// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied token.
/// </returns>
public static implicit operator SyntaxNodeOrToken(SyntaxToken token)
{
return new SyntaxNodeOrToken(token.Parent, token.Node, token.Position, token.Index);
}
/// <summary>
/// Returns the underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodeOrToken">
/// The input <see cref="SyntaxNodeOrToken"/>.
/// </param>
/// <returns>
/// The underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>.
/// </returns>
public static explicit operator SyntaxToken(SyntaxNodeOrToken nodeOrToken)
{
return nodeOrToken.AsToken();
}
/// <summary>
/// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied node.
/// </summary>
/// <param name="node">The input node.</param>
/// <returns>
/// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied node.
/// </returns>
public static implicit operator SyntaxNodeOrToken(SyntaxNode? node)
{
return node is object
? new SyntaxNodeOrToken(node)
: default;
}
/// <summary>
/// Returns the underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodeOrToken">
/// The input <see cref="SyntaxNodeOrToken"/>.
/// </param>
/// <returns>
/// The underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>.
/// </returns>
public static explicit operator SyntaxNode?(SyntaxNodeOrToken nodeOrToken)
{
return nodeOrToken.AsNode();
}
/// <summary>
/// SyntaxTree which contains current SyntaxNodeOrToken.
/// </summary>
public SyntaxTree? SyntaxTree => _nodeOrParent?.SyntaxTree;
/// <summary>
/// Get the location of this node or token.
/// </summary>
public Location? GetLocation()
{
if (AsToken(out var token))
{
return token.GetLocation();
}
return _nodeOrParent?.GetLocation();
}
#region Directive Lookup
// Get all directives under the node and its children in source code order.
internal IList<TDirective> GetDirectives<TDirective>(Func<TDirective, bool>? filter = null)
where TDirective : SyntaxNode
{
List<TDirective>? directives = null;
GetDirectives(this, filter, ref directives);
return directives ?? SpecializedCollections.EmptyList<TDirective>();
}
private static void GetDirectives<TDirective>(in SyntaxNodeOrToken node, Func<TDirective, bool>? filter, ref List<TDirective>? directives)
where TDirective : SyntaxNode
{
if (node._token != null && node.AsToken() is var token && token.ContainsDirectives)
{
GetDirectives(token.LeadingTrivia, filter, ref directives);
GetDirectives(token.TrailingTrivia, filter, ref directives);
}
else if (node._nodeOrParent != null)
{
GetDirectives(node._nodeOrParent, filter, ref directives);
}
}
private static void GetDirectives<TDirective>(SyntaxNode node, Func<TDirective, bool>? filter, ref List<TDirective>? directives)
where TDirective : SyntaxNode
{
foreach (var trivia in node.DescendantTrivia(node => node.ContainsDirectives, descendIntoTrivia: true))
{
_ = GetDirectivesInTrivia(trivia, filter, ref directives);
}
}
private static bool GetDirectivesInTrivia<TDirective>(in SyntaxTrivia trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives)
where TDirective : SyntaxNode
{
if (trivia.IsDirective)
{
if (trivia.GetStructure() is TDirective directive &&
filter?.Invoke(directive) != false)
{
if (directives == null)
{
directives = new List<TDirective>();
}
directives.Add(directive);
}
return true;
}
return false;
}
private static void GetDirectives<TDirective>(in SyntaxTriviaList trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives)
where TDirective : SyntaxNode
{
foreach (var tr in trivia)
{
if (!GetDirectivesInTrivia(tr, filter, ref directives) && tr.GetStructure() is SyntaxNode node)
{
GetDirectives(node, filter, ref directives);
}
}
}
#endregion
internal int Width => _token?.Width ?? _nodeOrParent?.Width ?? 0;
internal int FullWidth => _token?.FullWidth ?? _nodeOrParent?.FullWidth ?? 0;
internal int EndPosition => _position + this.FullWidth;
public static int GetFirstChildIndexSpanningPosition(SyntaxNode node, int position)
{
if (!node.FullSpan.IntersectsWith(position))
{
throw new ArgumentException("Must be within node's FullSpan", nameof(position));
}
return GetFirstChildIndexSpanningPosition(node.ChildNodesAndTokens(), position);
}
internal static int GetFirstChildIndexSpanningPosition(ChildSyntaxList list, int position)
{
int lo = 0;
int hi = list.Count - 1;
while (lo <= hi)
{
int r = lo + ((hi - lo) >> 1);
var m = list[r];
if (position < m.Position)
{
hi = r - 1;
}
else
{
if (position == m.Position)
{
// If we hit a zero width node, move left to the first such node (or the
// first one in the list)
for (; r > 0 && list[r - 1].FullWidth == 0; r--)
{
;
}
return r;
}
if (position >= m.EndPosition)
{
lo = r + 1;
continue;
}
return r;
}
}
throw ExceptionUtilities.Unreachable;
}
public SyntaxNodeOrToken GetNextSibling()
{
var parent = this.Parent;
if (parent == null)
{
return default(SyntaxNodeOrToken);
}
var siblings = parent.ChildNodesAndTokens();
return siblings.Count < 8
? GetNextSiblingFromStart(siblings)
: GetNextSiblingWithSearch(siblings);
}
public SyntaxNodeOrToken GetPreviousSibling()
{
if (this.Parent != null)
{
// walk reverse in parent's child list until we find ourself
// and then return the next child
var returnNext = false;
foreach (var child in this.Parent.ChildNodesAndTokens().Reverse())
{
if (returnNext)
{
return child;
}
if (child == this)
{
returnNext = true;
}
}
}
return default(SyntaxNodeOrToken);
}
private SyntaxNodeOrToken GetNextSiblingFromStart(ChildSyntaxList siblings)
{
var returnNext = false;
foreach (var sibling in siblings)
{
if (returnNext)
{
return sibling;
}
if (sibling == this)
{
returnNext = true;
}
}
return default(SyntaxNodeOrToken);
}
private SyntaxNodeOrToken GetNextSiblingWithSearch(ChildSyntaxList siblings)
{
var firstIndex = GetFirstChildIndexSpanningPosition(siblings, _position);
var count = siblings.Count;
var returnNext = false;
for (int i = firstIndex; i < count; i++)
{
if (returnNext)
{
return siblings[i];
}
if (siblings[i] == this)
{
returnNext = true;
}
}
return default(SyntaxNodeOrToken);
}
}
}
| 32.035611 | 151 | 0.520715 | [
"MIT"
] | 44wolfrevOkcatS/Loretta | src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs | 33,287 | C# |
namespace GameLogic.Rules
{
public class SelectorArguments
{
public float MinLength { get; set; }
public float MaxLength { get; set; }
}
}
| 16.9 | 44 | 0.609467 | [
"MIT"
] | Selinux24/SharpDX-Tests | Samples/Z Game Logic/Rules/SelectorArguments.cs | 171 | C# |
/*
* [The "BSD licence"]
* Copyright (c) 2011 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace TypeSql.Antlr.Runtime.Tree
{
/** <summary>
* A TreeAdaptor that works with any Tree implementation. It provides
* really just factory methods; all the work is done by BaseTreeAdaptor.
* If you would like to have different tokens created than ClassicToken
* objects, you need to override this and then set the parser tree adaptor to
* use your subclass.
* </summary>
*
* <remarks>
* To get your parser to build nodes of a different type, override
* create(Token), errorNode(), and to be safe, YourTreeClass.dupNode().
* dupNode is called to duplicate nodes during rewrite operations.
* </remarks>
*/
public class CommonTreeAdaptor : BaseTreeAdaptor
{
public override object Create( IToken payload )
{
return new CommonTree( payload );
}
/** <summary>
* Tell me how to create a token for use with imaginary token nodes.
* For example, there is probably no input symbol associated with imaginary
* token DECL, but you need to create it as a payload or whatever for
* the DECL node as in ^(DECL type ID).
* </summary>
*
* <remarks>
* If you care what the token payload objects' type is, you should
* override this method and any other createToken variant.
* </remarks>
*/
public override IToken CreateToken( int tokenType, string text )
{
return new CommonToken( tokenType, text );
}
/** <summary>
* Tell me how to create a token for use with imaginary token nodes.
* For example, there is probably no input symbol associated with imaginary
* token DECL, but you need to create it as a payload or whatever for
* the DECL node as in ^(DECL type ID).
* </summary>
*
* <remarks>
* This is a variant of createToken where the new token is derived from
* an actual real input token. Typically this is for converting '{'
* tokens to BLOCK etc... You'll see
*
* r : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ;
*
* If you care what the token payload objects' type is, you should
* override this method and any other createToken variant.
* </remarks>
*/
public override IToken CreateToken( IToken fromToken )
{
return new CommonToken( fromToken );
}
/** <summary>
* What is the Token associated with this node? If
* you are not using CommonTree, then you must
* override this in your own adaptor.
* </summary>
*/
public override IToken GetToken( object t )
{
if ( t is CommonTree )
{
return ( (CommonTree)t ).Token;
}
return null; // no idea what to do
}
}
}
| 41.575221 | 85 | 0.621115 | [
"MIT"
] | MJRichardson/TypeSql | TypeSql/Parsing/Antlr/Antlr3.Runtime/Tree/CommonTreeAdaptor.cs | 4,698 | C# |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Collections.Generic;
using System.Drawing;
namespace ICSharpCode.TextEditor.Document
{
public enum TextMarkerType
{
Invisible,
SolidBlock,
Underlined,
WaveLine
}
/// <summary>
/// Marks a part of a document.
/// </summary>
public class TextMarker : ISegment
{
[CLSCompliant(false)]
protected int offset = -1;
[CLSCompliant(false)]
protected int length = -1;
#region ICSharpCode.TextEditor.Document.ISegment interface implementation
public int Offset
{
get
{
return offset;
}
set
{
offset = value;
}
}
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
#endregion
public override string ToString()
{
return String.Format("[TextMarker: Offset = {0}, Length = {1}, Type = {2}]",
offset,
length,
textMarkerType);
}
TextMarkerType textMarkerType;
Color color;
Color foreColor;
string toolTip = null;
bool overrideForeColor = false;
public TextMarkerType TextMarkerType {
get {
return textMarkerType;
}
}
public Color Color {
get {
return color;
}
}
public Color ForeColor {
get {
return foreColor;
}
}
public bool OverrideForeColor {
get {
return overrideForeColor;
}
}
/// <summary>
/// Marks the text segment as read-only.
/// </summary>
public bool IsReadOnly { get; set; }
public string ToolTip {
get {
return toolTip;
}
set {
toolTip = value;
}
}
/// <summary>
/// Gets the last offset that is inside the marker region.
/// </summary>
public int EndOffset {
get {
return offset + length - 1;
}
}
public TextMarker(int offset, int length, TextMarkerType textMarkerType) : this(offset, length, textMarkerType, Color.Red)
{
}
public TextMarker(int offset, int length, TextMarkerType textMarkerType, Color color)
{
if (length < 1) length = 1;
this.offset = offset;
this.length = length;
this.textMarkerType = textMarkerType;
this.color = color;
}
public TextMarker(int offset, int length, TextMarkerType textMarkerType, Color color, Color foreColor)
{
if (length < 1) length = 1;
this.offset = offset;
this.length = length;
this.textMarkerType = textMarkerType;
this.color = color;
this.foreColor = foreColor;
this.overrideForeColor = true;
}
}
}
| 21.604167 | 124 | 0.538734 | [
"MIT"
] | chenrensong/Coding4Fun.WinFormUI | src/TextEditor/Document/MarkerStrategy/TextMarker.cs | 3,113 | 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;
namespace Dashboard
{
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();
}
}
} | 30.697674 | 106 | 0.688636 | [
"MIT"
] | extragornax/dashboard_epitech | Dashboard_api/Startup.cs | 1,320 | C# |
using System;
namespace BuffettCodeCommon.Period
{
public class ComparablePeriodUtil
{
public static int GetGap(IPeriod start, IPeriod end)
{
if (start is FiscalQuarterPeriod sfq && end is FiscalQuarterPeriod efq)
{
return GetGap(sfq, efq);
}
else if (start is DayPeriod sd && end is DayPeriod ed)
{
return GetGap(sd, ed);
}
else
{
throw new NotImplementedException();
}
}
public static int GetGap(FiscalQuarterPeriod start, FiscalQuarterPeriod end) => (int)(end.Year - start.Year) * 4 + (int)(end.Quarter - start.Quarter);
public static int GetGap(DayPeriod start, DayPeriod end) => (int)end.Value.Subtract(start.Value).TotalDays;
}
} | 30.25 | 158 | 0.567887 | [
"Apache-2.0"
] | BuffettCode/buffett-code-api-clinet-excel | BuffettCodeCommon/Period/ComparablePeriodUtil.cs | 847 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Todo
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 27.291667 | 70 | 0.709924 | [
"MIT"
] | hamed-farag/PushNotification | Todo/Todo/Global.asax.cs | 657 | C# |
using System;
namespace Ultraviolet.Input
{
/// <summary>
/// Represents a factory method which constructs instances of the <see cref="SoftwareKeyboardService"/> class.
/// </summary>
/// <returns>The instance of <see cref="SoftwareKeyboardService"/> that was created.</returns>
public delegate SoftwareKeyboardService SoftwareKeyboardServiceFactory();
/// <summary>
/// Represents a service which controls the software keyboard, if one is available on the current platform.
/// </summary>
public abstract class SoftwareKeyboardService
{
/// <summary>
/// Creates a new instance of the <see cref="SoftwareKeyboardService"/> class.
/// </summary>
/// <returns>The instance of <see cref="SoftwareKeyboardService"/> that was created.</returns>
public static SoftwareKeyboardService Create()
{
var uv = UltravioletContext.DemandCurrent();
return uv.GetFactoryMethod<SoftwareKeyboardServiceFactory>()();
}
/// <summary>
/// Shows the software keyboard, if one is available.
/// </summary>
/// <param name="mode">The display mode of the software keyboard.</param>
/// <returns><see langword="true"/> if the software keyboard was shown; otherwise, <see langword="false"/>.</returns>
public abstract Boolean ShowSoftwareKeyboard(KeyboardMode mode);
/// <summary>
/// Hides the software keyboard.
/// </summary>
/// <returns><see langword="true"/> if the software keyboard was hidden; otherwise, false.</returns>
public abstract Boolean HideSoftwareKeyboard();
/// <summary>
/// Gets or sets the region on the screen at which text is currently being entered.
/// </summary>
public abstract Rectangle? TextInputRegion { get; set; }
/// <summary>
/// Informs the Ultraviolet context that the software keyboard is being shown by publishing
/// a <see cref="UltravioletMessages.SoftwareKeyboardShown"/> message.
/// </summary>
protected void OnShowingSoftwareKeyboard()
{
var uv = UltravioletContext.DemandCurrent();
uv.Messages.Publish(UltravioletMessages.SoftwareKeyboardShown, null);
}
/// <summary>
/// Informs the Ultraviolet context that the software keyboard is being hidden by publishing
/// a <see cref="UltravioletMessages.SoftwareKeyboardHidden"/> message.
/// </summary>
protected void OnHidingSoftwareKeyboard()
{
var uv = UltravioletContext.DemandCurrent();
uv.Messages.Publish(UltravioletMessages.SoftwareKeyboardHidden, null);
}
}
}
| 42.276923 | 125 | 0.64556 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet/Shared/Input/SoftwareKeyboardService.cs | 2,750 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WindowsManagementAppHealthSummaryRequestBuilder.
/// </summary>
public partial class WindowsManagementAppHealthSummaryRequestBuilder : EntityRequestBuilder, IWindowsManagementAppHealthSummaryRequestBuilder
{
/// <summary>
/// Constructs a new WindowsManagementAppHealthSummaryRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public WindowsManagementAppHealthSummaryRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new IWindowsManagementAppHealthSummaryRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new IWindowsManagementAppHealthSummaryRequest Request(IEnumerable<Option> options)
{
return new WindowsManagementAppHealthSummaryRequest(this.RequestUrl, this.Client, options);
}
}
}
| 37.236364 | 153 | 0.603516 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WindowsManagementAppHealthSummaryRequestBuilder.cs | 2,048 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Maui.Animations;
using Microsoft.Maui.Handlers;
namespace Microsoft.Maui.Controls.Core.UnitTests
{
class AnimationReadyHandler : AnimationReadyHandler<BlockingTicker>
{
public AnimationReadyHandler()
: base(new TestAnimationManager(new BlockingTicker()))
{
}
}
class AnimationReadyHandlerAsync : AnimationReadyHandler<AsyncTicker>
{
public AnimationReadyHandlerAsync()
: base(new TestAnimationManager(new AsyncTicker()))
{
}
}
class AnimationReadyHandler<TTicker> : ViewHandler<IView, object>
where TTicker : ITicker, new()
{
public AnimationReadyHandler(IAnimationManager animationManager)
: base(new PropertyMapper<IView>())
{
SetMauiContext(new AnimationReadyMauiContext(animationManager));
}
public static AnimationReadyHandler<TTicker> Prepare<T>(params T[] views)
where T : View
{
var handler = new AnimationReadyHandler<TTicker>(new TestAnimationManager(new TTicker()));
foreach (var view in views)
view.Handler = handler;
return handler;
}
public static T Prepare<T>(T view, out AnimationReadyHandler<TTicker> handler)
where T : View
{
handler = new AnimationReadyHandler<TTicker>(new TestAnimationManager(new TTicker()));
view.Handler = handler;
return view;
}
public static T Prepare<T>(T view)
where T : View
{
view.Handler = new AnimationReadyHandler();
return view;
}
protected override object CreatePlatformView() => new();
public IAnimationManager AnimationManager => ((AnimationReadyMauiContext)MauiContext).AnimationManager;
class AnimationReadyMauiContext : IMauiContext, IServiceProvider
{
readonly IAnimationManager _animationManager;
public AnimationReadyMauiContext(IAnimationManager manager = null)
{
_animationManager = manager ?? new TestAnimationManager();
}
public IServiceProvider Services => this;
public IMauiHandlersFactory Handlers => throw new NotImplementedException();
public IAnimationManager AnimationManager => _animationManager;
public object GetService(Type serviceType)
{
if (serviceType == typeof(IAnimationManager))
return _animationManager;
throw new NotSupportedException();
}
}
}
static class AnimationReadyWindowExtensions
{
public static async Task DisableTicker(this AnimationReadyHandler<AsyncTicker> handler)
{
await Task.Delay(32);
((AsyncTicker)handler.AnimationManager.Ticker).SetEnabled(false);
}
public static async Task EnableTicker(this AnimationReadyHandler<AsyncTicker> handler)
{
await Task.Delay(32);
((AsyncTicker)handler.AnimationManager.Ticker).SetEnabled(true);
}
}
} | 25.214953 | 105 | 0.751668 | [
"MIT"
] | 10088/maui | src/Controls/tests/Core.UnitTests/TestClasses/AnimationReadyHandler.cs | 2,700 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace zwg_china.model
{
/// <summary>
/// 注册奖励的参与记录
/// </summary>
public class RewardForRegisterRecord : RecordingTimeModelBase
{
#region 属性
/// <summary>
/// 用户
/// </summary>
public virtual Author Owner { get; set; }
/// <summary>
/// 对应的计划(快照)
/// </summary>
public virtual RewardForRegisterSnapshot Plan { get; set; }
/// <summary>
/// 奖品类型
/// </summary>
public PrizesOfActivityType PrizeType { get; set; }
/// <summary>
/// 奖励数额
/// </summary>
public double Sum { get; set; }
#endregion
#region 构造方法
/// <summary>
/// 实例化一个新的注册奖励的参与记录
/// </summary>
public RewardForRegisterRecord()
{
}
/// <summary>
/// 实例化一个新的注册奖励的参与记录
/// </summary>
/// <param name="owner">用户</param>
/// <param name="plan">对应的计划(快照)</param>
public RewardForRegisterRecord(Author owner, RewardForRegisterSnapshot plan)
{
this.Owner = owner;
this.Plan = plan;
this.PrizeType = plan.PrizeType;
this.Sum = plan.Sum;
}
#endregion
}
}
| 22.47619 | 85 | 0.487994 | [
"Apache-2.0"
] | returnanapple/zwg-china-iworld | zwg-china.activity.model/RewardForRegisterRecord.cs | 1,572 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RevisaoEstoque.Controllers
{
public class RelatorioController : Controller
{
[Authorize]
public ActionResult PosicaoEstoque()
{
return View();
}
[Authorize]
public ActionResult Ressuprimento()
{
return View();
}
}
} | 19.727273 | 49 | 0.601382 | [
"MIT"
] | igorandrade12/Sistema-de-Cadastro-MVC | RevisaoEstoque/RevisaoEstoque/Controllers/RelatorioController.cs | 436 | C# |
namespace teste_03
{
partial class Form1
{
/// <summary>
/// Variável de designer necessária.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpar os recursos que estão sendo usados.
/// </summary>
/// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código gerado pelo Windows Form Designer
/// <summary>
/// Método necessário para suporte ao Designer - não modifique
/// o conteúdo deste método com o editor de código.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(98, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "teste";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(311, 238);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
}
}
| 32.403226 | 124 | 0.550523 | [
"MIT"
] | adrianosan/teste | teste 03/teste 03/Form1.Designer.cs | 2,023 | C# |
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Models.Manager
{
public class ManagerClaim : IdentityUserClaim<string>
{
}
}
| 17.5 | 57 | 0.757143 | [
"MIT"
] | Smahdie/Blog | src/Core/Models/Manager/ManagerClaim.cs | 212 | C# |
using System;
using System.Xml;
namespace pjank.BossaAPI.Fixml
{
public enum MDRejectReason
{
UnknownSymbol = '0', // nieznany walor
DuplicateRequestId = '1', // duplikat MDReqID
UnsupportedRequestType = '4', // błąd w polu SubReqTyp
UnsupportedMarketDepth = '5', // niewspierana liczba ofert
UnsupportedEntryType = '8' // niewspierane notowania
}
internal static class MDRejResnUtil
{
public static MDRejectReason Read(XmlElement xml, string name)
{
char ch = FixmlUtil.ReadChar(xml, name);
if (!Enum.IsDefined(typeof(MDRejectReason), (MDRejectReason)ch))
FixmlUtil.Error(xml, name, ch, "- unknown MDRejectReason");
return (MDRejectReason)ch;
}
}
}
| 28.423077 | 68 | 0.673884 | [
"Apache-2.0"
] | L-Sypniewski/bossa-api.net | BossaAPI/src/Networking/Fixml/MarketData/MDRejectReason.cs | 743 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using FileHelpers;
namespace nCode.Data
{
/// <summary>
///
/// </summary>
/// <typeparam name="B">FileHelpers boddy-class.</typeparam>
public abstract class FileHelpersImportManager<B> : ImportManager, IFileImportManager where B : class
{
public FileHelpersImportManager()
{
ShowDelimiterOption = false;
ShowHeaderOption = false;
}
protected FileHelperEngine<B> Engine { get; private set; }
public override void Import(IDictionary<string, object> options)
{
/* Validate Options. */
if (!options.ContainsKey("dataStream") || !(options["dataStream"] is Stream))
throw new ArgumentException("Options is expected to contain a 'dataStream' property.", "options");
if (!options.ContainsKey("encoding") || !(options["encoding"] is Encoding))
throw new ArgumentException("Options is expected to contain a 'encoding' property.", "options");
var dataStream = (Stream)options["dataStream"];
var encoding = (Encoding)options["encoding"];
//Delimiter delimiter;
//bool firstColumnIsHeaders;
Engine = new FileHelperEngine<B>();
IEnumerable<B> data;
/* Parse the stream. */
using (StreamReader reader = new StreamReader(dataStream, encoding))
{
try
{
data = Engine.ReadStream(reader);
}
catch (ConvertException ex)
{
Log.Warn(string.Format("FileHelpersImportManager Type: '{0}' failed during import.", GetType().AssemblyQualifiedName), ex);
throw new ImportFormatException(ex.Message, lineNumber: ex.LineNumber, data: ex.FieldStringValue, innerException: ex);
}
catch (FileHelpersException ex)
{
Log.Warn(string.Format("FileHelpersImportManager Type: '{0}' failed during import.", GetType().AssemblyQualifiedName), ex);
throw new ImportFormatException(ex.Message, innerException: ex);
}
}
ProccessData(data);
}
public abstract void ProccessData(IEnumerable<B> data);
public virtual bool ShowDelimiterOption { get; protected set; }
public virtual bool ShowHeaderOption { get; protected set; }
}
}
| 37.267606 | 144 | 0.573696 | [
"Unlicense"
] | niklascp/ncode | src/nCode/Data/FileHelpersImportManager.cs | 2,648 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XF_ListView.Models;
namespace XF_ListView
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListView_Exercicio1 : ContentPage
{
public ListView_Exercicio1()
{
InitializeComponent();
//List<String> itens = new List<string>()
listview.ItemsSource = new List<String>()
{
"Abacate","Abacaxi","Banana","Caju","Goiaba","Laranja","Melancia","Pêssego","Tangerina"
};
//listview.ItemsSource = itens;
}
private void listview_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
DisplayAlert("Item Selecionado: ", e.SelectedItem.ToString(), "OK");
}
}
}
| 26.085714 | 102 | 0.634173 | [
"MIT"
] | LuizMarcello/XF_ListView | XF_ListView/XF_ListView/XF_ListView/ListView_Exercicio1.xaml.cs | 916 | C# |
// Copyright (c) János Janka. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace Partnerinfo
{
/// <summary>
/// Adds extensions methods to the <see cref="Controller" /> class to make it easier to return a <see cref="Partnerinfo.OperationResult" /> with a model.
/// </summary>
public static class OperationErrorControllerExtensions
{
/// <summary>
/// Creates a <see cref="OperationErrorResult" /> object that renders a view to the response.
/// </summary>
/// <param name="controller">The controller to extend.</param>
/// <param name="result">The result.</param>
/// <returns>
/// The <see cref="OperationErrorResult" /> result that renders a view to the response.
/// </returns>
public static OperationErrorResult OperationError(this Controller controller, OperationResult result)
{
return new OperationErrorResult(result);
}
}
} | 41.692308 | 157 | 0.658672 | [
"Apache-2.0"
] | janosjanka/Partnerinfo | src/Partnerinfo.Web.Api/OperationErrorControllerExtensions.cs | 1,087 | 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("UTRS1671Allocator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("UTRS")]
[assembly: AssemblyProduct("UTRS1671Allocator")]
[assembly: AssemblyCopyright("Copyright © UTRS 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//[assembly: AssemblyKeyFile("ATML1671Allocator.snk")]
// 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("fedefc3b-12ed-405a-be51-616ccbd2a3b0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.675676 | 85 | 0.732226 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | UtrsSoftware/ATMLWorkBench | ATML1671Allocator/Properties/AssemblyInfo.cs | 1,508 | C# |
namespace YesterdayApi.Core.Identity
{
public interface ITokenDecoder
{
int GetUserId(string authHeader);
}
}
| 16.25 | 41 | 0.684615 | [
"MIT"
] | AlexTorianyk/yesterday-api | YesterdayApi/Core/Identity/ITokenDecoder.cs | 130 | C# |
using Moq;
using Prism.Forms.Tests.Mocks.Modules;
using Prism.Modularity;
using Xunit;
namespace Prism.Forms.Tests.Modularity
{
public class ModuleManagerExtensionsFixture
{
[Fact]
public void ModuleManagerExposesIModuleCatalogModules()
{
var modules = new[]
{
new ModuleInfo(typeof(ModuleA))
};
var moduleCatalogMock = new Mock<IModuleCatalog>();
moduleCatalogMock.Setup(c => c.Modules).Returns(modules);
IModuleManager manager = new ModuleManager(Mock.Of<IModuleInitializer>(), moduleCatalogMock.Object);
Assert.Same(modules, manager.Modules);
}
[Fact]
public void ModuleManagerReturnsCorrectModuleStateWithGeneric()
{
IModuleInfo moduleInfo = new ModuleInfo(typeof(ModuleA));
var moduleCatalogMock = new Mock<IModuleCatalog>();
moduleCatalogMock.Setup(c => c.Modules).Returns(new[] { moduleInfo });
IModuleManager manager = new ModuleManager(Mock.Of<IModuleInitializer>(), moduleCatalogMock.Object);
Assert.Equal(moduleInfo.State, manager.GetModuleState<ModuleA>());
moduleInfo.State = ModuleState.LoadingTypes;
Assert.Equal(moduleInfo.State, manager.GetModuleState<ModuleA>());
}
[Fact]
public void ModuleManagerReturnsCorrectModuleStateWithName()
{
IModuleInfo moduleInfo = new ModuleInfo(typeof(ModuleA));
var moduleCatalogMock = new Mock<IModuleCatalog>();
moduleCatalogMock.Setup(c => c.Modules).Returns(new[] { moduleInfo });
IModuleManager manager = new ModuleManager(Mock.Of<IModuleInitializer>(), moduleCatalogMock.Object);
Assert.Equal(moduleInfo.State, manager.GetModuleState(nameof(ModuleA)));
moduleInfo.State = ModuleState.LoadingTypes;
Assert.Equal(moduleInfo.State, manager.GetModuleState(nameof(ModuleA)));
}
[Fact]
public void ModuleManagerReturnsCorrectInitializationStateWithGeneric()
{
IModuleInfo moduleInfo = new ModuleInfo(typeof(ModuleA));
var moduleCatalogMock = new Mock<IModuleCatalog>();
moduleCatalogMock.Setup(c => c.Modules).Returns(new[] { moduleInfo });
IModuleManager manager = new ModuleManager(Mock.Of<IModuleInitializer>(), moduleCatalogMock.Object);
Assert.False(manager.IsModuleInitialized<ModuleA>());
moduleInfo.State = ModuleState.Initializing;
Assert.False(manager.IsModuleInitialized<ModuleA>());
moduleInfo.State = ModuleState.Initialized;
Assert.True(manager.IsModuleInitialized<ModuleA>());
}
[Fact]
public void ModuleManagerReturnsCorrectInitializationStateWithName()
{
IModuleInfo moduleInfo = new ModuleInfo(typeof(ModuleA));
var moduleCatalogMock = new Mock<IModuleCatalog>();
moduleCatalogMock.Setup(c => c.Modules).Returns(new[] { moduleInfo });
IModuleManager manager = new ModuleManager(Mock.Of<IModuleInitializer>(), moduleCatalogMock.Object);
Assert.False(manager.IsModuleInitialized(nameof(ModuleA)));
moduleInfo.State = ModuleState.Initializing;
Assert.False(manager.IsModuleInitialized(nameof(ModuleA)));
moduleInfo.State = ModuleState.Initialized;
Assert.True(manager.IsModuleInitialized(nameof(ModuleA)));
}
[Fact]
public void ModuleManagerLoadModuleGeneric_CallsLoadModuleWithName()
{
var managerMock = new Mock<IModuleManager>();
managerMock.Object.LoadModule<ModuleA>();
managerMock.Verify(m => m.LoadModule(nameof(ModuleA)));
}
}
}
| 43.123596 | 112 | 0.653205 | [
"MIT"
] | Adam--/Prism | tests/Forms/Prism.Forms.Tests/Modularity/ModuleManagerExtensionsFixture.cs | 3,840 | C# |
namespace Etch.OrchardCore.ContentPermissions.Models
{
public class ContentPermissionsPartSettings
{
public string RedirectUrl { get; set; }
public bool HasRedirectUrl
{
get { return !string.IsNullOrWhiteSpace(RedirectUrl); }
}
}
}
| 18.3125 | 67 | 0.634812 | [
"Apache-2.0"
] | giannik/EasyOC | src/Modules/StatCan.OrchardCore.ContentPermissions/Models/ContentPermissionsPartSettings.cs | 295 | C# |
using Nop.Core.Domain.Payments;
using Nop.Services.Logging;
using Nop.Services.Payments;
using System;
using System.Collections.Generic;
using Nop.Services.Localization;
using Nop.Services.Configuration;
using Nop.Services.Plugins;
using NopBrasil.Plugin.Payments.PayU.Controllers;
using NopBrasil.Plugin.Payments.PayU.Services;
using Microsoft.AspNetCore.Http;
using Nop.Core;
namespace NopBrasil.Plugin.Payments.PayU
{
public class PayUPaymentProcessor : BasePlugin, IPaymentMethod
{
private readonly ILogger _logger;
private readonly ISettingService _settingService;
private readonly IPaymentPayUService _payUService;
private readonly PayUPaymentSettings _payUPaymentSettings;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWebHelper _webHelper;
private readonly ILocalizationService _localizationService;
public PayUPaymentProcessor(ILogger logger, ISettingService settingService, IPaymentPayUService payUService, PayUPaymentSettings payUPaymentSettings,
IHttpContextAccessor httpContextAccessor, IWebHelper webHelper, ILocalizationService localizationService)
{
this._logger = logger;
this._settingService = settingService;
this._payUService = payUService;
this._payUPaymentSettings = payUPaymentSettings;
this._httpContextAccessor = httpContextAccessor;
this._webHelper = webHelper;
this._localizationService = localizationService;
}
public override void Install()
{
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Payments.EmailAdmin.PayU", "Email castrado no PayU");
_localizationService.AddOrUpdatePluginLocaleResource("Plugins.Payments.MethodDescription.PayU", "Descrição que será exibida no checkout");
_localizationService.AddOrUpdatePluginLocaleResource("NopBrasil.Plugins.Payments.PayU.Fields.Redirection", "Você será redirecionado para a pagina do PayU.");
base.Install();
}
public override void Uninstall()
{
_settingService.DeleteSetting<PayUPaymentSettings>();
_localizationService.DeletePluginLocaleResource("Plugins.Payments.EmailAdmin.PayU");
_localizationService.DeletePluginLocaleResource("Plugins.Payments.MethodDescription.PayU");
_localizationService.DeletePluginLocaleResource("NopBrasil.Plugins.Payments.PayU.Fields.Redirection");
base.Uninstall();
}
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
return new ProcessPaymentResult()
{
NewPaymentStatus = PaymentStatus.Pending
};
}
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
try
{
_httpContextAccessor.HttpContext.Response.Clear();
var write = _httpContextAccessor.HttpContext.Response.WriteAsync(_payUService.GetStringPost(postProcessPaymentRequest));
_httpContextAccessor.HttpContext.Response.Body.FlushAsync();
_httpContextAccessor.HttpContext.Response.Body.EndWrite(write);
}
catch (Exception e)
{
_logger.Error(e.Message, e);
}
}
public decimal GetAdditionalHandlingFee(IList<Nop.Core.Domain.Orders.ShoppingCartItem> cart) => 0;
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest) => new CapturePaymentResult();
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) => new RefundPaymentResult();
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest) => new VoidPaymentResult();
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) => new ProcessPaymentResult();
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest) => new CancelRecurringPaymentResult();
public bool CanRePostProcessPayment(Nop.Core.Domain.Orders.Order order) => false;
public Type GetControllerType() => typeof(PaymentPayUController);
public bool SupportCapture => false;
public bool SupportPartiallyRefund => false;
public bool SupportRefund => false;
public bool SupportVoid => false;
public RecurringPaymentType RecurringPaymentType => RecurringPaymentType.NotSupported;
public PaymentMethodType PaymentMethodType => PaymentMethodType.Redirection;
public bool HidePaymentMethod(IList<Nop.Core.Domain.Orders.ShoppingCartItem> cart) => false;
public bool SkipPaymentInfo => false;
public IList<string> ValidatePaymentForm(IFormCollection form) => new List<string>();
public ProcessPaymentRequest GetPaymentInfo(IFormCollection form) => new ProcessPaymentRequest();
public string PaymentMethodDescription => _payUPaymentSettings.PaymentMethodDescription;
public override string GetConfigurationPageUrl() => $"{_webHelper.GetStoreLocation()}Admin/PaymentPayU/Configure";
public string GetPublicViewComponentName() => "PaymentPayU";
}
}
| 44.429752 | 169 | 0.727307 | [
"MIT"
] | nopCommerceBrasil/NopBrasil.Plugin.Payments.PayU | PayUPaymentProcessor.cs | 5,383 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tree : MonoBehaviour
{
[SerializeField] private float treeHealth;
[SerializeField] private Animator anim;
[SerializeField] private GameObject woodPrefab;
[SerializeField] private int totalWood;
[SerializeField] private ParticleSystem leafs;
private bool isCut;
public void OnHit()
{
treeHealth--;
anim.SetTrigger("isHit");
leafs.Play();
if (treeHealth <= 0)
{
// cria o toco e instancia os drops (madeira)
for (int i = 0; i < totalWood; i++)
{
Instantiate(woodPrefab, transform.position + new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), 0f), transform.rotation);
}
anim.SetTrigger("cut");
isCut = true;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Axe") && !isCut)
{
Debug.Log("bateu");
OnHit();
}
}
} | 25.232558 | 144 | 0.578802 | [
"MIT"
] | ThiagoPereira232/Curso-Start-GameDev | Top Down Game 2D/Assets/Scripts/Craft/Tree.cs | 1,085 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Silk.NET.Core.Attributes;
#pragma warning disable 1591
namespace Silk.NET.OpenGL
{
[NativeName("Name", "PathElementType")]
public enum PathElementType : int
{
[NativeName("Name", "GL_UTF8_NV")]
Utf8NV = 0x909A,
[NativeName("Name", "GL_UTF16_NV")]
Utf16NV = 0x909B,
}
}
| 22.761905 | 71 | 0.667364 | [
"MIT"
] | Ar37-rs/Silk.NET | src/OpenGL/Silk.NET.OpenGL/Enums/PathElementType.gen.cs | 478 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class CosmosMethodCallTranslatorProvider : IMethodCallTranslatorProvider
{
private readonly List<IMethodCallTranslator> _plugins = new();
private readonly List<IMethodCallTranslator> _translators = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public CosmosMethodCallTranslatorProvider(
ISqlExpressionFactory sqlExpressionFactory,
IEnumerable<IMethodCallTranslatorPlugin> plugins)
{
_plugins.AddRange(plugins.SelectMany(p => p.Translators));
_translators.AddRange(
new IMethodCallTranslator[]
{
new EqualsTranslator(sqlExpressionFactory),
new StringMethodTranslator(sqlExpressionFactory),
new ContainsTranslator(sqlExpressionFactory),
new RandomTranslator(sqlExpressionFactory)
//new LikeTranslator(sqlExpressionFactory),
//new EnumHasFlagTranslator(sqlExpressionFactory),
//new GetValueOrDefaultTranslator(sqlExpressionFactory),
//new ComparisonTranslator(sqlExpressionFactory),
});
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression? Translate(
IModel model,
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
Check.NotNull(model, nameof(model));
Check.NotNull(method, nameof(method));
Check.NotNull(arguments, nameof(arguments));
Check.NotNull(logger, nameof(logger));
return _plugins.Concat(_translators)
.Select(t => t.Translate(instance, method, arguments, logger))
.FirstOrDefault(t => t != null);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void AddTranslators(IEnumerable<IMethodCallTranslator> translators)
=> _translators.InsertRange(0, translators);
}
}
| 53.036145 | 113 | 0.66856 | [
"Apache-2.0"
] | AshkanAbd/efcore | src/EFCore.Cosmos/Query/Internal/CosmosMethodCallTranslatorProvider.cs | 4,402 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.SHUZIWULIU.Models
{
public class CancelCreditIssuebatchRequest : TeaModel {
// OAuth模式下的授权token
[NameInMap("auth_token")]
[Validation(Required=false)]
public string AuthToken { get; set; }
[NameInMap("product_instance_id")]
[Validation(Required=false)]
public string ProductInstanceId { get; set; }
// 批次号
[NameInMap("batch_id")]
[Validation(Required=true)]
public string BatchId { get; set; }
// 货主分布式数字身份
[NameInMap("consignor_did")]
[Validation(Required=true)]
public string ConsignorDid { get; set; }
// 集团平台方分布式数字身份
[NameInMap("group_platform_did")]
[Validation(Required=true)]
public string GroupPlatformDid { get; set; }
// 业务发起方分布式数字身份
[NameInMap("platform_did")]
[Validation(Required=true)]
public string PlatformDid { get; set; }
// 产品id
// A模式:PRODUCT_MYBANK,
// A+模式:PRODUCT_MYBANK_A_PLUS,
// B模式:PRODUCT_MYBANK_B
[NameInMap("product_id")]
[Validation(Required=true)]
public string ProductId { get; set; }
}
}
| 25.692308 | 59 | 0.610778 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | shuziwuliu/csharp/core/Models/CancelCreditIssuebatchRequest.cs | 1,446 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.HDInsight.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The HDInsight REST API operation.
/// </summary>
public partial class Operation
{
/// <summary>
/// Initializes a new instance of the Operation class.
/// </summary>
public Operation()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Operation class.
/// </summary>
/// <param name="name">The operation name:
/// {provider}/{resource}/{operation}</param>
/// <param name="display">The object that represents the
/// operation.</param>
public Operation(string name = default(string), OperationDisplay display = default(OperationDisplay))
{
Name = name;
Display = display;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the operation name: {provider}/{resource}/{operation}
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the object that represents the operation.
/// </summary>
[JsonProperty(PropertyName = "display")]
public OperationDisplay Display { get; set; }
}
}
| 30.241935 | 109 | 0.592 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/HDInsight/Management.HDInsight/Generated/Models/Operation.cs | 1,875 | C# |
namespace GraphQLCore.Validation.Rules
{
using Exceptions;
using Language.AST;
using System.Collections.Generic;
using Type;
public class FieldsOnCorrectType : IValidationRule
{
public IEnumerable<GraphQLException> Validate(GraphQLDocument document, IGraphQLSchema schema)
{
var visitor = new FieldsOnCorrectTypeVisitor(schema);
visitor.Visit(document);
return visitor.Errors;
}
}
}
| 24.947368 | 102 | 0.668776 | [
"MIT"
] | mkmarek/graphql-ast-dotnetcore | src/GraphQLCore/Validation/Rules/FieldsOnCorrectType.cs | 476 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VEF.ComponentModel;
namespace VEF.Interfaces.Settings
{
//public abstract class AbstractSettings : IDataErrorInfo //: ApplicationSettingsBase, IDataErrorInfo
//{
// #region Member
// protected Dictionary<string, object> Backup;
// #endregion
// #region CTOR
// protected AbstractSettings()
// {
// Backup = new Dictionary<string, object>();
// }
// #endregion
// #region Methods
// //protected virtual void UpdateBackup(string propertyName = "")
// //{
// // if (propertyName == null || string.IsNullOrEmpty(propertyName) == true)
// // {
// // throw new ArgumentException("Error handling null property for object");
// // }
// // if (Backup.ContainsKey(propertyName))
// // Backup.Remove(propertyName);
// // Backup.Add(propertyName, this[propertyName]);
// //}
// ////.Net 4.5 [CallerMemberName]
// //protected virtual void ApplyDefault(string propertyName = "")
// //{
// // if (propertyName == null || string.IsNullOrEmpty(propertyName) == true)
// // {
// // throw new ArgumentException("Error handling null property for object");
// // }
// // PropertyInfo prop = this.GetType().GetProperty(propertyName);
// // if (prop.GetCustomAttributes(true).Length > 0)
// // {
// // object[] defaultValueAttribute = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
// // if (defaultValueAttribute != null)
// // {
// // DefaultValueAttribute defaultValue = defaultValueAttribute[0] as DefaultValueAttribute;
// // if (defaultValue != null)
// // {
// // prop.SetValue(this, defaultValue.Value, null);
// // }
// // }
// // }
// //}
// #endregion
// #region IDataErrorInfo
// [Display(Description = "Error", Name = "Error", GroupName = "Error", AutoGenerateField = false)]
// public virtual string Error
// {
// get { return null; }
// }
// string IDataErrorInfo.this[string columnName]
// {
// get { return null; }
// }
// #endregion
//}
}
| 31 | 115 | 0.53595 | [
"MIT"
] | devxkh/FrankE | Editor/VEF/VEF.XForms/Interface/Settings/AbstractSettings.cs | 2,575 | C# |
using System.IO;
using System.Linq;
using DesperateDevs.CodeGeneration;
namespace Entitas.CodeGeneration.Plugins {
public class ComponentEntityApiInterfaceGenerator : AbstractGenerator {
public override string name { get { return "Component (Entity API Interface)"; } }
const string STANDARD_TEMPLATE =
@"public partial interface I${ComponentName}Entity {
${ComponentType} ${componentName} { get; }
bool has${ComponentName} { get; }
void Add${ComponentName}(${newMethodParameters});
void Replace${ComponentName}(${newMethodParameters});
void Remove${ComponentName}();
}
";
const string FLAG_TEMPLATE =
@"public partial interface I${ComponentName}Entity {
bool ${prefixedComponentName} { get; set; }
}
";
const string ENTITY_INTERFACE_TEMPLATE = "public partial class ${EntityType} : I${ComponentName}Entity { }\n";
public override CodeGenFile[] Generate(CodeGeneratorData[] data) {
return data
.OfType<ComponentData>()
.Where(d => d.ShouldGenerateMethods())
.Where(d => d.GetContextNames().Length > 1)
.SelectMany(generate)
.ToArray();
}
CodeGenFile[] generate(ComponentData data) {
return new[] { generateInterface(data) }
.Concat(data.GetContextNames().Select(contextName => generateEntityInterface(contextName, data)))
.ToArray();
}
CodeGenFile generateInterface(ComponentData data) {
var template = data.GetMemberData().Length == 0
? FLAG_TEMPLATE
: STANDARD_TEMPLATE;
return new CodeGenFile(
"Components" + Path.DirectorySeparatorChar +
"Interfaces" + Path.DirectorySeparatorChar +
"I" + data.ComponentName() + "Entity.cs",
template.Replace(data, string.Empty),
GetType().FullName
);
}
CodeGenFile generateEntityInterface(string contextName, ComponentData data) {
return new CodeGenFile(
contextName + Path.DirectorySeparatorChar +
"Components" + Path.DirectorySeparatorChar +
data.ComponentNameWithContext(contextName).AddComponentSuffix() + ".cs",
ENTITY_INTERFACE_TEMPLATE.Replace(data, contextName),
GetType().FullName
);
}
}
}
| 35.084507 | 118 | 0.603372 | [
"MIT"
] | Eagle-Lai/Entitas-CSharp | Addons/Entitas.CodeGeneration.Plugins/Entitas.CodeGeneration.Plugins/CodeGenerators/Component/ComponentEntityApiInterfaceGenerator.cs | 2,493 | C# |
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
namespace EssentialUIKit.Themes
{
[Preserve(AllMembers = true)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DarkTheme
{
public DarkTheme()
{
InitializeComponent();
}
}
} | 20.733333 | 53 | 0.652733 | [
"MIT"
] | MohanlalGo/essential-ui-kit-for-xamarin.forms | EssentialUIKit/Themes/DarkTheme.xaml.cs | 313 | C# |
using Biobanks.Entities.Data;
using Biobanks.Identity.Data.Entities;
using Biobanks.Services.Dto;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Biobanks.Services.Contracts
{
public interface IOrganisationService
{
/// <summary>
/// Get all untracked Organisation which match the given parameter filters
/// </summary>
/// <param name="name">Organisation name filter, matches all organisation that contains name</param>
/// <param name="includeSuspended">Results to include Organgisations that have been suspended, true by default</param>
/// <returns>An Enumerable of all applicable untracked Organisations</returns>
Task<IEnumerable<Organisation>> List(string name = "", bool includeSuspended = true);
/// <summary>
/// Get all untracked Organisation which match the given parameter filters
/// </summary>
/// <param name="name">Organisation name filter, matches all organisation that contains name</param>
/// <param name="includeSuspended">Results to include Organgisations that have been suspended, true by default</param>
/// <returns>
/// An Enumerable of all applicable untracked Organisations, including properties:
/// <list type="bullet">
/// <item>Collections</item>
/// <item>DiagnosisCapabilities</item>
/// <item>OrganisationUsers</item>
/// </list>
/// </returns>
Task<IEnumerable<Organisation>> ListForActivity(string name = "", bool includeSuspended = true);
/// <summary>
/// Get all untracked Organisation which match by Anonymous Identifer
/// </summary>
/// <param name="organisationAnonymousIds">Collection of Organisation Annoymous Identifier to match against</param>
/// <returns>An Enumerable of all applicable untracked Organisations</returns>
Task<IEnumerable<Organisation>> ListByAnonymousIdentifiers(IEnumerable<Guid> organisationAnonymousIds);
/// <summary>
/// Get all untracked Organisation which match by Organisation External Id
/// </summary>
/// <param name="organisationExternalId">Collection of Organisation External Id to match against</param>
/// <returns>An Enumerable of all applicable untracked Organisations</returns>
Task<IEnumerable<Organisation>> ListByExternalIds(IList<string> organisationExternalId);
/// <summary>
/// Get all untracked Organisation which match are part of the given Netowrk
/// <param name="networkId">The Id of the Network to match against</param>
/// <returns>An Enumerable of all applicable untracked Organisations</returns>
Task<IEnumerable<Organisation>> ListByNetworkId(int networkId);
/// <summary>
/// Get all untracked Organisation which are under the control by the given User
/// <param name="userId">The Id of the User to match against</param>
/// <returns>An Enumerable of all applicable untracked Organisations</returns>
Task<IEnumerable<Organisation>> ListByUserId(string userId);
/// <summary>
/// Get the untracked Organisation for a given Id
/// </summary>
/// <returns>The Organisation of given Id. Otherwise null</returns>
Task<Organisation> Get(int biobankId);
/// <summary>
/// Get the untracked Organisation for a given External Id
/// </summary>
/// <returns>The Organisation of given External Id. Otherwise null</returns>
Task<Organisation> GetByExternalId(string externalId);
/// <summary>
/// Get the untracked Organisation for a given Organisation Name
/// </summary>
/// <returns>The Organisation of name. Otherwise null</returns>
Task<Organisation> GetByName(string organisationName);
/// <summary>
/// Create a new Organisation
/// </summary>
/// <returns>The newly created Organisation with assigned Id</returns>
Task<Organisation> Create(OrganisationDTO organisationDto);
/// <summary>
/// Update an exisiting Organisation
/// </summary>
/// <returns>The updated Organisation reference</returns>
Task<Organisation> Update(OrganisationDTO organisationDto);
/// <summary>
/// Delete an exisiting Organisation
/// </summary>
Task Delete(int organisationId);
/// <summary>
/// Checks if a Registration Request exists for an Organisation of given name
/// </summary>
/// <param name="name">Name of the Organisation</param>
/// <returns>true - If an Open or Accepted request exists for the given Organisation</returns>
Task<bool> RegistrationRequestExists(string name);
/// <summary>
/// Checks if there is any associated API Credentials for the given Organisation
/// </summary>
/// <param name="organisationId">Internal Id of the Organisation</param>
/// <returns>true - There is at least one set of API Credenitals for the given Organisation</returns>
Task<bool> IsApiClient(int organisationId);
/// <summary>
/// Checks if the Organisation is suspended
/// </summary>
Task<bool> IsSuspended(int organisationId);
/// <summary>
/// Suspends an Organisation
/// </summary>
Task<Organisation> Suspend(int organisationId);
/// <summary>
/// Unsuspends an Organisation
/// </summary>
Task<Organisation> Unsuspend(int organisationId);
/// <summary>
/// List all untracked, accepted Organisation Registration Requests
/// </summary>
/// <returns>Enumerable of all accepted registration requests</returns>
Task<IEnumerable<OrganisationRegisterRequest>> ListAcceptedRegistrationRequests();
/// <summary>
/// List all untracked, open Organisation Registration Requests
/// </summary>
/// <returns>Enumerable of all accepted registration requests</returns>
Task<IEnumerable<OrganisationRegisterRequest>> ListOpenRegistrationRequests();
/// <summary>
/// List all untracked, historic Organisation Registration Requests. Historic requests are either accepted or declined
/// </summary>
/// <returns>Enumerable of all historic registration requests</returns>
Task<IEnumerable<OrganisationRegisterRequest>> ListHistoricalRegistrationRequests();
/// <summary>
/// Get the Registration Request by it's Id
/// </summary>
/// <returns>A Registration Request if it exists, otherwise null</returns>
Task<OrganisationRegisterRequest> GetRegistrationRequest(int requestId);
/// <summary>
/// Get the Registration Request by the email of a user in the request
/// </summary>
/// <param name="email">The email of the user in the request</param>
/// <returns>A Registration Request if it exists, otherwise null</returns>
Task<OrganisationRegisterRequest> GetRegistrationRequestByEmail(string email);
/// <summary>
/// Get the Registration Request by the name of the Organisation in the request
/// </summary>
/// <param name="name">The name of the request's Organisation</param>
/// <returns>A Registration Request if it exists, otherwise null</returns>
Task<OrganisationRegisterRequest> GetRegistrationRequestByName(string name);
/// <summary>
/// Add a new Registration Request for a new Organisation
/// </summary>
/// <returns>The newly created Registration Request</returns>
Task<OrganisationRegisterRequest> AddRegistrationRequest(OrganisationRegisterRequest request);
/// <summary>
/// Update an exisiting Registration Request for a new Organisation
/// </summary>
/// <returns>The updated Registration Request</returns>
Task<OrganisationRegisterRequest> UpdateRegistrationRequest(OrganisationRegisterRequest request);
/// <summary>
/// Delete an exisiting Registration Request for a new Organisation
/// </summary>
Task RemoveRegistrationRequest(OrganisationRegisterRequest request);
/// <summary>
/// Adds an exisiting Sser to an exisiting Organisation
/// </summary>
/// <param name="userId">The Id of the User</param>
/// <param name="organisationId">The Id of the Organisation</param>
/// <returns>A new OrganisationUser relationship</returns>
Task<OrganisationUser> AddUserToOrganisation(string userId, int organisationId);
/// <summary>
/// Remove an exisiting Sser to an exisiting Organisation
/// </summary>
/// <param name="userId">The Id of the User</param>
/// <param name="organisationId">The Id of the Organisation</param>
Task RemoveUserFromOrganisation(string userId, int organisationId);
/// <summary>
/// Adds an exisiting Funder to an exisiting Organisation
/// </summary>
/// <param name="funderId">The Id of the Funder being added</param>
/// <param name="organisationId">The Id of the Organisation</param>
/// <returns>true - If successful in adding Funder</returns>
Task AddFunder(int funderId, int organisationId);
/// <summary>
/// Removes an exisiting Funder to an exisiting Organisation
/// </summary>
/// <param name="funderId">The Id of the Funder being added</param>
/// <param name="organisationId">The Id of the Organisation</param>
Task RemoveFunder(int funderId, int biobankId);
/// <summary>
/// Get the last active user for a given Organisation
/// </summary>
/// <param name="organisationId">The Id of the Organisation</param>
/// <returns>
/// The User that was last online, that is part of the given Organisation.
/// Otherwise null, if no Users or Organisation exists
/// </returns>
Task<ApplicationUser> GetLastActiveUser(int organisationId);
/// <summary>
/// Generates a Credential (ID, Secret) pair for authenticating against the API as the given Organisation
/// </summary>
/// <param name="organisationId">The Id of the Organisation</param>
/// <param name="clientName">Optional client name, null by default</param>
/// <returns>KeyValuePair (ID, Secret). The generated ID is permenant, but the secret can be regenerated</returns>
Task<KeyValuePair<string, string>> GenerateNewApiClient(int organisationId, string clientName = null);
/// <summary>
/// Regenerates the API Secret for a given Organisation
/// </summary>
/// <param name="organisationId">The Id of the Organisation</param>
/// <returns>KeyValuePair (ID, Secret) with newly regenerated Secret</returns>
Task<KeyValuePair<string, string>> GenerateNewSecretForBiobank(int organisationId);
/// <summary>
/// Lists the reasons for an Organisations registration
/// </summary>
/// <returns>An untracked Enumerable of Organisation Registration Reasons</returns>
Task<IEnumerable<OrganisationRegistrationReason>> ListRegistrationReasons(int organisationId);
/// <summary>
/// Whether this Organisation make use of the Publication feature. If so, the Directory will attempt to source
/// relevant publications associated with this Organisation
/// </summary>
Task<bool> UsesPublications(int organisationId);
}
}
| 47.544355 | 126 | 0.656178 | [
"MIT"
] | biobankinguk/biobankinguk | src/Directory/Services/Contracts/IOrganisationService.cs | 11,793 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using BenchmarkDotNet.Attributes;
using SixLabors.ImageSharp.Web.Synchronization;
namespace SixLabors.ImageSharp.Web.Benchmarks.Synchronization
{
/// <summary>
/// Each of these tests obtains a lock (which completes synchronously as nobody else is holding the lock)
/// and then releases that lock.
/// </summary>
[Config(typeof(MemoryConfig))]
public class AsyncLockBenchmarks
{
private readonly AsyncLock asyncLock = new();
private readonly AsyncReaderWriterLock asyncReaderWriterLock = new();
private readonly AsyncKeyLock<string> asyncKeyLock = new();
private readonly AsyncKeyReaderWriterLock<string> asyncKeyReaderWriterLock = new();
[Benchmark]
public void AsyncLock() => this.asyncLock.LockAsync().Result.Dispose();
[Benchmark]
public void AsyncReaderWriterLock_Reader() => this.asyncReaderWriterLock.ReaderLockAsync().Result.Dispose();
[Benchmark]
public void AsyncReaderWriterLock_Writer() => this.asyncReaderWriterLock.WriterLockAsync().Result.Dispose();
[Benchmark]
public void AsyncKeyLock() => this.asyncKeyLock.LockAsync("key").Result.Dispose();
[Benchmark]
public void AsyncKeyReaderWriterLock_Reader() => this.asyncKeyReaderWriterLock.ReaderLockAsync("key").Result.Dispose();
[Benchmark]
public void AsyncKeyReaderWriterLock_Writer() => this.asyncKeyReaderWriterLock.WriterLockAsync("key").Result.Dispose();
/*
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19043.1348 (21H1/May2021Update)
Intel Core i9-9900K CPU 3.60GHz (Coffee Lake), 1 CPU, 16 logical and 8 physical cores
.NET SDK=6.0.100
[Host] : .NET Core 3.1.21 (CoreCLR 4.700.21.51404, CoreFX 4.700.21.51508), X64 RyuJIT
DefaultJob : .NET Core 3.1.21 (CoreCLR 4.700.21.51404, CoreFX 4.700.21.51508), X64 RyuJIT
| Method | Mean | Error | StdDev | Gen 0 | Allocated |
|-------------------------------- |----------:|---------:|---------:|-------:|----------:|
| AsyncLock | 34.93 ns | 0.144 ns | 0.135 ns | - | - |
| AsyncReaderWriterLock_Reader | 28.45 ns | 0.117 ns | 0.109 ns | - | - |
| AsyncReaderWriterLock_Writer | 28.66 ns | 0.125 ns | 0.117 ns | - | - |
| AsyncKeyLock | 276.48 ns | 5.379 ns | 5.031 ns | 0.0210 | 176 B |
| AsyncKeyReaderWriterLock_Reader | 261.96 ns | 1.522 ns | 1.423 ns | 0.0210 | 176 B |
| AsyncKeyReaderWriterLock_Writer | 266.35 ns | 1.661 ns | 1.554 ns | 0.0210 | 176 B |
*/
}
}
| 48.241379 | 127 | 0.606505 | [
"Apache-2.0"
] | DonPangPang/ImageSharp.Web | tests/ImageSharp.Web.Benchmarks/Synchronization/AsyncLockBenchmarks.cs | 2,798 | C# |
using Alphaleonis.Win32.Filesystem;
using System.Security.AccessControl;
namespace Security2
{
public partial class FileSystemAccessRule2
{
#region Properties
private FileSystemAccessRule fileSystemAccessRule;
private string fullName;
private bool inheritanceEnabled;
private string inheritedFrom;
public string Name { get { return System.IO.Path.GetFileName(fullName); } }
public string FullName { get { return fullName; } set { fullName = value; } }
public bool InheritanceEnabled { get { return inheritanceEnabled; } set { inheritanceEnabled = value; } }
public string InheritedFrom { get { return inheritedFrom; } set { inheritedFrom = value; } }
public AccessControlType AccessControlType { get { return fileSystemAccessRule.AccessControlType; } }
public FileSystemRights2 AccessRights { get { return (FileSystemRights2)fileSystemAccessRule.FileSystemRights; } }
public IdentityReference2 Account { get { return fileSystemAccessRule.IdentityReference; } }
public InheritanceFlags InheritanceFlags { get { return fileSystemAccessRule.InheritanceFlags; } }
public bool IsInherited { get { return fileSystemAccessRule.IsInherited; } }
public PropagationFlags PropagationFlags { get { return fileSystemAccessRule.PropagationFlags; } }
#endregion
public FileSystemAccessRule2(FileSystemAccessRule fileSystemAccessRule)
{
this.fileSystemAccessRule = fileSystemAccessRule;
}
public FileSystemAccessRule2(FileSystemAccessRule fileSystemAccessRule, FileSystemInfo item)
{
this.fileSystemAccessRule = fileSystemAccessRule;
this.fullName = item.FullName;
}
public FileSystemAccessRule2(FileSystemAccessRule fileSystemAccessRule, string path)
{
this.fileSystemAccessRule = fileSystemAccessRule;
}
public static implicit operator FileSystemAccessRule(FileSystemAccessRule2 ace2)
{
return ace2.fileSystemAccessRule;
}
public static implicit operator FileSystemAccessRule2(FileSystemAccessRule ace)
{
return new FileSystemAccessRule2(ace);
}
//REQUIRED BECAUSE OF CONVERSION OPERATORS
public override bool Equals(object obj)
{
return fileSystemAccessRule == (FileSystemAccessRule)obj;
}
public override int GetHashCode()
{
return fileSystemAccessRule.GetHashCode();
}
public override string ToString()
{
return string.Format("{0} '{1}' ({2})",
AccessControlType.ToString()[0],
Account.AccountName,
AccessRights.ToString()
);
}
public SimpleFileSystemAccessRule ToSimpleFileSystemAccessRule2()
{
return new SimpleFileSystemAccessRule(fullName, Account, AccessRights);
}
}
} | 40.743243 | 122 | 0.671642 | [
"MIT"
] | AspenForester/NTFSSecurity | Security2/FileSystem/FileSystemAccessRule2 Class/FileSystemAccessRule2.cs | 3,017 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpFileSystem.FileSystems;
namespace SharpFileSystem
{
public sealed class MemoryFileSystemWatcher
: IFileSystemWatcher
, IDisposable
{
readonly MemoryFileSystem fileSystem;
readonly FileSystemPath path;
bool enableRaisingEvents;
public event EventHandler<FileSystemChange> Changed;
void RaiseChanged(FileSystemChange change)
{
Changed?.Invoke(this, change);
}
void OnChanged(object sender, FileSystemChange e)
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Created:
if (e.NewPath.ParentPath == path)
{
RaiseChanged(e);
}
break;
case WatcherChangeTypes.Changed:
if (e.NewPath.ParentPath == path)
{
RaiseChanged(e);
}
break;
case WatcherChangeTypes.Deleted:
if (e.OldPath.ParentPath == path)
{
RaiseChanged(e);
}
break;
case WatcherChangeTypes.Renamed:
if (e.OldPath.ParentPath == path)
{
if (e.NewPath.ParentPath == path)
{
RaiseChanged(e);
}
else
{
RaiseChanged(FileSystemChange.FromDeleted(e.OldPath));
}
}
else
{
if (e.NewPath.ParentPath == path)
{
RaiseChanged(FileSystemChange.FromCreated(e.NewPath));
}
}
break;
}
}
void Attach()
{
if (enableRaisingEvents) return;
enableRaisingEvents = true;
fileSystem.Changed += OnChanged;
}
void Detach()
{
if (!enableRaisingEvents) return;
enableRaisingEvents = false;
fileSystem.Changed -= OnChanged;
}
public void Dispose()
{
Detach();
}
#region IFileSystemWatcher implementation
public IFileSystem FileSystem
{
get { return fileSystem; }
}
public FileSystemPath Path
{
get { return path; }
}
public bool EnableRaisingEvents
{
get { return enableRaisingEvents; }
set
{
if (value)
{
Attach();
}
else
{
Detach();
}
}
}
#endregion
public MemoryFileSystemWatcher(MemoryFileSystem fileSystem, FileSystemPath path)
{
this.fileSystem = fileSystem;
this.path = path;
}
}
}
| 26.109375 | 88 | 0.428785 | [
"MIT"
] | vain0/playground | 2017-01-15-tuktuk-the-explorer/src/sharpfilesystem/SharpFileSystem/FileSystemWatchers/MemoryFileSystemWatcher.cs | 3,344 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DSA.DataStructures.Lists;
using System.Linq;
namespace DSAUnitTests.DataStructures.Lists
{
[TestClass]
public class ArrayListTests
{
[TestMethod]
public void AddingItemsOneByOne()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
int trueCount = 0;
int previousItem = int.MinValue;
foreach (var item in list)
{
if (previousItem > item) Assert.Fail();
previousItem = item;
trueCount++;
}
Assert.IsTrue(list.Count == itemCount
&& list.Count == trueCount);
}
[TestMethod]
public void AddingRangeOfItems()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
if (list.Count != itemCount) Assert.Fail();
var list2 = new ArrayList<int>();
list2.AddRange(list);
int trueCount = 0;
int previousItem = int.MinValue;
foreach (var item in list2)
{
if (previousItem > item) Assert.Fail();
previousItem = item;
trueCount++;
}
Assert.IsTrue(list.Count == itemCount
&& list2.Count == itemCount
&& list2.Count == trueCount);
}
[TestMethod]
public void InitializingArrayListWithCollection()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
var list2 = new ArrayList<int>(list);
int trueCount = 0;
int previousItem = int.MinValue;
foreach (var item in list2)
{
if (previousItem > item) Assert.Fail();
previousItem = item;
trueCount++;
}
Assert.IsTrue(list.Count == itemCount
&& list2.Count == itemCount
&& list2.Count == trueCount);
}
[TestMethod]
public void RemovingAllExceptOne()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
for (int i = 0; i < itemCount - 1; i++)
{
if (!list.Remove(i)) Assert.Fail(i.ToString());
}
int trueCount = 0;
foreach (var item in list)
{
trueCount++;
}
Assert.IsTrue(list.Count == 1
&& trueCount == 1
&& list[0] == itemCount - 1);
}
[TestMethod]
public void InitializationWithZeroCapacityAndAddingItemsAfterwards()
{
var list = new ArrayList<int>(0);
int itemCount = 100;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
int trueCount = 0;
int previousItem = int.MinValue;
foreach (var item in list)
{
if (previousItem > item) Assert.Fail();
previousItem = item;
trueCount++;
}
Assert.IsTrue(list.Count == itemCount
&& list.Count == trueCount);
}
[TestMethod]
public void RemovingAllItemsAndAddingAgain()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
for (int i = 0; i < itemCount; i++)
{
if (!list.Remove(i)) Assert.Fail();
}
bool countWasZero = list.Count == 0;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
int trueCount = 0;
int previousItem = int.MinValue;
foreach (var item in list)
{
if (previousItem > item) Assert.Fail();
previousItem = item;
trueCount++;
}
Assert.IsTrue(list.Count == itemCount
&& list.Count == trueCount
&& countWasZero);
}
[TestMethod]
public void RemoveRangeOfItems()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
list.RemoveRange(0, itemCount - 1);
int trueCount = 0;
foreach (var item in list)
{
trueCount++;
}
Assert.IsTrue(list.Count == 1
&& list.Count == trueCount
&& list[0] == itemCount - 1);
}
[TestMethod]
public void InsertAllItemsAtTheBeginningAndCheckForReversedOrder()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Insert(0, i);
}
var list2 = new ArrayList<int>(list.Reverse());
bool areReversed = true;
for (int i = 0; i < itemCount; i++)
{
if (list[i] != list2[itemCount - 1 - i])
{
areReversed = false;
break;
}
}
Assert.IsTrue(list.Count == itemCount
&& list2.Count == itemCount
&& areReversed);
}
[TestMethod]
public void RemoveAtZeroUntilOneItemIsLeft()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
for (int i = 1; i < itemCount; i++)
{
list.RemoveAt(0);
}
int trueCount = 0;
foreach (var item in list)
{
trueCount++;
}
Assert.IsTrue(list.Count == 1
&& list.Count == trueCount
&& list[0] == itemCount - 1);
}
[TestMethod]
public void IndexOfAndLastIndexOfTest()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
list.Insert(0, i);
}
bool allInPlace = true;
for (int i = 0; i < itemCount; i++)
{
int first = list.IndexOf(i);
int last = list.LastIndexOf(i);
if (last - first - 1 - 2 * i != 0)
{
allInPlace = false;
break;
}
}
Assert.IsTrue(list.Count == itemCount * 2
&& allInPlace);
}
[TestMethod]
public void CheckIfContainedBeforeAndAfterRemoval()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
if (list.Contains(i)) Assert.Fail();
list.Add(i);
if (!list.Contains(i)) Assert.Fail();
}
for (int i = 0; i < itemCount; i++)
{
if (!list.Contains(i)) Assert.Fail();
list.Remove(i);
if (list.Contains(i)) Assert.Fail();
}
Assert.IsTrue(list.Count == 0);
}
[TestMethod]
public void AddingAfterClearingCollection()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
list.Clear();
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
bool everythingIntact = true;
for (int i = 0; i < itemCount; i++)
{
if (list[i] != i)
{
everythingIntact = false;
break;
}
}
Assert.IsTrue(list.Count == itemCount
&& everythingIntact);
}
[TestMethod]
public void InsertingRangeOfItemsAtTheMiddle()
{
var list = new ArrayList<int>();
int itemCount = 1000;
for (int i = 0; i < itemCount; i++)
{
list.Add(i);
}
var list2 = new ArrayList<int>(list);
list.InsertRange(itemCount / 2, list2);
for (int i = 0; i < itemCount / 2; i++)
{
if (list[i] != i) Assert.Fail();
}
for (int i = itemCount / 2; i < itemCount + itemCount / 2; i++)
{
if (list[i] != i - itemCount / 2) Assert.Fail();
}
for (int i = itemCount + itemCount / 2; i < itemCount * 2; i++)
{
if (list[i] != i - itemCount) Assert.Fail();
}
Assert.IsTrue(list.Count == itemCount * 2);
}
}
}
| 24.895782 | 76 | 0.401874 | [
"MIT"
] | MichaelaIvanova/DSA | DSA/DSAUnitTests/DataStructures/Lists/ArrayListTests.cs | 10,035 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Health Error</summary>
public partial class HealthError :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IHealthError,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IHealthErrorInternal
{
/// <summary>Backing field for <see cref="CreationTimeUtc" /> property.</summary>
private global::System.DateTime? _creationTimeUtc;
/// <summary>Error creation time (UTC)</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public global::System.DateTime? CreationTimeUtc { get => this._creationTimeUtc; set => this._creationTimeUtc = value; }
/// <summary>Backing field for <see cref="EntityId" /> property.</summary>
private string _entityId;
/// <summary>ID of the entity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string EntityId { get => this._entityId; set => this._entityId = value; }
/// <summary>Backing field for <see cref="ErrorCategory" /> property.</summary>
private string _errorCategory;
/// <summary>Category of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorCategory { get => this._errorCategory; set => this._errorCategory = value; }
/// <summary>Backing field for <see cref="ErrorCode" /> property.</summary>
private string _errorCode;
/// <summary>Error code.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorCode { get => this._errorCode; set => this._errorCode = value; }
/// <summary>Backing field for <see cref="ErrorLevel" /> property.</summary>
private string _errorLevel;
/// <summary>Level of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorLevel { get => this._errorLevel; set => this._errorLevel = value; }
/// <summary>Backing field for <see cref="ErrorMessage" /> property.</summary>
private string _errorMessage;
/// <summary>Error message.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorMessage { get => this._errorMessage; set => this._errorMessage = value; }
/// <summary>Backing field for <see cref="ErrorSource" /> property.</summary>
private string _errorSource;
/// <summary>Source of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorSource { get => this._errorSource; set => this._errorSource = value; }
/// <summary>Backing field for <see cref="ErrorType" /> property.</summary>
private string _errorType;
/// <summary>Type of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string ErrorType { get => this._errorType; set => this._errorType = value; }
/// <summary>Backing field for <see cref="InnerHealthError" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IInnerHealthError[] _innerHealthError;
/// <summary>
/// The inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is
/// used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing
/// the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception
/// -> InnerException.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IInnerHealthError[] InnerHealthError { get => this._innerHealthError; set => this._innerHealthError = value; }
/// <summary>Backing field for <see cref="PossibleCaus" /> property.</summary>
private string _possibleCaus;
/// <summary>Possible causes of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string PossibleCaus { get => this._possibleCaus; set => this._possibleCaus = value; }
/// <summary>Backing field for <see cref="RecommendedAction" /> property.</summary>
private string _recommendedAction;
/// <summary>Recommended action to resolve error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string RecommendedAction { get => this._recommendedAction; set => this._recommendedAction = value; }
/// <summary>Backing field for <see cref="RecoveryProviderErrorMessage" /> property.</summary>
private string _recoveryProviderErrorMessage;
/// <summary>DRA error message.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string RecoveryProviderErrorMessage { get => this._recoveryProviderErrorMessage; set => this._recoveryProviderErrorMessage = value; }
/// <summary>Backing field for <see cref="SummaryMessage" /> property.</summary>
private string _summaryMessage;
/// <summary>Summary message of the entity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string SummaryMessage { get => this._summaryMessage; set => this._summaryMessage = value; }
/// <summary>Creates an new <see cref="HealthError" /> instance.</summary>
public HealthError()
{
}
}
/// Health Error
public partial interface IHealthError :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable
{
/// <summary>Error creation time (UTC)</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Error creation time (UTC)",
SerializedName = @"creationTimeUtc",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? CreationTimeUtc { get; set; }
/// <summary>ID of the entity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"ID of the entity.",
SerializedName = @"entityId",
PossibleTypes = new [] { typeof(string) })]
string EntityId { get; set; }
/// <summary>Category of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Category of error.",
SerializedName = @"errorCategory",
PossibleTypes = new [] { typeof(string) })]
string ErrorCategory { get; set; }
/// <summary>Error code.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Error code.",
SerializedName = @"errorCode",
PossibleTypes = new [] { typeof(string) })]
string ErrorCode { get; set; }
/// <summary>Level of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Level of error.",
SerializedName = @"errorLevel",
PossibleTypes = new [] { typeof(string) })]
string ErrorLevel { get; set; }
/// <summary>Error message.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Error message.",
SerializedName = @"errorMessage",
PossibleTypes = new [] { typeof(string) })]
string ErrorMessage { get; set; }
/// <summary>Source of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Source of error.",
SerializedName = @"errorSource",
PossibleTypes = new [] { typeof(string) })]
string ErrorSource { get; set; }
/// <summary>Type of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Type of error.",
SerializedName = @"errorType",
PossibleTypes = new [] { typeof(string) })]
string ErrorType { get; set; }
/// <summary>
/// The inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is
/// used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing
/// the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception
/// -> InnerException.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception -> InnerException.",
SerializedName = @"innerHealthErrors",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IInnerHealthError) })]
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IInnerHealthError[] InnerHealthError { get; set; }
/// <summary>Possible causes of error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Possible causes of error.",
SerializedName = @"possibleCauses",
PossibleTypes = new [] { typeof(string) })]
string PossibleCaus { get; set; }
/// <summary>Recommended action to resolve error.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Recommended action to resolve error.",
SerializedName = @"recommendedAction",
PossibleTypes = new [] { typeof(string) })]
string RecommendedAction { get; set; }
/// <summary>DRA error message.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"DRA error message.",
SerializedName = @"recoveryProviderErrorMessage",
PossibleTypes = new [] { typeof(string) })]
string RecoveryProviderErrorMessage { get; set; }
/// <summary>Summary message of the entity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Summary message of the entity.",
SerializedName = @"summaryMessage",
PossibleTypes = new [] { typeof(string) })]
string SummaryMessage { get; set; }
}
/// Health Error
internal partial interface IHealthErrorInternal
{
/// <summary>Error creation time (UTC)</summary>
global::System.DateTime? CreationTimeUtc { get; set; }
/// <summary>ID of the entity.</summary>
string EntityId { get; set; }
/// <summary>Category of error.</summary>
string ErrorCategory { get; set; }
/// <summary>Error code.</summary>
string ErrorCode { get; set; }
/// <summary>Level of error.</summary>
string ErrorLevel { get; set; }
/// <summary>Error message.</summary>
string ErrorMessage { get; set; }
/// <summary>Source of error.</summary>
string ErrorSource { get; set; }
/// <summary>Type of error.</summary>
string ErrorType { get; set; }
/// <summary>
/// The inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is
/// used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing
/// the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception
/// -> InnerException.
/// </summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IInnerHealthError[] InnerHealthError { get; set; }
/// <summary>Possible causes of error.</summary>
string PossibleCaus { get; set; }
/// <summary>Recommended action to resolve error.</summary>
string RecommendedAction { get; set; }
/// <summary>DRA error message.</summary>
string RecoveryProviderErrorMessage { get; set; }
/// <summary>Summary message of the entity.</summary>
string SummaryMessage { get; set; }
}
} | 54.313208 | 413 | 0.655458 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/HealthError.cs | 14,129 | C# |
using MasterDevs.ChromeDevTools;
namespace MasterDevs.ChromeDevTools.Protocol.Network
{
/// <summary>
/// Fired when WebSocket is closed.
/// </summary>
[Event(ProtocolName.Network.WebSocketClosed)]
public class WebSocketClosedEvent
{
/// <summary>
/// Gets or sets Request identifier.
/// </summary>
public string RequestId { get; set; }
/// <summary>
/// Gets or sets Timestamp.
/// </summary>
public double Timestamp { get; set; }
}
}
| 22 | 52 | 0.681818 | [
"MIT"
] | brewdente/AutoWebPerf | MasterDevs.ChromeDevTools/Protocol/Network/WebSocketClosedEvent.cs | 462 | C# |
using NUnit.Framework;
using System;
namespace nerderies.TelegramBotApi.UnitTests.Parameters
{
public class MultipartStringParameterTests
{
[Test]
public void Constructor_NullParameter_Throws()
{
Assert.Throws<ArgumentException>(() => new MultiPartStringParameter(null, "A"));
Assert.Throws<ArgumentException>(() => new MultiPartStringParameter("A", null));
Assert.Throws<ArgumentException>(() => new MultiPartStringParameter(null, null));
}
}
}
| 31.058824 | 93 | 0.668561 | [
"MIT"
] | devnulli/TelegramBotApi.NET | TelegramBotApi/TelegramBotApi.UnitTests/QueryParameters/MultipartStringParameterTests.cs | 530 | C# |
using FusionPlusPlus.Engine.Model;
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace FusionPlusPlus.Engine.Parser
{
public class LogItemParser
{
public static CultureInfo _fallbackFormatProvider = new CultureInfo("en-US");
public LogItem Parse(string value)
{
value = value.Trim(new char[] { '\r', '\n' });
var result = new LogItem();
result.FullMessage = value;
result.AccumulatedState = LogItem.State.Information;
var lines = value.Split(LineSeparators, StringSplitOptions.None);
foreach (var line in lines)
{
if (result.TimeStampUtc.Year == 1)
FindDate(line, d => result.TimeStampUtc = d.ToUniversalTime());
AddValueIfRelevant(line, "DisplayName", s => result.DisplayName = s);
AddValueIfRelevant(line, "AppName", s => result.AppName = s);
AddValueIfRelevant(line, "AppBase", s => result.AppBase = s);
AddValueIfRelevant(line, "PrivatePath", s => result.PrivatePath = s);
AddValueIfRelevant(line, "DynamicPath", s => result.DynamicPath = s);
AddValueIfRelevant(line, "CacheBase", s => result.CacheBase = s);
AddValueIfRelevant(line, "Calling Assembly", s => result.CallingAssembly = s);
AddValueIfRelevant(line, "Aufruf von Assembly", s => result.CallingAssembly = s);
if (line.Contains("The operation failed.") || line.Contains("Fehler bei diesem Vorgang."))
result.AccumulatedState = LogItem.State.Error;
if (result.AccumulatedState == LogItem.State.Error)
continue;
if (line.StartsWith("WRN", StringComparison.OrdinalIgnoreCase))
result.AccumulatedState = LogItem.State.Warning;
else if (line.StartsWith("ERR", StringComparison.OrdinalIgnoreCase))
result.AccumulatedState = LogItem.State.Error;
}
return result;
}
private void AddValueIfRelevant(string content, string keyword, Action<string> setter)
{
var match = Regex.Match(content, $@"(?<={keyword}\s*[=|:]).*?$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (match.Success)
{
var value = match.Value.Trim().TrimEnd('.');
if (string.Equals(value, "NULL", StringComparison.OrdinalIgnoreCase))
return;
setter(value);
}
}
private bool FindDate(string content, Action<DateTime> setter)
{
var match = Regex.Match(content, @"(?<=\().*?@.*?(?=\))");
if (match.Success)
{
var value = match.Value.Trim().Replace("@", "");
if (DateTime.TryParse(value, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeLocal, out DateTime result))
{
setter(result);
return true;
}
if (DateTime.TryParse(value, _fallbackFormatProvider, DateTimeStyles.AssumeLocal, out DateTime fallbackResult))
{
setter(fallbackResult);
return true;
}
}
return false;
}
internal string[] LineSeparators { get; } = new string[] { Environment.NewLine, "\n" };
}
}
| 31.195652 | 118 | 0.68676 | [
"MIT"
] | bogdan-h/Fusion | Fusion++.Engine/Parser/LogItemParser.cs | 2,872 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Demos
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HierarchicalItemsTemplate : ContentPage
{
public class HierarchicalItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public HierarchicalItem(string name)
{
this.name = name;
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
private ObservableCollection<HierarchicalItem> children = new ObservableCollection<HierarchicalItem>();
public ObservableCollection<HierarchicalItem> Children
{
get
{
return children;
}
}
}
private HierarchicalItem root;
public HierarchicalItem Root
{
get
{
return root;
}
}
public HierarchicalItemsTemplate()
{
InitializeComponent ();
root = new HierarchicalItem("Root");
root.Children.Add(new HierarchicalItem("1"));
root.Children[0].Children.Add(new HierarchicalItem("1.1"));
root.Children[0].Children.Add(new HierarchicalItem("1.2"));
root.Children[0].Children.Add(new HierarchicalItem("1.3"));
root.Children.Add(new HierarchicalItem("2"));
root.Children[1].Children.Add(new HierarchicalItem("2.1"));
root.Children[1].Children.Add(new HierarchicalItem("2.2"));
root.Children[1].Children.Add(new HierarchicalItem("2.3"));
root.Children.Add(new HierarchicalItem("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nSed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor."));
root.Children[2].Children.Add(new HierarchicalItem("3.1"));
root.Children[2].Children.Add(new HierarchicalItem("3.2"));
root.Children[2].Children.Add(new HierarchicalItem("3.3"));
root.Children[2].Children[0].Children.Add(new HierarchicalItem("Lorem ipsum dolor sit amet"));
this.BindingContext = this;
}
}
} | 33.409639 | 213 | 0.586008 | [
"MIT"
] | kevinbrunet/SkiaSharp.DiagramEngine | Demos/Demos/HierarchicalItemsTemplate.xaml.cs | 2,775 | C# |
namespace CommandPattern
{
using Core;
using Core.Contracts;
public class StartUp
{
public static void Main(string[] args)
{
ICommandInterpreter command = new CommandInterpreter();
IEngine engine = new Engine(command);
engine.Run();
}
}
}
| 20.0625 | 67 | 0.570093 | [
"MIT"
] | ivanov-mi/SoftUni-Training | 03CSharpOOP/07ReflectionAndAttributes/01CommandPattern/StartUp.cs | 323 | C# |
using System.Collections.Generic;
namespace HairSalon.Models
{
public class Client
{
public string Name { get; set; }
public int ClientId { get; set; }
public string Description { get; set; }
public int StylistId { get; set; }
public virtual Stylist Stylist { get; set; }
}
} | 20.466667 | 48 | 0.654723 | [
"MIT"
] | Brenthubbard/HairSalon.Solution | HairSalon/Models/Client.cs | 307 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace Ytg.ServerWeb.Page.Bank {
public partial class ytg_user_recharge {
}
}
| 22.5 | 81 | 0.322222 | [
"Apache-2.0"
] | heqinghua/lottery-code-qq-814788821- | YtgProject/Ytg.Server/Page/Bank/ytg_user_recharge.aspx.designer.cs | 474 | C# |
using System;
namespace Domain0.Auth.AspNet.Example
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 19.25 | 69 | 0.613636 | [
"MIT"
] | LavrentyAfanasiev/domain0 | examples/Domain0.Auth.AspNet.Example/WeatherForecast.cs | 308 | C# |
using System;
namespace Hamburgueria_Tarde.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.636364 | 70 | 0.680556 | [
"MIT"
] | GabrielMelegaro/HamburgueriaWEBMVC | Models/ErrorViewModel.cs | 216 | C# |
public class Solution {
public int FindLUSlength(string[] strs) {
//sort the array by length descendinly
if(strs.Length == 0) return -1;
Array.Sort(strs, (a, b) => b.Length - a.Length);
for(var i = 0 ; i < strs.Length; ++i){
var isSubsequence = false;
for(var j = 0; j < strs.Length; ++j){
if(j == i) continue;
isSubsequence = IsSubsequence(strs[i], strs[j]);
if(isSubsequence) break;
}
if(!isSubsequence) return strs[i].Length;
}
return -1;
}
//check if a is subsequence of b
private bool IsSubsequence(string a, string b){
if(a.Length > b.Length) return false;
if(a.Length == b.Length) {
if(a == b) return true;
else return false;
}
var i = 0;
foreach(var c in b)
if(i < a.Length && a[i] == c) i++;
return i == a.Length;
}
} | 32.633333 | 64 | 0.490296 | [
"MIT"
] | webigboss/Leetcode | 522. Longest Uncommon Subsequence II/522_Original_Sort_CheckSubsequence.cs | 979 | C# |
// ============================================================================
// FileName: Record.cs
//
// Description:
//
//
// Author(s):
// Alphons van der Heijden
//
// History:
// 28 Mar 2008 Aaron Clauson Added to sipswitch code base based on http://www.codeproject.com/KB/library/DNS.NET_Resolver.aspx.
//
// License:
// The Code Project Open License (CPOL) https://www.codeproject.com/info/cpol10.aspx
// ============================================================================
// Stuff records are made of
namespace Heijden.DNS
{
public abstract class Record
{
/// <summary>
/// The Resource Record this RDATA record belongs to
/// </summary>
public RR RR;
}
}
| 25.965517 | 130 | 0.4834 | [
"BSD-3-Clause"
] | SubportBE/sipsorcery | src/net/DNS/Records/Record.cs | 753 | C# |
using Fpl.Client.Abstractions;
using Fpl.Client.Models;
using FplBot.Data.Slack;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using Slackbot.Net.Endpoints.Hosting;
using Slackbot.Net.SlackClients.Http;
using Slackbot.Net.SlackClients.Http.Exceptions;
namespace FplBot.WebApi.Pages.Admin.TeamDetails;
public class TeamDetailsIndex : PageModel
{
private readonly ISlackTeamRepository _teamRepo;
private readonly ISlackClientBuilder _builder;
private readonly ILeagueClient _leagueClient;
private readonly IOptions<OAuthOptions> _slackAppOptions;
private readonly ILogger<TeamDetailsIndex> _logger;
public TeamDetailsIndex(ISlackTeamRepository teamRepo, ILogger<TeamDetailsIndex> logger, IOptions<OAuthOptions> slackAppOptions, ISlackClientBuilder builder, ILeagueClient leagueClient)
{
_teamRepo = teamRepo;
_logger = logger;
_slackAppOptions = slackAppOptions;
_builder = builder;
_leagueClient = leagueClient;
}
public async Task OnGet(string teamId)
{
var teamIdToUpper = teamId.ToUpper();
var team = await _teamRepo.GetTeam(teamIdToUpper);
if (team != null)
{
Team = team;
if (team.FplbotLeagueId.HasValue)
{
var league = await _leagueClient.GetClassicLeague(team.FplbotLeagueId.Value, tolerate404:true);
League = league;
}
var slackClient = await CreateSlackClient(teamIdToUpper);
try
{
var channels = await slackClient.ConversationsListPublicChannels(500);
ChannelStatus = channels.Channels.FirstOrDefault(c => team.FplBotSlackChannel == $"#{c.Name}" || team.FplBotSlackChannel == c.Id) != null;
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
}
}
}
public ClassicLeague League { get; set; }
public bool? ChannelStatus { get; set; }
public async Task<IActionResult> OnPost(string teamId)
{
_logger.LogInformation($"Deleting {teamId}");
var slackClient = await CreateSlackClient(teamId);
try
{
var res = await slackClient.AppsUninstall(_slackAppOptions.Value.CLIENT_ID, _slackAppOptions.Value.CLIENT_SECRET);
if (res.Ok)
{
TempData["msg"] = "Uninstall queued, and will be handled at some point";
}
else
{
TempData["msg"] = $"Uninstall failed '{res.Error}'";
}
}
catch (WellKnownSlackApiException e) when (e.Message == "account_inactive")
{
await _teamRepo.DeleteByTeamId(teamId);
TempData["msg"] = "Token no longer valid. Team deleted.";
}
return RedirectToPage("../Index");
}
private async Task<ISlackClient> CreateSlackClient(string teamId)
{
var team = await _teamRepo.GetTeam(teamId);
var slackClient = _builder.Build(token: team.AccessToken);
return slackClient;
}
public SlackTeam Team { get; set; }
}
| 34.44086 | 189 | 0.639713 | [
"MIT"
] | Eszra92/fplbot | src/FplBot.WebApi/Pages/Admin/TeamDetails/Show.cshtml.cs | 3,203 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.