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 ProxyServices.Messages;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ProxyServices.Models;
namespace ProxyServices
{
public class Server : Proxy
{
private readonly TcpListener _listener;
private readonly int _bufferSize;
private readonly bool advertisementFilter;
private readonly bool caching;
private readonly bool privacyFilter;
private readonly byte[] _buffer;
private readonly CacheControl _cache;
private readonly SynchronizationContext uiContext = SynchronizationContext.Current;
private bool _listening;
public Server(int port, int bufferSize, ProxyUiEventArgs args)
{
_bufferSize = bufferSize;
_listening = true;
_listener = new TcpListener(IPAddress.Any, port);
_buffer = new byte[_bufferSize];
advertisementFilter = args.AdvertisementFilterEnabled;
privacyFilter = args.PrivacyFilterEnabled;
caching = args.CacheEnabled;
_cache = new CacheControl();
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
try
{
_listener.Start();
_ = Listen();
}
catch (Exception ex)
{
AddUiMessage(ex);
}
}
/// <summary>
/// Start listening for incoming clients on a different thread
/// </summary>
private async Task Listen()
{
AddUiMessage("Proxy Started", "TCP");
while (_listening)
{
try
{
var c = await _listener.AcceptTcpClientAsync();
_ = Task.Run(() => HandleConnection(c));
}
catch (Exception ex)
{
AddUiMessage(ex);
}
}
}
/// <summary>
/// Handles the connection from a tcp client, reads the http message, sends a request to the client and writes it back to original tcp client.
/// </summary>
/// <param name="socket"></param>
private async Task HandleConnection(TcpClient socket)
{
using (var ns = socket.GetStream())
{
if (!_listening) return;
var request = GetHttpRequest(ns);
uiContext.Send(x => AddUiMessage(request.GetHeaders(), "Request"), null);
var ms = HandleCache(request, ns);
SetCache(ms, request);
}
}
/// <summary>
/// Gets the HTTP request from stream
/// </summary>
/// <param name="ns"></param>
/// <returns></returns>
private HttpRequest GetHttpRequest(NetworkStream ns)
{
var stringBuilder = new StringBuilder();
do
{
var readBytes = ns.Read(_buffer, 0, _bufferSize);
stringBuilder.AppendFormat("{0}", Encoding.ASCII.GetString(_buffer, 0, readBytes));
} while (ns.DataAvailable);
var message = stringBuilder.ToString();
stringBuilder.Clear();
var request = new HttpRequest(message);
if (privacyFilter && request.Headers["User-Agent"] != null)
{
request.Headers["User-Agent"] = "Proxy";
}
return request;
}
/// <summary>
/// Gets request from client or out of the cache pool
/// </summary>
/// <param name="request"></param>
/// <param name="ns"></param>
/// <returns></returns>
private MemoryStream HandleCache(HttpRequest request, NetworkStream ns)
{
if (!caching)
{
return SentWithClient(request, ns);
}
var cacheItem = _cache.GetCacheItem(request);
return cacheItem == null ? SentWithClient(request, ns) : SentCached(cacheItem, ns);
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="ns"></param>
/// <returns></returns>
private MemoryStream SentWithClient(HttpRequest request, NetworkStream ns)
{
var client = new Client(_bufferSize, advertisementFilter);
var ms = client.HandleConnection(request, ns);
var response = new HttpResponse(ms.ToArray());
uiContext.Send(x => AddUiMessage(response.GetHeaders(), "Response"), null);
return ms;
}
/// <summary>
///
/// </summary>
/// <param name="cacheItem"></param>
/// <param name="ns"></param>
/// <returns></returns>
private MemoryStream SentCached(CacheItem cacheItem, NetworkStream ns)
{
var ms = cacheItem.ResponseBytes;
var response = new HttpResponse(ms.ToArray());
var count = 0;
if (ms.Length > _bufferSize)
{
while (count < ms.Length)
{
if (count > ms.Length)
{
count -= (count - Convert.ToInt32(ms.Length));
}
ns.Write(ms.GetBuffer(), count, _bufferSize);
count += _bufferSize;
}
}
else
{
ns.Write(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}
uiContext.Send(x => AddUiMessage(response.GetHeaders(), "Cached Response"), null);
return ms;
}
/// <summary>
/// Set response to HttpResponse and set to cache
/// </summary>
/// <param name="ms"></param>
/// <param name="request"></param>
private void SetCache(MemoryStream ms, HttpRequest request)
{
if (caching && ms != null)
{
_cache.AddToCache(new CacheItem
{
Url = request.Url,
ExpireTime = DateTime.Now.AddDays(30),
Response = new HttpResponse(ms.ToArray()),
ResponseBytes = ms,
});
}
}
/// <summary>
/// Disposes the Server and sets it to off
/// </summary>
public void Stop()
{
_listening = false;
_listener.Stop();
AddUiMessage("Closed connection", "TCP");
}
}
}
| 30.821918 | 150 | 0.504148 | [
"MIT"
] | bramerto/NotS-WIN | Proxy/Server.cs | 6,752 | C# |
using UnityEngine;
using System.Collections;
public class TitleGUI : MonoBehaviour {
public GameObject Optionsandstatusholder;
public int Qlevel;
public int Opscreenon;
// OnGUI is called once per frame
void OnGUI () {
if(GUI.Button(new Rect(65,410,200,30), "START")){
Application.LoadLevel(1);
}
if(GUI.Button(new Rect(275,410,200,30), "OPTIONS")){
if (Opscreenon == 0){
Optionsandstatus.Optionsscreenactive = 1;
Opscreenon = 1;
}
else{
Optionsandstatus.Optionsscreenactive = 0;
Opscreenon = 0;
}
}
if (CrossSceneVars.Developmode ==1 || Optionsandstatus.Champmodeunlocked == 1){
if(GUI.Button(new Rect(485,410,200,30), "CHAMPION MODE")){
Application.LoadLevel(4);
}
}
else{
GUI.Box(new Rect(485,410,200,30), "CHAMPION MODE (LOCKED)");
GUI.Label(new Rect(515, 440, 200, 30), "Blow up core to unlock");
}
}
void Start () {
Qlevel = Optionsandstatus.Maxquality;
if (Qlevel == 1){
QualitySettings.currentLevel = QualityLevel.Fastest;
}
if (Qlevel == 2){
QualitySettings.currentLevel = QualityLevel.Fast;
}
if (Qlevel == 3){
QualitySettings.currentLevel = QualityLevel.Simple;
}
if (Qlevel == 4){
QualitySettings.currentLevel = QualityLevel.Good;
}
if (Qlevel == 5){
QualitySettings.currentLevel = QualityLevel.Beautiful;
}
if (Qlevel == 6){
QualitySettings.currentLevel = QualityLevel.Fantastic;
}
if (GameObject.FindGameObjectWithTag("OAS")){
//Instantiate(CrossSceneVarHolder, new Vector3(0,0,0), Quaternion.identity);
}
else{
Instantiate(Optionsandstatusholder, new Vector3(0,0,0), Quaternion.identity);
}
}
}
| 24.626866 | 81 | 0.681212 | [
"MIT"
] | RS17/Tunnel-Strike | Assets/Title/TitleGUI.cs | 1,650 | C# |
using BaseballHistory.Domain.Entities;
using BaseballHistory.Domain.Filters;
using BaseballHistory.Domain.Helpers;
using BaseballHistory.Domain.Services;
using BaseballHistory.Domain.Supervisor;
using Microsoft.AspNetCore.Mvc;
namespace BaseballHistory.API.Controllers;
[Route("api/[controller]")]
[ApiController]
public class TeamsFranchiseController : ControllerBase
{
private readonly IBaseballHistorySupervisor _supervisor;
private readonly ILogger<TeamsFranchiseController> _logger;
private readonly IUriService _uriService;
public TeamsFranchiseController(IBaseballHistorySupervisor baseballHistorySupervisor,
ILogger<TeamsFranchiseController> logger, IUriService uriService)
{
_supervisor = baseballHistorySupervisor;
_logger = logger;
_uriService = uriService;
}
[HttpGet("{pageNumber}/{pageSize}")]
public async Task<ActionResult<List<TeamsFranchise>>> Get(int pageNumber, int pageSize)
{
try
{
pageNumber = pageNumber < 1 ? 1 : pageNumber;
var route = Request.Path.Value!;
var validFilter = new PaginationFilter(pageNumber, pageSize);
var pagedData = await _supervisor.GetTeamsFranchise(pageNumber, pageSize);
var totalRecords = await _supervisor.GetTeamsFranchiseCount();
var pagedReponse = PaginationHelper.CreatePagedReponse(pagedData, validFilter, totalRecords, _uriService, route);
return new ObjectResult(pagedReponse);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside the TeamsFranchiseController Get action: {ex}");
return StatusCode(500, "Internal server error");
}
}
// franchId
[HttpGet("{franchId}", Name = "GetTeamsFranchiseById")]
public async Task<ActionResult<TeamsFranchise>> Get(string franchId)
{
try
{
var entity = await _supervisor.GetTeamsFranchiseById(franchId);
if (entity == null) return NotFound();
return Ok(entity);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside the TeamsFranchiseController GetById action: {ex}");
return StatusCode(500, "Internal server error");
}
}
} | 36.793651 | 125 | 0.685073 | [
"MIT"
] | cwoodruff/baseball-history | BaseballHistoryAPI/BaseballHistory.API/Controllers/TeamsFranchiseController.cs | 2,318 | C# |
using UnityEngine;
using System.Collections;
// Cartoon FX - (c) 2015 Jean Moreno
public class CFX_Demo_RandomDirectionTranslate : MonoBehaviour
{
public float speed = 30.0f;
public Vector3 baseDir = Vector3.zero;
public Vector3 axis = Vector3.forward;
public bool gravity;
private Vector3 dir;
void Start ()
{
dir = new Vector3(Random.Range(0.0f,360.0f),Random.Range(0.0f,360.0f),Random.Range(0.0f,360.0f)).normalized;
dir.Scale(axis);
dir += baseDir;
}
void Update ()
{
this.transform.Translate(dir * speed * Time.deltaTime);
if(gravity)
{
this.transform.Translate(Physics.gravity * Time.deltaTime);
}
}
}
| 20.83871 | 110 | 0.70743 | [
"MIT"
] | 12195302inha/ShootingGame | Assets/JMO Assets/Cartoon FX/Demo/Assets/CFX_Demo_RandomDirectionTranslate.cs | 646 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace WarOfEmpires.Models.Attacks {
public sealed class ExecuteAttackModel {
public int DefenderId { get; set; }
public string DisplayName { get; set; }
public int Population { get; set; }
public bool HasWarDamage { get; set; }
[DisplayName("Attack type")]
[Required(ErrorMessage = "Attack type is required")]
public string AttackType { get; set; }
[DisplayName("Number of turns")]
[Required(ErrorMessage = "Number of turns is required")]
[RegularExpression("^([1-9]|10)$", ErrorMessage = "Number of turns must be a valid number between 1 and 10")]
public int Turns { get; set; }
public bool IsTruce { get; set; }
public List<string> ValidAttackTypes { get; set; }
}
} | 38.956522 | 117 | 0.651786 | [
"MIT"
] | maikelbos0/WarOfEmpires | WarOfEmpires.Models/Attacks/ExecuteAttackModel.cs | 898 | C# |
using CSharpier.Tests.TestFileTests;
using NUnit.Framework;
namespace CSharpier.Tests.TestFiles
{
public class InterfaceDeclarationTests : BaseTest
{
[Test]
public void InterfaceDeclarations()
{
this.RunTest("InterfaceDeclaration", "InterfaceDeclarations");
}
}
}
| 21.4 | 74 | 0.666667 | [
"MIT"
] | brikabrak/csharpier | Src/CSharpier.Tests/TestFiles/InterfaceDeclaration/_InterfaceDeclarationTests.cs | 321 | C# |
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
using TMPro;
public class Menu : Elemento
{
private float progressoLoad;
private GameObject load;
private bool carregando;
private float timer;
private int cenaId;
private void Start()
{
carregando = false;
timer = 0;
}
private void Update()
{
if (carregando)
{
timer += Time.deltaTime;
}
if (timer >= 0.5f)
{
StartCoroutine(CarregarParalelo(cenaId));
}
}
public static void AbrirMenu(GameObject menu)
{
menu.SetActive(true);
}
public static void FecharMenu(GameObject menu)
{
menu.SetActive(false);
}
public static void HabilitarBotao(GameObject botao)
{
botao.GetComponent<Button>().interactable = true;
}
public static void DesabilitarBotao(GameObject botao)
{
botao.GetComponent<Button>().interactable = false;
}
public static void CarregarCena(int cenaId)
{
SceneManager.LoadScene(cenaId);
}
public void LoadObjeto(GameObject load)
{
carregando = true;
this.load = Instantiate(load, gameObject.transform);
this.load.SetActive(true);
}
public void CarregarCenaParalelo(int cenaId)
{
this.cenaId = cenaId;
}
IEnumerator CarregarParalelo(int cenaId)
{
AsyncOperation op = SceneManager.LoadSceneAsync(cenaId);
while (!op.isDone)
{
progressoLoad = Mathf.Clamp01(op.progress / 0.9f);
if (load.GetComponentInChildren<Slider>() != null)
{
load.GetComponentInChildren<Slider>().value = progressoLoad;
load.GetComponentInChildren<TextMeshProUGUI>().text = ((int)progressoLoad * 100) + "%";
}
yield return null;
}
}
public void Pausar(bool pausar)
{
if (pausar)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
}
| 23.910112 | 103 | 0.579417 | [
"Unlicense"
] | GabrielMendesM/WhackAMole | Whack A Mole/Assets/Desenvolvimento/Scripts/Menu.cs | 2,128 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace WebAPI_NG_TokenbasedAuth.Models
{
// Models used as parameters to AccountController actions.
public class AddExternalLoginBindingModel
{
[Required]
[Display(Name = "External access token")]
public string ExternalAccessToken { get; set; }
}
public class ChangePasswordBindingModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class RegisterBindingModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class RegisterExternalBindingModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
public class RemoveLoginBindingModel
{
[Required]
[Display(Name = "Login provider")]
public string LoginProvider { get; set; }
[Required]
[Display(Name = "Provider key")]
public string ProviderKey { get; set; }
}
public class SetPasswordBindingModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| 31.905882 | 110 | 0.623525 | [
"MIT"
] | FernandoPucci/WebAPI | WebAPI_NG_TokenbasedAuth/WebAPI_NG_TokenbasedAuth/Models/AccountBindingModels.cs | 2,714 | C# |
namespace RecruitmentTool.WebApi.Infrastructure.ServiceExtensions
{
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.DependencyInjection;
public static class VersioningExtension
{
public static void AddVersioning(this IServiceCollection services)
{
services.AddApiVersioning(
config =>
{
config.ReportApiVersions = true;
config.AssumeDefaultVersionWhenUnspecified = true;
config.DefaultApiVersion = new ApiVersion(1, 0);
config.ApiVersionReader = new HeaderApiVersionReader("api-version");
});
services.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
// note: this option is only necessary when versioning by url segment. the SubstitutionFormat
// can also be used to control the format of the API version in route templates
options.SubstituteApiVersionInUrl = true;
});
}
}
}
| 36.90625 | 113 | 0.591025 | [
"MIT"
] | 3nch3v/RecruitmentTool | src/RecruitmentTool.WebApi/Infrastructure/ServiceExtensions/VersioningExtension.cs | 1,183 | C# |
//-------------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2019 Tasharen Entertainment Inc
//-------------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIButtonKeys))]
#else
[CustomEditor(typeof(UIButtonKeys), true)]
#endif
public class UIButtonKeysEditor : UIKeyNavigationEditor
{
public override void OnInspectorGUI ()
{
base.OnInspectorGUI();
EditorGUILayout.HelpBox("This component has been replaced by UIKeyNavigation.", MessageType.Warning);
if (GUILayout.Button("Auto-Upgrade"))
{
NGUIEditorTools.ReplaceClass(serializedObject, typeof(UIKeyNavigation));
Selection.activeGameObject = null;
}
}
}
| 26.275862 | 103 | 0.65748 | [
"Unlicense"
] | AhriHaran/Unity | 3DRPG/Assets/NGUI/Scripts/Editor/UIButtonKeysEditor.cs | 763 | C# |
using ClickerGame.Models;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// スコア表示用ビュー。
/// </summary>
public class ScoreView : MonoBehaviour
{
/// <summary>
/// スコア表示テキスト。
/// </summary>
[SerializeField]
private Text _scoreText = null;
/// <summary>
/// 表示する通貨型。
/// </summary>
public CurrencyType CurrencyType => _currencyType;
[SerializeField]
private CurrencyType _currencyType = CurrencyType.None;
/// <summary>
/// 表示する通貨インベントリー。
/// </summary>
public CurrencyInventory DataSource
{
get => _dataSource;
set
{
if (_dataSource != null)
{
_dataSource.Changed -= OnDataSourceChanged;
}
_dataSource = value;
if (_dataSource != null)
{
_dataSource.Changed += OnDataSourceChanged;
}
}
}
private CurrencyInventory _dataSource;
/// <summary>
/// 表示中の通貨。
/// </summary>
public Currency Currency
{
get => _currency;
private set
{
_currency = value;
var q = _dataSource.GetQuantity(CurrencyType);
_scoreText.text = q.ToString("F") + CurrencyType;
}
}
private Currency _currency;
private void Start()
{
Currency = new Currency(CurrencyType, 0);
}
private void OnDataSourceChanged(Currency currency)
{
if (currency.Type == CurrencyType)
{
Currency = currency;
}
}
}
| 21.625 | 61 | 0.544637 | [
"MIT"
] | KuniTatsu/GameJam | Assets/Scripts/Views/ScoreView.cs | 1,657 | C# |
using AvalonCode.Services.Models;
using Microsoft.CodeAnalysis.MSBuild;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AvalonCode.Services.Implementation
{
internal class SolutionExplorer : ISolutionExplorer
{
public SolutionHost? CurrentSolution { get; private set; }
public async Task<SolutionHost> OpenSolution(string solutionFilePath, IEnumerable<Assembly>? additionalAssemblies = null, CancellationToken cancellationToken = default)
{
await CloseSolution();
var workspace = MSBuildWorkspace.Create();
await workspace.OpenSolutionAsync(solutionFilePath, cancellationToken: cancellationToken);
var solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(solutionFilePath);
var solutionInfo = new SolutionHost(workspace, additionalAssemblies);
var solutionItemsDictionary = solutionFile.ProjectsInOrder
.ToDictionary(_=>_.ProjectGuid, _ =>
{
if (_.ProjectType == Microsoft.Build.Construction.SolutionProjectType.SolutionFolder)
return new SolutionFolderItem(_.ProjectName);
if (_.ProjectType == Microsoft.Build.Construction.SolutionProjectType.KnownToBeMSBuildFormat)
return new ProjectItem(_.ProjectName, _.AbsolutePath, workspace);
return (SolutionItem)new UnknownItem(_.ProjectName);
});
foreach (var itemInSolution in solutionFile.ProjectsInOrder)
{
var solutionItem = solutionItemsDictionary[itemInSolution.ProjectGuid];
if (solutionItem == null) continue;
if (itemInSolution.ParentProjectGuid == null)
{
solutionInfo.AddChild(solutionItem);
}
else
{
var parentSolutionItem = solutionItemsDictionary[itemInSolution.ParentProjectGuid];
if (parentSolutionItem == null) continue;
parentSolutionItem.AddChild(solutionItem);
}
}
return CurrentSolution = solutionInfo;
}
public Task CloseSolution()
{
if (CurrentSolution != null)
{
CurrentSolution.Workspace.Dispose();
CurrentSolution = null;
}
return Task.CompletedTask;
}
}
}
| 34.565789 | 176 | 0.609821 | [
"MIT"
] | adospace/AvalonCode | src/AvalonCode.Services/Implementation/SolutionExplorer.cs | 2,629 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DelegatedCommand.cs">
// Copyright© 2021 Ryan Wilson
// Licensed under the MIT license. See LICENSE.md in the solution root for full license information.
// </copyright>
// <summary>
// DelegatedCommand.cs Implementation
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace XIVEVENT {
using System;
using System.Windows.Input;
public class DelegatedCommand : ICommand {
private readonly Func<object, bool> _canExecute;
private readonly Action<object> _execute;
public DelegatedCommand(Action<object> execute) : this(execute, null) { }
public DelegatedCommand(Action<object> execute, Func<object, bool>? canExecute) {
this._execute = execute ?? throw new ArgumentNullException(nameof(execute));
this._canExecute = canExecute ?? (x => true);
}
public event EventHandler CanExecuteChanged {
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object parameter) {
return this._canExecute(parameter);
}
public void Execute(object parameter) {
this._execute(parameter);
}
public void Refresh() {
CommandManager.InvalidateRequerySuggested();
}
}
} | 35.568182 | 120 | 0.546965 | [
"MIT"
] | FFXIVAPP/xivevent | XIVEVENT/DelegatedCommand.cs | 1,568 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Support
{
/// <summary>
/// Gets the reason that a storage account name could not be used. The Reason element is only returned if NameAvailable is
/// false.
/// </summary>
[System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ReasonTypeConverter))]
public partial struct Reason :
System.Management.Automation.IArgumentCompleter
{
/// <summary>
/// Implementations of this function are called by PowerShell to complete arguments.
/// </summary>
/// <param name="commandName">The name of the command that needs argument completion.</param>
/// <param name="parameterName">The name of the parameter that needs argument completion.</param>
/// <param name="wordToComplete">The (possibly empty) word being completed.</param>
/// <param name="commandAst">The command ast in case it is needed for completion.</param>
/// <param name="fakeBoundParameters">This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot
/// or will not attempt to evaluate an argument, in which case you may need to use commandAst.</param>
/// <returns>
/// A collection of completion results, most like with ResultType set to ParameterValue.
/// </returns>
public global::System.Collections.Generic.IEnumerable<global::System.Management.Automation.CompletionResult> CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters)
{
if (global::System.String.IsNullOrEmpty(wordToComplete) || "AccountNameInvalid".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'AccountNameInvalid'", "AccountNameInvalid", global::System.Management.Automation.CompletionResultType.ParameterValue, "AccountNameInvalid");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "AlreadyExists".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'AlreadyExists'", "AlreadyExists", global::System.Management.Automation.CompletionResultType.ParameterValue, "AlreadyExists");
}
}
}
} | 71.214286 | 373 | 0.719157 | [
"MIT"
] | Agazoth/azure-powershell | src/Functions/generated/api/Support/Reason.Completer.cs | 2,950 | C# |
////////PROVISIONAL IMPLEMENTATION////////
////////PROVISIONAL IMPLEMENTATION////////
////////PROVISIONAL IMPLEMENTATION////////
using Microsoft.LiveLabs.JavaScript.IL2JS;
using System.Text;
namespace System.IO
{
/// Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
public class BinaryReader : IDisposable
{
private Stream m_stream;
public BinaryReader(Stream input)
{
this.m_stream = input;
}
public BinaryReader(Stream input, Encoding encoding)
{
this.m_stream = input;
}
public virtual void Close()
{
this.m_stream.Close();
}
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
Stream stream = this.m_stream;
this.m_stream = null;
if (stream != null)
{
stream.Close();
}
}
public virtual int PeekChar() { throw new NotSupportedException(); }
public virtual int Read() { throw new NotSupportedException(); }
public virtual int Read(byte[] buffer, int index, int count) { throw new NotSupportedException(); }
public virtual int Read(char[] buffer, int index, int count) { throw new NotSupportedException(); }
public virtual bool ReadBoolean() { throw new NotSupportedException(); }
public virtual byte ReadByte() { throw new NotSupportedException(); }
public virtual byte[] ReadBytes(int count) { throw new NotSupportedException(); }
public virtual char ReadChar() { throw new NotSupportedException(); }
public virtual char[] ReadChars(int count) { throw new NotSupportedException(); }
public virtual decimal ReadDecimal() { throw new NotSupportedException(); }
public virtual double ReadDouble() { throw new NotSupportedException(); }
public virtual short ReadInt16() { throw new NotSupportedException(); }
public virtual int ReadInt32() { throw new NotSupportedException(); }
public virtual long ReadInt64() { throw new NotSupportedException(); }
public virtual sbyte ReadSByte() { throw new NotSupportedException(); }
public virtual float ReadSingle() { throw new NotSupportedException(); }
public virtual string ReadString() { throw new NotSupportedException(); }
public virtual ushort ReadUInt16() { throw new NotSupportedException(); }
public virtual uint ReadUInt32() { throw new NotSupportedException(); }
public virtual ulong ReadUInt64() { throw new NotSupportedException(); }
public virtual Stream BaseStream { get { return this.m_stream; } }
}
}
| 40.666667 | 107 | 0.634355 | [
"Apache-2.0"
] | Reactive-Extensions/IL2JS | mscorlib/System/IO/BinaryReader.cs | 2,808 | C# |
/*
Copyright 2016 Dominik Werner
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace MipsSim.Model.Mips.Hardware
{
/// <summary>
/// This class is able to execute all real mips instructions
/// </summary>
public class InstructionExecute
{
#region constants
private const int OpCodeStart = 0;
private const int OpCodeEnd = 5;
private const int OpCodeLength = 6;
private const int RsStart = 6;
private const int RsEnd = 10;
private const int RsLength = 5;
private const int RtStart = 11;
private const int RtEnd = 15;
private const int RtLength = 5;
private const int TargetStart = 6;
private const int TargetEnd = 31;
private const int TargetLength = 26;
private const int ImmediateStart = 16;
private const int ImmediateEnd = 31;
private const int ImmediateLength = 16;
private const int RdStart = 16;
private const int RdEnd = 20;
private const int RdLength = 5;
private const int ShamtStart = 21;
private const int ShamtEnd = 25;
private const int ShamtLength = 5;
private const int FunctStart = 26;
private const int FunctEnd = 31;
private const int FunctLength = 6;
#endregion
/// <summary>
/// Execute R Type instruction
/// </summary>
/// <param name="data">instruction in binary form</param>
public void ExecuteRType(bool[] data)
{
bool[] rs = data.GetRange(RsStart, RsLength);
bool[] rt = data.GetRange(RtStart, RtLength);
bool[] rd = data.GetRange(RdStart, RdLength);
bool[] shamt = data.GetRange(ShamtStart, ShamtLength);
bool[] funct = data.GetRange(FunctStart, FunctLength);
string functCode = funct.ToBitString();
bool[] rsValue = Cpu.Instance.GetRegValue(rs);
bool[] rtValue = Cpu.Instance.GetRegValue(rt);
bool[] result = { false };
bool write = false;
bool increasePC = false;
switch (functCode)
{
case AssemblerInstructions.AddFunct:
result = Extensions.AddBinary(rsValue, rtValue);
write = true;
increasePC = true;
if (!rsValue[0] && !rtValue[0] && result[0]) throw new Exception("arithmetic overflow exception");
break;
case AssemblerInstructions.AdduFunct:
result = Extensions.AddBinary(rsValue, rtValue);
write = true;
increasePC = true;
break;
case AssemblerInstructions.AndFunct:
result = rsValue.BitWiseAnd(rtValue);
write = true;
increasePC = true;
break;
case AssemblerInstructions.DivFunct:
Cpu.Instance.SetRegData(Cpu.Instance.Lo.RegisterName, (rsValue.ToInt() / rtValue.ToInt()).ToBits());
Cpu.Instance.SetRegData(Cpu.Instance.Hi.RegisterName, (rsValue.ToInt() % rtValue.ToInt()).ToBits());
increasePC = true;
break;
case AssemblerInstructions.DivuFunct:
Cpu.Instance.SetRegData(Cpu.Instance.Lo.RegisterName, (rsValue.ToInt() / rtValue.ToInt()).ToBits());
Cpu.Instance.SetRegData(Cpu.Instance.Hi.RegisterName, (rsValue.ToInt() % rtValue.ToInt()).ToBits());
increasePC = true;
break;
case AssemblerInstructions.JalrFunct:
result = (Cpu.Instance.PC.Data.ToInt() + 4).ToBits();
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, rsValue);
write = true;
break;
case AssemblerInstructions.JrFunct:
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, rsValue);
break;
case AssemblerInstructions.MfhiFunct:
result = Cpu.Instance.Hi.Data;
increasePC = true;
write = true;
break;
case AssemblerInstructions.MfloFunct:
result = Cpu.Instance.Lo.Data;
increasePC = true;
write = true;
break;
case AssemblerInstructions.MthiFunct:
Cpu.Instance.SetRegData(Cpu.Instance.Hi.RegisterName, Cpu.Instance.GetRegValue(rd));
increasePC = true;
break;
case AssemblerInstructions.MtloFunct:
Cpu.Instance.SetRegData(Cpu.Instance.Lo.RegisterName, Cpu.Instance.GetRegValue(rd));
increasePC = true;
break;
case AssemblerInstructions.MultFunct:
int a = rsValue.ToInt();
int b = rtValue.ToInt();
bool[] product = (rsValue.ToInt() * rtValue.ToInt()).ToBits().ToLength(64);
int p = product.ToInt();
Cpu.Instance.SetRegData(Cpu.Instance.Hi.RegisterName, product.GetRange(0, 32));
Cpu.Instance.SetRegData(Cpu.Instance.Lo.RegisterName, product.GetRange(32, 32));
increasePC = true;
break;
case AssemblerInstructions.MultuFunct:
bool[] productu = (rsValue.ToInt() * rtValue.ToInt()).ToBits().ToLength(64);
Cpu.Instance.SetRegData(Cpu.Instance.Hi.RegisterName, productu.GetRange(0, 32));
Cpu.Instance.SetRegData(Cpu.Instance.Lo.RegisterName, productu.GetRange(32, 32));
increasePC = true;
break;
case AssemblerInstructions.NorFunct:
result = rsValue.BitWiseOr(rtValue).BitWiseNegate();
write = true;
increasePC = true;
break;
case AssemblerInstructions.OrFunct:
result = rsValue.BitWiseOr(rtValue);
write = true;
increasePC = true;
break;
case AssemblerInstructions.SllFunct:
result = rtValue.ShiftLeft(shamt.ToInt());
write = true;
increasePC = true;
break;
case AssemblerInstructions.SllvFunct:
result = rtValue.ShiftLeft(rsValue.ToInt());
write = true;
increasePC = true;
break;
case AssemblerInstructions.SltFunct:
result = (rsValue.ToInt() < rtValue.ToInt()) ? Extensions.GetBitsBitString("01").ToLength(32) : (0).ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.SltuFunct:
result = (rsValue.ToInt() < rtValue.ToInt()) ? Extensions.GetBitsBitString("01").ToLength(32) : (0).ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.SraFunct:
result = rtValue.ShiftRight(getSraShamtTerm(shamt.ToInt(), rtValue));
write = true;
increasePC = true;
break;
case AssemblerInstructions.SravFunct:
result = rtValue.ShiftRight(getSraShamtTerm(rsValue.ToInt(), rtValue));
write = true;
increasePC = true;
break;
case AssemblerInstructions.SrlFunct:
result = rtValue.ShiftRight(shamt.ToInt());
write = true;
increasePC = true;
break;
case AssemblerInstructions.SrlvFunct:
result = rtValue.ShiftRight(rsValue.ToInt());
write = true;
increasePC = true;
break;
case AssemblerInstructions.SubFunct:
result = Extensions.SubstractBinary(rsValue, rtValue);
write = true;
increasePC = true;
break;
case AssemblerInstructions.SubuFunct:
result = Extensions.SubstractBinary(rsValue, rtValue);
write = true;
increasePC = true;
break;
case AssemblerInstructions.XorFunct:
result = rsValue.BitWiseXor(rtValue);
write = true;
increasePC = true;
break;
}
if(write) Cpu.Instance.SetRegData(rd, result.ToLength(32));
if (increasePC) Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + 4).ToBits());
}
/// <summary>
/// Execute I Type Instruction
/// </summary>
/// <param name="data">instruction in binary format</param>
public void ExecuteIType(bool[] data)
{
bool[] opCode = data.GetRange(OpCodeStart, OpCodeLength);
bool[] rs = data.GetRange(RsStart, RsLength);
bool[] rt = data.GetRange(RtStart, RtLength);
bool[] immidiate = data.GetRange(ImmediateStart, ImmediateLength);
bool[] rsValue = Cpu.Instance.GetRegValue(rs);
bool[] result = { false };
bool write = false;
bool increasePC = false;
string opCodeString = opCode.ToBitString();
switch (opCodeString)
{
case AssemblerInstructions.AddiOpCode:
result = Extensions.AddBinary(rsValue, immidiate);
write = true;
increasePC = true;
if (!rsValue[0] && !immidiate[0] && result[0]) throw new Exception("arithmetic overflow exception");
break;
case AssemblerInstructions.AddiuOpCode:
result = Extensions.AddBinary(rsValue, immidiate);
write = true;
increasePC = true;
break;
case AssemblerInstructions.AndiOpCode:
result = rsValue.BitWiseAnd((0).ToBits().JoinArray(immidiate).ToLength(32));
write = true;
increasePC = true;
break;
case AssemblerInstructions.BeqOpCode:
if (rsValue.ToInt() == Cpu.Instance.GetRegValue(rt).ToInt())
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
break;
case AssemblerInstructions.BgezOpCode:
if (rt.ToInt() == 1) // bgez
{
if(rsValue.ToInt() >= 0)
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
}
else // bltz
{
if (rsValue.ToInt() < 0)
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
}
break;
case AssemblerInstructions.BgtzOpCode:
if (rsValue.ToInt() > 0)
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
break;
case AssemblerInstructions.BlezOpCode:
if (rsValue.ToInt() <= 0)
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
break;
case AssemblerInstructions.BneOpCode:
if (rsValue.ToInt() != Cpu.Instance.GetRegValue(rt).ToInt())
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + immidiate.ToInt() * 4).ToBits());
else increasePC = true;
break;
case AssemblerInstructions.LbOpCode:
result = Memory.Instance.Data[rsValue.ToUnsignedInt() + immidiate.ToInt()].ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.LbuOpCode:
result = Memory.Instance.Data[rsValue.ToUnsignedInt() + immidiate.ToInt()].ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.LhOpCode:
bool[] first = Memory.Instance.Data[rsValue.ToUnsignedInt() + immidiate.ToInt()].ToBits();
bool[] second = Memory.Instance.Data[rsValue.ToUnsignedInt() + 4 + immidiate.ToInt()].ToBits();
result = first.JoinArray(second).ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.LhuOpCode:
bool[] firstu = Memory.Instance.Data[rsValue.ToUnsignedInt() + immidiate.ToInt()].ToBits();
bool[] secondu = Memory.Instance.Data[rsValue.ToUnsignedInt() + 4 + immidiate.ToInt()].ToBits();
result = firstu.JoinArray(secondu).ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.LuiOpCode:
result = immidiate.ShiftLeft(16);
write = true;
increasePC = true;
break;
case AssemblerInstructions.LwOpCode:
int offset = immidiate.ToInt();
uint address = (offset >= 0) ? rsValue.ToUnsignedInt() + (uint)offset : rsValue.ToUnsignedInt() - (uint)offset;
//result = reorderForSavingLoadingToMemory(Memory.Instance.LoadWord(address));
result = Memory.Instance.LoadWord(address);
write = true;
increasePC = true;
break;
case AssemblerInstructions.OriOpCode:
result = rsValue.BitWiseOr((0).ToBits().JoinArray(immidiate).ToLength(32));
write = true;
increasePC = true;
break;
case AssemblerInstructions.SbOpCode:
offset = immidiate.ToInt();
address = (offset >= 0) ? rsValue.ToUnsignedInt() + (uint)offset : rsValue.ToUnsignedInt() - (uint)offset;
//Memory.Instance.SaveWord(address, reorderForSavingLoadingToMemory((0).ToBits().JoinArray(Cpu.Instance.GetRegValue(rt).GetRange(24, 8)).ToLength(32)));
Memory.Instance.SaveWord(address, (0).ToBits().JoinArray(Cpu.Instance.GetRegValue(rt).GetRange(24, 8)).ToLength(32));
increasePC = true;
break;
case AssemblerInstructions.SltiOpCode:
result = (rsValue.ToInt() < immidiate.ToInt()) ? Extensions.GetBitsBitString("01").ToLength(32) : (0).ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.SltiuOpCode:
result = (rsValue.ToInt() < immidiate.ToInt()) ? Extensions.GetBitsBitString("01").ToLength(32) : (0).ToBits().ToLength(32);
write = true;
increasePC = true;
break;
case AssemblerInstructions.ShOpCode:
offset = immidiate.ToInt();
address = (offset >= 0) ? rsValue.ToUnsignedInt() + (uint)offset : rsValue.ToUnsignedInt() - (uint)offset;
//Memory.Instance.SaveWord(address, reorderForSavingLoadingToMemory((0).ToBits().JoinArray(Cpu.Instance.GetRegValue(rt).GetRange(16, 16)).ToLength(32)));
Memory.Instance.SaveWord(address, (0).ToBits().JoinArray(Cpu.Instance.GetRegValue(rt).GetRange(16, 16)).ToLength(32));
increasePC = true;
break;
case AssemblerInstructions.SwOpCode:
offset = immidiate.ToInt();
address = (offset >= 0) ? rsValue.ToUnsignedInt() + (uint)offset : rsValue.ToUnsignedInt() - (uint)offset;
//Memory.Instance.SaveWord(address, reorderForSavingLoadingToMemory(Cpu.Instance.GetRegValue(rt)));
Memory.Instance.SaveWord(address, Cpu.Instance.GetRegValue(rt));
increasePC = true;
break;
case AssemblerInstructions.XoriOpCode:
result = rsValue.BitWiseXor((0).ToBits().JoinArray(immidiate).ToLength(32));
write = true;
increasePC = true;
break;
}
if (write) Cpu.Instance.SetRegData(rt, result.ToLength(32));
if (increasePC) Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, (Cpu.Instance.PC.Data.ToInt() + 4).ToBits());
}
/// <summary>
/// (NOT USED ANYMORE)
/// Reorder 32-Bit number in order to correctly save it to the memory.
/// This is nessesary because otherwise the byte order would be wrong
/// and the save method cannot be changed because it is used by the compiler
/// </summary>
/// <param name="data"></param>
/// <returns>0xFF 0x1A 0xB2 0x7F => 0x7F 0xB2 0x1A 0xFF</returns>
private bool[] reorderForSavingLoadingToMemory(bool[] data)
{
byte[] temp = data.ToMipsInstructionBytes();
byte[] newTemp = new byte[4];
newTemp[0] = temp[3];
newTemp[1] = temp[2];
newTemp[2] = temp[1];
newTemp[3] = temp[0];
return newTemp.ToMipsInstructionBits();
}
/// <summary>
/// Execute J Type Instruction
/// </summary>
/// <param name="data">instruction in binary format</param>
public void ExecuteJType(bool[] data)
{
bool[] target = data.GetRange(TargetStart, TargetLength);
bool[] opCode = data.GetRange(OpCodeStart, OpCodeLength);
string opCodeString = opCode.ToBitString();
bool[] suffix = { false, false };
bool[] jumpDestination;
switch (opCodeString)
{
case AssemblerInstructions.JOpCode:
jumpDestination = Cpu.Instance.PC.Data.GetRange(0, 4).JoinArray(target).JoinArray(suffix);
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, jumpDestination);
break;
case AssemblerInstructions.JalOpCode:
bool[] ra = Extensions.AddBinary(Cpu.Instance.PC.Data, (4).ToBits());
Cpu.Instance.SetRegData("$ra", ra);
jumpDestination = Cpu.Instance.PC.Data.GetRange(0, 4).JoinArray(target).JoinArray(suffix);
Cpu.Instance.SetRegData(Cpu.Instance.PC.RegisterName, jumpDestination);
break;
}
}
/// <summary>
/// Get shitf amount for shift right instruction
/// </summary>
/// <param name="shamt">shamt data</param>
/// <param name="rtValue">rt data</param>
/// <returns></returns>
private int getSraShamtTerm(int shamt, bool[] rtValue)
{
int result = 0;
for (int i = 1; i <= shamt; i++) result += (int)Math.Pow(2, 32 - i);
result *= rtValue.ShiftRight(31).ToInt();
result += shamt;
return result;
}
#region Singleton
private InstructionExecute()
{
}
public static InstructionExecute Instance
{
get
{
if (_instance == null) _instance = new InstructionExecute();
return _instance;
}
}
private static InstructionExecute _instance;
#endregion
}
}
| 48.050109 | 174 | 0.514078 | [
"Apache-2.0"
] | dowerner/MipsSim | MipsSim/MipsSim/Model/Mips/Hardware/InstructionExecute.cs | 22,057 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
using Xunit;
namespace Tests.Search.Request
{
/**
* Allows to highlight search results on one or more fields.
* The implementation uses either the lucene `highlighter` or `fast-vector-highlighter`.
*
* See the Elasticsearch documentation on {ref_current}/search-request-body.html#request-body-search-highlighting[highlighting] for more detail.
*/
public class HighlightingUsageTests : SearchUsageTestBase
{
public HighlightingUsageTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
public string LastNameSearch { get; } = Project.First.LeadDeveloper.LastName;
protected override object ExpectJson => new
{
query = new
{
match = new Dictionary<string, object>
{
{
"name.standard", new Dictionary<string, object>
{
{ "query", "Upton Sons Shield Rice Rowe Roberts" }
}
}
}
},
highlight = new
{
pre_tags = new[] { "<tag1>" },
post_tags = new[] { "</tag1>" },
encoder = "html",
highlight_query = new
{
match = new Dictionary<string, object>
{
{
"name.standard", new Dictionary<string, object>
{
{ "query", "Upton Sons Shield Rice Rowe Roberts" }
}
}
}
},
fields = new Dictionary<string, object>
{
{
"name.standard", new Dictionary<string, object>
{
{ "type", "plain" },
{ "force_source", true },
{ "fragment_size", 150 },
{ "fragmenter", "span" },
{ "number_of_fragments", 3 },
{ "no_match_size", 150 }
}
},
{
"leadDeveloper.firstName", new Dictionary<string, object>
{
{ "type", "fvh" },
{ "phrase_limit", 10 },
{ "boundary_max_scan", 50 },
{ "pre_tags", new[] { "<name>" } },
{ "post_tags", new[] { "</name>" } },
{
"highlight_query", new Dictionary<string, object>
{
{
"match", new Dictionary<string, object>
{
{
"leadDeveloper.firstName", new Dictionary<string, object>
{
{ "query", "Kurt Edgardo Naomi Dariana Justice Felton" }
}
}
}
}
}
}
}
},
{
"leadDeveloper.lastName", new Dictionary<string, object>
{
{ "type", "unified" },
{ "pre_tags", new[] { "<name>" } },
{ "post_tags", new[] { "</name>" } },
{
"highlight_query", new Dictionary<string, object>
{
{
"match", new Dictionary<string, object>
{
{
"leadDeveloper.lastName", new Dictionary<string, object>
{
{ "query", LastNameSearch }
}
}
}
}
}
}
}
}
}
}
};
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
.Query(q => q
.Match(m => m
.Field(f => f.Name.Suffix("standard"))
.Query("Upton Sons Shield Rice Rowe Roberts")
)
)
.Highlight(h => h
.PreTags("<tag1>")
.PostTags("</tag1>")
.Encoder(HighlighterEncoder.Html)
.HighlightQuery(q => q
.Match(m => m
.Field(f => f.Name.Suffix("standard"))
.Query("Upton Sons Shield Rice Rowe Roberts")
)
)
.Fields(
fs => fs
.Field(p => p.Name.Suffix("standard"))
.Type("plain")
.ForceSource()
.FragmentSize(150)
.Fragmenter(HighlighterFragmenter.Span)
.NumberOfFragments(3)
.NoMatchSize(150),
fs => fs
.Field(p => p.LeadDeveloper.FirstName)
.Type(HighlighterType.Fvh)
.PreTags("<name>")
.PostTags("</name>")
.BoundaryMaxScan(50)
.PhraseLimit(10)
.HighlightQuery(q => q
.Match(m => m
.Field(p => p.LeadDeveloper.FirstName)
.Query("Kurt Edgardo Naomi Dariana Justice Felton")
)
),
fs => fs
.Field(p => p.LeadDeveloper.LastName)
.Type(HighlighterType.Unified)
.PreTags("<name>")
.PostTags("</name>")
.HighlightQuery(q => q
.Match(m => m
.Field(p => p.LeadDeveloper.LastName)
.Query(LastNameSearch)
)
)
)
);
protected override SearchRequest<Project> Initializer =>
new SearchRequest<Project>
{
Query = new MatchQuery
{
Query = "Upton Sons Shield Rice Rowe Roberts",
Field = "name.standard"
},
Highlight = new Highlight
{
PreTags = new[] { "<tag1>" },
PostTags = new[] { "</tag1>" },
Encoder = HighlighterEncoder.Html,
HighlightQuery = new MatchQuery
{
Query = "Upton Sons Shield Rice Rowe Roberts",
Field = "name.standard"
},
Fields = new Dictionary<Field, IHighlightField>
{
{
"name.standard", new HighlightField
{
Type = HighlighterType.Plain,
ForceSource = true,
FragmentSize = 150,
Fragmenter = HighlighterFragmenter.Span,
NumberOfFragments = 3,
NoMatchSize = 150
}
},
{
"leadDeveloper.firstName", new HighlightField
{
Type = "fvh",
PhraseLimit = 10,
BoundaryMaxScan = 50,
PreTags = new[] { "<name>" },
PostTags = new[] { "</name>" },
HighlightQuery = new MatchQuery
{
Field = "leadDeveloper.firstName",
Query = "Kurt Edgardo Naomi Dariana Justice Felton"
}
}
},
{
"leadDeveloper.lastName", new HighlightField
{
Type = HighlighterType.Unified,
PreTags = new[] { "<name>" },
PostTags = new[] { "</name>" },
HighlightQuery = new MatchQuery
{
Field = "leadDeveloper.lastName",
Query = LastNameSearch
}
}
}
}
}
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldBeValid();
foreach (var highlightsInEachHit in response.Hits.Select(d => d.Highlight))
{
foreach (var highlightField in highlightsInEachHit)
{
if (highlightField.Key == "name.standard")
{
foreach (var highlight in highlightField.Value)
{
highlight.Should().Contain("<tag1>");
highlight.Should().Contain("</tag1>");
}
}
else if (highlightField.Key == "leadDeveloper.firstName")
{
foreach (var highlight in highlightField.Value)
{
highlight.Should().Contain("<name>");
highlight.Should().Contain("</name>");
}
}
else if (highlightField.Key == "leadDeveloper.lastName")
{
foreach (var highlight in highlightField.Value)
{
highlight.Should().Contain("<name>");
highlight.Should().Contain("</name>");
}
}
else
Assert.True(false, $"highlights contains unexpected key {highlightField.Key}");
}
}
}
}
}
| 25.95053 | 144 | 0.558143 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/Search/Request/HighlightingUsageTests.cs | 7,344 | C# |
using System;
using System.Collections.Generic;
using Construct.Admin.Controllers;
using Construct.Admin.Data.Response;
using Construct.Admin.State;
using Construct.Base.Test.Functional.Base;
using Construct.Core.Data.Response;
using Construct.Core.Database.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NUnit.Framework;
namespace Construct.Admin.Test.Functional.Controllers
{
public class AdminSessionControllerTest : BaseSqliteTest
{
/// <summary>
/// Controller under test.
/// </summary>
private AdminSessionController _adminSessionController;
/// <summary>
/// Sets up the controller.
/// </summary>
[SetUp]
public void SetUpController()
{
// Create the controller.
this._adminSessionController = new AdminSessionController()
{
ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext()
}
};
// Add the test users.
this.AddData((context) =>
{
context.Users.Add(new Core.Database.Model.User()
{
HashedId = "test_hash_1",
Name = "Test Name 1",
Email = "test1@email",
SignUpTime = DateTime.Now,
});
context.Users.Add(new Core.Database.Model.User()
{
HashedId = "test_hash_2",
Name = "Test Name 2",
Email = "test2@email",
SignUpTime = DateTime.Now,
Permissions = new List<Permission>()
{
new Permission()
{
Name = "NotLabManager",
},
},
});
context.Users.Add(new Core.Database.Model.User()
{
HashedId = "test_hash_3",
Name = "Test Name 3",
Email = "test3@email",
SignUpTime = DateTime.Now,
Permissions = new List<Permission>()
{
new Permission()
{
Name = "LabManager",
},
},
});
});
}
/// <summary>
/// Tests the GetAuthenticate with no hashed id.
/// </summary>
[Test]
public void TestGetAuthenticateNoHashedId()
{
var response = this._adminSessionController.GetAuthenticate(null).Result.Value;
Assert.AreEqual(400, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is GenericStatusResponse);
Assert.AreEqual("missing-hashed-id", response.Status);
}
/// <summary>
/// Tests the GetAuthenticate with no user.
/// </summary>
[Test]
public void TestGetAuthenticateNoUser()
{
var response = this._adminSessionController.GetAuthenticate("unknown_user").Result.Value;
Assert.AreEqual(401, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is UnauthorizedResponse);
}
/// <summary>
/// Tests the GetAuthenticate with a user with no permissions.
/// </summary>
[Test]
public void TestGetAuthenticateNoPermissions()
{
var response = this._adminSessionController.GetAuthenticate("test_hash_1").Result.Value;
Assert.AreEqual(401, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is UnauthorizedResponse);
}
/// <summary>
/// Tests the GetAuthenticate with no lab manager permissions.
/// </summary>
[Test]
public void TestGetAuthenticateNotLabManager()
{
var response = this._adminSessionController.GetAuthenticate("test_hash_2").Result.Value;
Assert.AreEqual(401, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is UnauthorizedResponse);
}
/// <summary>
/// Tests the GetAuthenticate with a lab manager.
/// </summary>
[Test]
public void TestGetAuthenticateLabManager()
{
var response = (SessionResponse) this._adminSessionController.GetAuthenticate("test_hash_3").Result.Value;
Assert.AreEqual(200, this._adminSessionController.Response.StatusCode);
var nextResponse = (SessionResponse) this._adminSessionController.GetAuthenticate("test_hash_3").Result.Value;
Assert.AreNotEqual(response.Session, nextResponse.Session);
}
/// <summary>
/// Tests the GetCheckSession with no session.
/// </summary>
[Test]
public void TestGetCheckSessionNoSession()
{
var response = this._adminSessionController.GetCheckSession(null).Value;
Assert.AreEqual(400, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is GenericStatusResponse);
Assert.AreEqual("missing-session", response.Status);
}
/// <summary>
/// Tests the GetCheckSession with an invalid session.
/// </summary>
[Test]
public void TestGetCheckSessionInvalidSession()
{
var response = this._adminSessionController.GetCheckSession("unknown_session").Value;
Assert.AreEqual(401, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is UnauthorizedResponse);
}
/// <summary>
/// Tests the GetCheckSession with a invalid session.
/// </summary>
[Test]
public void TestGetCheckSessionValidSession()
{
var session = Session.GetSingleton().CreateSession("test_hash_3");
var response = this._adminSessionController.GetCheckSession(session).Value;
Assert.AreEqual(200, this._adminSessionController.Response.StatusCode);
Assert.IsTrue(response is BaseSuccessResponse);
}
}
} | 37.588235 | 122 | 0.563224 | [
"MIT"
] | ChrisFigura/Makerspace-Database-Server | Construct.Admin.Test/Functional/Controllers/AdminSessionControllerTest.cs | 6,390 | C# |
using System;
namespace UniMob.UI
{
public abstract class View<TState> : ViewBase<TState>
where TState : IViewState
{
protected sealed override void DidStateAttached(TState state)
{
try
{
using (Atom.NoWatch)
{
state.DidViewMount(this);
}
}
catch (Exception ex)
{
Zone.Current.HandleUncaughtException(ex);
}
}
protected sealed override void DidStateDetached(TState state)
{
try
{
using (Atom.NoWatch)
{
state.DidViewUnmount(this);
}
}
catch (Exception ex)
{
Zone.Current.HandleUncaughtException(ex);
}
}
}
} | 23.394737 | 69 | 0.434196 | [
"MIT"
] | adrenak/UniMob.UI | Runtime/View.cs | 889 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.Lex.Outputs
{
/// <summary>
/// Defines the Amazon CloudWatch Logs destination log group for conversation text logs.
/// </summary>
[OutputType]
public sealed class BotTextLogDestination
{
public readonly Outputs.BotCloudWatchLogGroupLogDestination CloudWatch;
[OutputConstructor]
private BotTextLogDestination(Outputs.BotCloudWatchLogGroupLogDestination cloudWatch)
{
CloudWatch = cloudWatch;
}
}
}
| 28.857143 | 93 | 0.712871 | [
"Apache-2.0"
] | pulumi/pulumi-aws-native | sdk/dotnet/Lex/Outputs/BotTextLogDestination.cs | 808 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AccountingNote7308.UserControl
{
public partial class ucPager : System.Web.UI.UserControl
{
public int PageSize { get; set; }
public int TotalSize { get; set; }
public int cPage { get; set; }
public string Url { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//Bind();
}
private int GetcurrentPage()
{
string txtpage = Request.QueryString["Page"];
if (string.IsNullOrWhiteSpace(txtpage))
return 1;
int PagerIndex;
if (!int.TryParse(txtpage, out PagerIndex))
return 1;
return PagerIndex;
}
public void Bind()
{
if (this.PageSize <= 0)
throw new DivideByZeroException();
int totalpage = this.TotalSize / this.PageSize;
if (this.TotalSize % this.PageSize > 0)
totalpage += 1;
this.aFirst.HRef = $"{this.Url}?page=1";
this.aLast.HRef = $"{this.Url}?page={totalpage}";
this.cPage = this.GetcurrentPage();
if (cPage == 1)
{
this.a1.Visible = false;
this.a2.Visible = false;
this.a3.HRef = "";
}
else if (cPage == totalpage)
{
this.a4.Visible = false;
this.a5.Visible = false;
this.a3.HRef = "";
}
else if (cPage == 2)
{
this.a1.Visible = false;
}
else if (cPage == (totalpage - 1))
{
this.a4.Visible = false;
}
int prevM1 = this.cPage - 1;
int prevM2 = this.cPage - 2;
this.a2.HRef = $"{this.Url}?page={prevM1}";
this.a2.InnerText = prevM1.ToString();
this.a1.HRef = $"{this.Url}?page={prevM2}";
this.a1.InnerText = prevM2.ToString();
int nextP1 = this.cPage + 1;
int nextP2 = this.cPage + 2;
this.a4.HRef = $"{this.Url}?page={nextP1}";
this.a4.InnerText = nextP1.ToString();
this.a5.HRef = $"{this.Url}?page={nextP2}";
this.a5.InnerText = nextP2.ToString();
this.a3.InnerText = this.cPage.ToString();
if (prevM2 <= 0)
this.a1.Visible = false;
if (prevM1 <= 0)
this.a2.Visible = false;
if (nextP1 > totalpage)
this.a4.Visible = false;
if (nextP2 > totalpage)
this.a5.Visible = false;
this.Pager_ltl.Text = $"共{this.TotalSize}筆, 共{totalpage}頁。" +
$"目前在第{this.GetcurrentPage()}頁。<br/>";
}
}
}
| 29.514851 | 73 | 0.480711 | [
"MIT"
] | thousandtw/AccountingNote | AccountingNote/AccountingNote7308/UserControl/ucPager_UserList.ascx.cs | 3,005 | C# |
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2021. *
* *
* Use subject to the terms of the Apache License 2.0 available at *
* http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Leap.Unity.Interaction
{
public interface IInternalInteractionController
{
void FixedUpdateController();
bool CheckHoverEnd(out HashSet<IInteractionBehaviour> hoverEndedObjects);
bool CheckHoverBegin(out HashSet<IInteractionBehaviour> hoverBeganObjects);
bool CheckHoverStay(out HashSet<IInteractionBehaviour> hoveredObjects);
bool CheckPrimaryHoverEnd(out IInteractionBehaviour primaryHoverEndedObject);
bool CheckPrimaryHoverBegin(out IInteractionBehaviour primaryHoverBeganObject);
bool CheckPrimaryHoverStay(out IInteractionBehaviour primaryHoveredObject);
bool CheckContactEnd(out HashSet<IInteractionBehaviour> contactEndedObjects);
bool CheckContactBegin(out HashSet<IInteractionBehaviour> contactBeganObjects);
bool CheckContactStay(out HashSet<IInteractionBehaviour> contactedObjects);
bool CheckGraspEnd(out IInteractionBehaviour releasedObject);
bool CheckGraspBegin(out IInteractionBehaviour newlyGraspedObject);
bool CheckGraspHold(out IInteractionBehaviour graspedObject);
bool CheckSuspensionBegin(out IInteractionBehaviour suspendedObject);
bool CheckSuspensionEnd(out IInteractionBehaviour resumedObject);
}
} | 45.690476 | 87 | 0.65555 | [
"MIT"
] | Gustav-Rixon/M7012E-DRv3 | Remote control/Assets/ThirdParty/Ultraleap/Tracking/Interaction Engine/Runtime/Scripts/Internal/Interface/IInternalInteractionController.cs | 1,919 | C# |
extern alias Their;
using System;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace Prometheus.Client.Benchmarks.Comparison.Summary
{
public class SummaryCollectingBenchmarks : ComparisonBenchmarkBase
{
private const int _metricsCount = 100;
private const int _labelsCount = 5;
private const int _variantsCount = 100;
private const int _observationsCount = 100;
public SummaryCollectingBenchmarks()
{
var labelNames = GenerateLabelNames(_labelsCount).ToArray();
var labelVariants = GenerateLabelValues(_variantsCount, _labelsCount);
var rnd = new Random();
foreach (var metric in GenerateMetricNames(_metricsCount, 0))
{
var ourMetric = OurMetricFactory.CreateSummary(metric, HelpText, labelNames);
var theirMetric = TheirMetricFactory.CreateSummary(metric, HelpText, labelNames);
foreach (var labels in labelVariants)
{
for (var i = 0; i < _observationsCount; i++)
{
var val = rnd.Next(10);
ourMetric.WithLabels(labels).Observe(val);
theirMetric.WithLabels(labels).Observe(val);
}
}
}
}
[Benchmark(Baseline = true)]
public void Collecting_Baseline()
{
using var stream = Stream.Null;
TheirCollectorRegistry.CollectAndExportAsTextAsync(stream).GetAwaiter().GetResult();
}
[Benchmark]
public void Collecting()
{
using var stream = Stream.Null;
ScrapeHandler.ProcessAsync(OurCollectorRegistry , stream).GetAwaiter().GetResult();
}
}
}
| 33.944444 | 97 | 0.592471 | [
"MIT"
] | PrometheusClientNet/Prometheus.Client | tests/Prometheus.Client.Benchmarks.Comparison/Summary/SummaryCollectingBenchmarks.cs | 1,833 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace NDG.Views
{
public partial class AboutPage : PhoneApplicationPage
{
public AboutPage()
{
InitializeComponent();
}
}
} | 22.782609 | 58 | 0.700382 | [
"BSD-3-Clause"
] | nokiadatagathering/WP7-Official | NDG/Views/AboutPage.xaml.cs | 526 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jobba.Core.Events;
using Jobba.Core.Interfaces;
using Jobba.Core.Interfaces.Repositories;
using Jobba.Core.Models;
using Microsoft.Extensions.Logging;
namespace Jobba.Core.Implementations
{
public class DefaultJobReScheduler : IJobReScheduler
{
private readonly IJobEventPublisher _jobEventPublisher;
private readonly IJobListStore _jobListStore;
private readonly ILogger<DefaultJobReScheduler> _logger;
public DefaultJobReScheduler(IJobListStore jobListStore,
IJobEventPublisher jobEventPublisher,
ILogger<DefaultJobReScheduler> logger)
{
_jobListStore = jobListStore;
_jobEventPublisher = jobEventPublisher;
_logger = logger;
}
public async Task RestartFaultedJobsAsync(CancellationToken cancellationToken)
{
var jobs = await _jobListStore.GetJobsToRetry(cancellationToken);
var jobsArray = jobs ?? new JobInfoBase[0];
var tasks = jobsArray
.Select(job =>
{
_logger.LogDebug("Restarting job. JobId: {JobId} Description: {JobDescription}", job.Id, job.Description);
return _jobEventPublisher
.PublishJobRestartEvent(
new JobRestartEvent { JobId = job.Id, JobParamsTypeName = job.JobParamsTypeName, JobStateTypeName = job.JobStateTypeName },
cancellationToken);
})
.ToArray();
await Task.WhenAll(tasks);
}
}
}
| 34.8125 | 151 | 0.637343 | [
"MIT"
] | firebend/jobba | Jobba.Core/Implementations/DefaultJobReScheduler.cs | 1,671 | C# |
namespace ERHMS.Console.Utilities
{
public interface IUtility
{
void Run();
}
}
| 13.5 | 35 | 0.555556 | [
"Apache-2.0"
] | CDCgov/erhms-info-manager | ERHMS.Console/Utilities/IUtility.cs | 110 | 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.
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.Linq;
namespace IdentityServer4.Services
{
class DefaultIdentityServerInteractionService : IIdentityServerInteractionService
{
private readonly IdentityServerOptions _options;
private readonly IHttpContextAccessor _context;
private readonly IMessageStore<LogoutMessage> _logoutMessageStore;
private readonly IMessageStore<ErrorMessage> _errorMessageStore;
private readonly IConsentMessageStore _consentMessageStore;
private readonly IPersistedGrantService _grants;
private readonly IUserSession _userSession;
private readonly ILogger _logger;
private readonly ReturnUrlParser _returnUrlParser;
public DefaultIdentityServerInteractionService(
IdentityServerOptions options,
IHttpContextAccessor context,
IMessageStore<LogoutMessage> logoutMessageStore,
IMessageStore<ErrorMessage> errorMessageStore,
IConsentMessageStore consentMessageStore,
IPersistedGrantService grants,
IUserSession userSession,
ReturnUrlParser returnUrlParser,
ILogger<DefaultIdentityServerInteractionService> logger)
{
_options = options;
_context = context;
_logoutMessageStore = logoutMessageStore;
_errorMessageStore = errorMessageStore;
_consentMessageStore = consentMessageStore;
_grants = grants;
_userSession = userSession;
_returnUrlParser = returnUrlParser;
_logger = logger;
}
public async Task<AuthorizationRequest> GetAuthorizationContextAsync(string returnUrl)
{
var result = await _returnUrlParser.ParseAsync(returnUrl);
if (result != null)
{
_logger.LogTrace("AuthorizationRequest being returned");
}
else
{
_logger.LogTrace("No AuthorizationRequest being returned");
}
return result;
}
public async Task<LogoutRequest> GetLogoutContextAsync(string logoutId)
{
var msg = await _logoutMessageStore.ReadAsync(logoutId);
var iframeUrl = await _context.HttpContext.GetIdentityServerSignoutFrameCallbackUrlAsync(msg?.Data);
return new LogoutRequest(iframeUrl, msg?.Data);
}
public async Task<string> CreateLogoutContextAsync()
{
var user = await _userSession.GetIdentityServerUserAsync();
if (user != null)
{
var clientIds = await _userSession.GetClientListAsync();
if (clientIds.Any())
{
var sid = await _userSession.GetCurrentSessionIdAsync();
var msg = new Message<LogoutMessage>(new LogoutMessage
{
SubjectId = user?.GetSubjectId(),
SessionId = sid,
ClientIds = clientIds
}, _options.UtcNow);
var id = await _logoutMessageStore.WriteAsync(msg);
return id;
}
}
return null;
}
public async Task<ErrorMessage> GetErrorContextAsync(string errorId)
{
if (errorId != null)
{
var result = await _errorMessageStore.ReadAsync(errorId);
var data = result?.Data;
if (data != null)
{
_logger.LogTrace("Error context loaded");
}
else
{
_logger.LogTrace("No error context found");
}
return data;
}
_logger.LogTrace("No error context found");
return null;
}
public async Task GrantConsentAsync(AuthorizationRequest request, ConsentResponse consent, string subject = null)
{
if (subject == null)
{
var user = await _userSession.GetIdentityServerUserAsync();
subject = user?.GetSubjectId();
}
if (subject == null) throw new ArgumentNullException(nameof(subject), "User is not currently authenticated, and no subject id passed");
var consentRequest = new ConsentRequest(request, subject);
await _consentMessageStore.WriteAsync(consentRequest.Id, new Message<ConsentResponse>(consent, _options.UtcNow));
}
public bool IsValidReturnUrl(string returnUrl)
{
var result = _returnUrlParser.IsValidReturnUrl(returnUrl);
if (result)
{
_logger.LogTrace("IsValidReturnUrl true");
}
else
{
_logger.LogTrace("IsValidReturnUrl false");
}
return result;
}
public async Task<IEnumerable<Consent>> GetAllUserConsentsAsync()
{
var user = await _userSession.GetIdentityServerUserAsync();
if (user != null)
{
var subject = user.GetSubjectId();
return await _grants.GetAllGrantsAsync(subject);
}
return Enumerable.Empty<Consent>();
}
public async Task RevokeUserConsentAsync(string clientId)
{
var user = await _userSession.GetIdentityServerUserAsync();
if (user != null)
{
var subject = user.GetSubjectId();
await _grants.RemoveAllGrantsAsync(subject, clientId);
}
}
public async Task RevokeTokensForCurrentSessionAsync()
{
var user = await _userSession.GetIdentityServerUserAsync();
if (user != null)
{
var subject = user.GetSubjectId();
var clients = await _userSession.GetClientListAsync();
foreach (var client in clients)
{
await _grants.RemoveAllGrantsAsync(subject, client);
}
}
}
}
}
| 35.545455 | 147 | 0.588386 | [
"Apache-2.0"
] | gcbenjamin/IdentityServer4 | src/IdentityServer4/Services/DefaultIdentityServerInteractionService.cs | 6,649 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Courier.Hosts
{
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Contracts;
using GreenPipes;
using Logging;
using Util;
public class CompensateActivityHost<TActivity, TLog> :
IFilter<ConsumeContext<RoutingSlip>>
where TActivity : class, CompensateActivity<TLog>
where TLog : class
{
static readonly ILog _log = Logger.Get<CompensateActivityHost<TActivity, TLog>>();
readonly CompensateActivityFactory<TActivity, TLog> _activityFactory;
readonly IRequestPipe<CompensateActivityContext<TActivity, TLog>, CompensationResult> _compensatePipe;
public CompensateActivityHost(CompensateActivityFactory<TActivity, TLog> activityFactory,
IPipe<RequestContext> compensatePipe)
{
_activityFactory = activityFactory;
_compensatePipe = compensatePipe.CreateRequestPipe<CompensateActivityContext<TActivity, TLog>, CompensationResult>();
}
public async Task Send(ConsumeContext<RoutingSlip> context, IPipe<ConsumeContext<RoutingSlip>> next)
{
var timer = Stopwatch.StartNew();
try
{
CompensateContext<TLog> compensateContext = new HostCompensateContext<TLog>(HostMetadataCache.Host, context);
if (_log.IsDebugEnabled)
{
_log.DebugFormat("Host: {0} Activity: {1} Compensating: {2}", context.ReceiveContext.InputAddress, TypeMetadataCache<TActivity>.ShortName,
compensateContext.TrackingNumber);
}
await Task.Yield();
try
{
var result = await _activityFactory.Compensate(compensateContext, _compensatePipe).Result().ConfigureAwait(false);
await result.Evaluate().ConfigureAwait(false);
}
catch (Exception ex)
{
var result = compensateContext.Failed(ex);
await result.Evaluate().ConfigureAwait(false);
}
await context.NotifyConsumed(timer.Elapsed, TypeMetadataCache<TActivity>.ShortName).ConfigureAwait(false);
await next.Send(context).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Error($"The activity {TypeMetadataCache<TActivity>.ShortName} threw an exception", ex);
await context.NotifyFaulted(timer.Elapsed, TypeMetadataCache<TActivity>.ShortName, ex).ConfigureAwait(false);
throw;
}
}
public void Probe(ProbeContext context)
{
var scope = context.CreateFilterScope("compensateActivity");
scope.Set(new
{
ActivityType = TypeMetadataCache<TActivity>.ShortName,
LogType = TypeMetadataCache<TLog>.ShortName
});
_compensatePipe.Probe(scope);
}
}
} | 40.276596 | 159 | 0.618331 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit/Courier/Hosts/CompensateActivityHost.cs | 3,786 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace mediver_server.Areas.Identity.Pages.Account.Manage
{
public static class ManageNavPages
{
public static string Index => "Index";
public static string Email => "Email";
public static string ChangePassword => "ChangePassword";
public static string DownloadPersonalData => "DownloadPersonalData";
public static string DeletePersonalData => "DeletePersonalData";
public static string ExternalLogins => "ExternalLogins";
public static string PersonalData => "PersonalData";
public static string TwoFactorAuthentication => "TwoFactorAuthentication";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email);
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
public static string DownloadPersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DownloadPersonalData);
public static string DeletePersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DeletePersonalData);
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData);
public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication);
private static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string
?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName);
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
}
}
| 42.333333 | 140 | 0.751274 | [
"MIT"
] | mediver-app/mediver | mediver-server/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs | 2,161 | C# |
using System.Web;
using System.Web.Optimization;
namespace Rn.Mailer
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 39.172414 | 113 | 0.5625 | [
"Apache-2.0"
] | rncode/Rn.Mailer | src/Rn.Mailer/App_Start/BundleConfig.cs | 1,138 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using DDay.iCal.Validator.Xml;
namespace DDay.iCal.Validator.Serialization
{
public class XmlValidationSerializer :
IValidationSerializer
{
#region Constructors
public XmlValidationSerializer(
IXmlDocumentProvider docProvider)
{
XmlDocProvider = docProvider;
}
public XmlValidationSerializer(
IXmlDocumentProvider docProvider,
IValidationRuleset ruleset,
ITestResult[] testResults) :
this(docProvider)
{
Ruleset = ruleset;
TestResults = testResults;
}
public XmlValidationSerializer(
IXmlDocumentProvider docProvider,
IValidationRuleset ruleset,
IValidationResult[] validationResults) :
this(docProvider)
{
Ruleset = ruleset;
ValidationResults = validationResults;
}
#endregion
#region IValidationSerializer Members
public string DefaultExtension
{
get { return "xml"; }
}
public Encoding DefaultEncoding
{
get { return Encoding.UTF8; }
}
virtual public IXmlDocumentProvider XmlDocProvider { get; set; }
virtual public IValidationRuleset Ruleset { get; set; }
virtual public ITestResult[] TestResults { get; set; }
virtual public IValidationResult[] ValidationResults { get; set; }
virtual public void Serialize(Stream stream, Encoding encoding)
{
XmlWriter xw = null;
try
{
if (XmlDocProvider != null)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.CloseOutput = false;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Encoding = encoding;
settings.Indent = true;
settings.IndentChars = " ";
settings.NewLineChars = "\r\n";
settings.NewLineOnAttributes = true;
xw = XmlWriter.Create(stream, settings);
XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("i", "http://icalvalid.wikidot.com/validation");
// FIXME: add a schema!
// doc.Schemas.Add("http://icalvalid.wikidot.com/validation", "schema.xsd");
DateTime now = DateTime.Now;
XmlElement results = doc.CreateElement("results", "http://icalvalid.wikidot.com/validation");
results.SetAttribute("language", ResourceManager.CurrentLanguageIdentifier);
results.SetAttribute("datetime", now.ToString("yyyy-MM-dd") + "T" + now.ToString("hh:mm:ss"));
if (TestResults != null &&
TestResults.Length > 0)
{
XmlElement testResults = doc.CreateElement("testResults", "http://icalvalid.wikidot.com/validation");
testResults.SetAttribute("ruleset", Ruleset.Name);
foreach (ITestResult result in TestResults)
{
XmlElement testResult = doc.CreateElement("testResult", "http://icalvalid.wikidot.com/validation");
testResult.SetAttribute("rule", result.Rule);
testResult.SetAttribute("expected", result.Test.Type == TestType.Pass ? "pass" : "fail");
if (result.Passed != null && result.Passed.HasValue)
{
string pass = (result.Test.Type == TestType.Pass ? "pass" : "fail");
string fail = (result.Test.Type == TestType.Pass ? "fail" : "pass");
testResult.SetAttribute("actual", BoolUtil.IsTrue(result.Passed) ? pass : fail);
}
else
{
testResult.SetAttribute("actual", "none");
}
if (!string.IsNullOrEmpty(result.Test.ExpectedError))
testResult.SetAttribute("errorName", result.Test.ExpectedError);
if (result.Error != null)
testResult.SetAttribute("error", result.Error.ToString());
testResults.AppendChild(testResult);
}
results.AppendChild(testResults);
}
if (ValidationResults != null &&
ValidationResults.Length > 0)
{
XmlElement validationResults = doc.CreateElement("validationResults", "http://icalvalid.wikidot.com/validation");
validationResults.SetAttribute("ruleset", Ruleset.Name);
foreach (IValidationResult result in ValidationResults)
{
XmlElement validationResult = doc.CreateElement("validationResult", "http://icalvalid.wikidot.com/validation");
validationResult.SetAttribute("rule", result.Rule);
if (result.Passed != null && result.Passed.HasValue)
validationResult.SetAttribute("result", result.Passed.Value ? "pass" : "fail");
else
validationResult.SetAttribute("result", "none");
if (result.Errors != null &&
result.Errors.Length > 0)
{
XmlElement validationErrors = doc.CreateElement("errors", "http://icalvalid.wikidot.com/validation");
foreach (IValidationError error in result.Errors)
{
XmlElement validationError = doc.CreateElement("error", "http://icalvalid.wikidot.com/validation");
validationError.SetAttribute("name", error.Name);
validationError.SetAttribute("type", error.Type.ToString().ToLower());
validationError.SetAttribute("message", error.Message);
validationError.SetAttribute("isFatal", error.IsFatal.ToString().ToLower());
if (error.Line != default(int))
validationError.SetAttribute("line", error.Line.ToString());
if (error.Col != default(int))
validationError.SetAttribute("col", error.Col.ToString());
validationErrors.AppendChild(validationError);
}
validationResult.AppendChild(validationErrors);
}
validationResults.AppendChild(validationResult);
}
results.AppendChild(validationResults);
}
doc.AppendChild(results);
doc.Save(xw);
}
}
finally
{
if (xw != null)
{
xw.Close();
xw = null;
}
}
}
#endregion
}
}
| 43.951613 | 140 | 0.478165 | [
"BSD-3-Clause"
] | 3rdandUrban-dev/Nuxleus | linux-distro/package/nuxleus/Source/Vendor/dday-ical/DDay.iCal.Validator/DDay.iCal.Validator/Serialization/XmlValidationSerializer.cs | 8,177 | C# |
using System;
using System.Collections.Generic;
using System.Net; // for EndPoint
using System.Net.Sockets; // for Socket
using System.Text;
using System.Threading; // for Interlocked
namespace ServerCore
{
// 패킷 형태
public abstract class PacketSession : Session
{
// 헤더는 2바이트라고 가정하자.
public static readonly int HeaderSize = 2;
// [size(2)][packeId(2)][...] [size(2)][packeId(2)][...] // sealed : 다른 클래스가 상속했을때 overide 차단
public sealed override int OnRecv(ArraySegment<byte> buffer) // 패킷 받기 (from Client)
{
int processLen = 0; // 현재 처리한 바이트 수.
// 주어진 패킷을 처리할 수 있을때까지 무한 반복
while (true)
{
// 최소한 헤더를 파싱할 수 있는지 (2바이트보다 작으면)
if (buffer.Count < HeaderSize)
break;
// 패킷이 완전체로 왔는지 확인 (헤더 패킷을 까봐야 알수있음. 내용을 봐야암)
ushort dataSize = BitConverter.ToUInt16(buffer.Array, buffer.Offset); //ushort 크기 뱉음
// 패킷이 완전체가 아니라 부분적으로 왔을떄
if (buffer.Count < dataSize)
break;
// 여기까지 왔으면 패킷 조립 가능
OnRecvPacket(new ArraySegment<byte>(buffer.Array, buffer.Offset, dataSize));
processLen += dataSize;
// 버퍼를 옮겨줘야함.
buffer = new ArraySegment<byte>(buffer.Array, buffer.Offset + dataSize, buffer.Count - dataSize);
}
return processLen;
}
// PacketSession을 상속받는 애들은 OnRecv 인터페이스가 아니라 OnRecvPacket이라는 인터페이스로 받아라.
public abstract void OnRecvPacket(ArraySegment<byte> buffer);
}
public abstract class Session
{
// Member variable
Socket _socket; // Session Socket (대리인)
int _disconnected = 0; // flag for Interlocked
Queue<ArraySegment<byte>> _sendQueue = new Queue<ArraySegment<byte>>(); // for send
object _lock = new object(); // for lock
SocketAsyncEventArgs _recvArgs = new SocketAsyncEventArgs();
SocketAsyncEventArgs _sendArgs = new SocketAsyncEventArgs(); // 재사용
List<ArraySegment<byte>> _pendingList = new List<ArraySegment<byte>>(); // for bufferList
RecvBuffer _recvBuffer = new RecvBuffer(1024); // 1024 / 4096
// interface
public abstract void OnConnected(EndPoint endpoint); // 클라가 접속
public abstract int OnRecv(ArraySegment<byte> buffer); // 패킷 받기 (from Client)
public abstract void OnSend(int numOfBytes); // 패킷 보내기 (to Client)
public abstract void OnDisconnected(EndPoint endPoint);
//
// Initialize
public void Start(Socket socket)
{
_socket = socket; // socket 연결
_recvArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnRecvCompleted);
_sendArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendCompleted);
RegisterRecv(); // 최초 실행
}
// if you want to Send, Call Send Function
public void Send(ArraySegment<byte> sendBuff)
{
lock (_lock)
{
// Critical Section
_sendQueue.Enqueue(sendBuff);
if (_pendingList.Count == 0)
RegisterSend();
}
}
public void Disconnect()
{
if (Interlocked.Exchange(ref _disconnected, 1) == 1)
return;
OnDisconnected(_socket.RemoteEndPoint);
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
}
#region 네트워크 통신
//////// SendAsync
void RegisterSend()
{
while (_sendQueue.Count > 0)
{
ArraySegment<byte> buff = _sendQueue.Dequeue(); // 버퍼 꺼내기
_pendingList.Add(buff);
}
_sendArgs.BufferList = _pendingList; // BufferList 사용
bool pending = _socket.SendAsync(_sendArgs); // BufferList의 경우 보낼떄 한꺼번에 전달된다.
if (pending == false)
OnSendCompleted(null, _sendArgs);
}
void OnSendCompleted(object sender, SocketAsyncEventArgs args)
{
// Critical section (cuz _pending)
lock (_lock)
{
if (args.BytesTransferred > 0 && args.SocketError == SocketError.Success)
{
try
{
_sendArgs.BufferList = null; // 버퍼 초기화
_pendingList.Clear(); // 버퍼리스트를 위한 초기화
OnSend(_sendArgs.BytesTransferred);
if (_sendQueue.Count > 0) // 큐가 빌때까지
RegisterSend(); // 비동기 실행 (낚싯대 던지기)
}
catch (Exception e)
{
Console.WriteLine($"OnSendCompleted is Failed {e}");
}
}
else
{
Disconnect();
}
}
}
//////// ReceiveAsync
void RegisterRecv()
{
_recvBuffer.Clean();
ArraySegment<byte> segment = _recvBuffer.WriteSegment;
_recvArgs.SetBuffer(segment.Array, segment.Offset, segment.Count);
bool pending = _socket.ReceiveAsync(_recvArgs); // Async Receive 실행
if (pending == false)
OnRecvCompleted(null, _recvArgs);
}
void OnRecvCompleted(object sender, SocketAsyncEventArgs args)
{
if (args.BytesTransferred > 0 && args.SocketError == SocketError.Success)
{
try
{
// Write 커서 이동.
if (_recvBuffer.OnWrite(args.BytesTransferred) == false)
{
Disconnect();
return;
}
// 컨텐츠쪽에서 데이터를 넘겨주고 얼마나 처리했는지 받는다.
int processLen = OnRecv(_recvBuffer.ReadSegment);
if (processLen < 0 || _recvBuffer.DataSize < processLen)
{
Disconnect();
return;
}
// Read 커서 이동.
if (_recvBuffer.OnRead(processLen) == false)
{
Disconnect();
return;
}
RegisterRecv(); // 다시 낚싯대를 던짐
}
catch (Exception e)
{
Console.WriteLine($"OnRecvCompleted Faild {e}");
}
}
else
{
Disconnect();
}
}
#endregion
}
}
| 32.533654 | 113 | 0.497709 | [
"MIT"
] | 610ksh/CSharpGameServer | Server(error)/ServerCore/Session.cs | 7,395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Basket.Api.Entities
{
public class ShoppingCart
{
public string UserName { get; set; }
public List<ShoppingCartItem> Items { get; set; } = new List<ShoppingCartItem>();
public ShoppingCart()
{
}
public ShoppingCart(string userName)
{
UserName = userName;
}
public decimal TotalPrice
{
get
{
decimal totalprice = 0;
foreach (var item in Items)
{
totalprice += item.Price * item.Quantity;
}
return totalprice;
}
}
}
}
| 21.555556 | 89 | 0.506443 | [
"MIT"
] | zargostar/microservices | Src/Services/Basket/Basket.Api/Entities/ShoppingCart.cs | 778 | 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 sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// This is the response object from the ListNotebookInstances operation.
/// </summary>
public partial class ListNotebookInstancesResponse : AmazonWebServiceResponse
{
private string _nextToken;
private List<NotebookInstanceSummary> _notebookInstances = new List<NotebookInstanceSummary>();
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// If the response to the previous <code>ListNotebookInstances</code> request was truncated,
/// Amazon SageMaker returns this token. To retrieve the next set of notebook instances,
/// use the token in the next request.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property NotebookInstances.
/// <para>
/// An array of <code>NotebookInstanceSummary</code> objects, one for each notebook instance.
/// </para>
/// </summary>
public List<NotebookInstanceSummary> NotebookInstances
{
get { return this._notebookInstances; }
set { this._notebookInstances = value; }
}
// Check to see if NotebookInstances property is set
internal bool IsSetNotebookInstances()
{
return this._notebookInstances != null && this._notebookInstances.Count > 0;
}
}
} | 33.675325 | 107 | 0.650212 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/ListNotebookInstancesResponse.cs | 2,593 | C# |
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace JudgeSystem.Web.Infrastructure.Extensions
{
public static class FormFileExtensions
{
public static async Task<byte[]> ToArrayAsync(this IFormFile file)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
}
}
| 23.8 | 74 | 0.617647 | [
"MIT"
] | NaskoVasilev/JudgeSystem | Web/JudgeSystem.Web.Infrastructure/Extensions/FormFileExtensions.cs | 478 | C# |
using UnityEngine;
using System.Collections;
public class DestroyOnHit : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other){
Destroy (other.gameObject);
}
}
| 16.9 | 43 | 0.775148 | [
"Apache-2.0"
] | Cremate91/BunnyRunTut | Assets/Scriptes/DestroyOnHit.cs | 171 | C# |
using JetBrains.Annotations;
namespace OpenMLTD.MilliSim.Extension.Components.CoreComponents {
/// <summary>
/// Synchronization method of <see cref="SyncTimer"/>.
/// </summary>
public enum TimerSyncMethod {
/// <summary>
/// Uses the naive method. Synchronized time is directly read from time source.
/// </summary>
Naive = 0,
/// <summary>
/// Uses the estimated method. Estimates and calibrates the time by using both the time source and an internal <see cref="System.Diagnostics.Stopwatch"/>.
/// </summary>
[UsedImplicitly]
Estimated = 1
}
}
| 30.619048 | 162 | 0.625194 | [
"MIT"
] | hozuki/MilliSim | src/plugins/OpenMLTD.MilliSim.Extension.Components.CoreComponents/TimerSyncMethod.cs | 643 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LeetCode.Test
{
[TestClass]
public class _0829_ConsecutiveNumbersSum_Test
{
[TestMethod]
public void ConsecutiveNumbersSum_1()
{
var solution = new _0829_ConsecutiveNumbersSum();
var result = solution.ConsecutiveNumbersSum(5);
Assert.AreEqual(2, result);
}
[TestMethod]
public void ConsecutiveNumbersSum_2()
{
var solution = new _0829_ConsecutiveNumbersSum();
var result = solution.ConsecutiveNumbersSum(9);
Assert.AreEqual(3, result);
}
[TestMethod]
public void ConsecutiveNumbersSum_3()
{
var solution = new _0829_ConsecutiveNumbersSum();
var result = solution.ConsecutiveNumbersSum(15);
Assert.AreEqual(4, result);
}
}
}
| 27.545455 | 61 | 0.607261 | [
"MIT"
] | BigEggStudy/LeetCode-CS | LeetCode.Test/0801-0850/0829-ConsecutiveNumbersSum-Test.cs | 909 | C# |
using DragonSpark.Compose;
using DragonSpark.Model.Results;
using System;
using System.Linq.Expressions;
namespace DragonSpark.Runtime.Invocation.Expressions;
sealed class Parameter<T> : FixedSelectedSingleton<string, ParameterExpression>
{
public static Parameter<T> Default { get; } = new Parameter<T>();
public Parameter(string name = "parameter") : base(Parameters<T>.Default, name) {}
}
sealed class Parameter : Invocation1<Type, string, ParameterExpression>
{
public static Parameter Default { get; } = new Parameter();
Parameter() : this(A.Type<object[]>()) {}
public Parameter(Type parameter) : base(Expression.Parameter, parameter) {}
} | 29.863636 | 83 | 0.754947 | [
"MIT"
] | DragonSpark/Framework | DragonSpark/Runtime/Invocation/Expressions/Parameter.cs | 659 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Iot.Device.GrovePiDevice.Models
{
/// <summary>
/// The supported Digital Grove Ports
/// See README.md files for the exact location of each Port
/// </summary>
public enum GrovePort
{
/// <summary>Analog pin 0 (A0)</summary>
AnalogPin0 = 0,
/// <summary>Analog pin (A1)</summary>
AnalogPin1 = 1,
/// <summary>Analog pin (A2)</summary>
AnalogPin2 = 2,
/// <summary>Digital pin 2</summary>
DigitalPin2 = 2,
/// <summary>Digital pin 3</summary>
DigitalPin3 = 3,
/// <summary>Digital pin 4</summary>
DigitalPin4 = 4,
/// <summary>Digital pin 5</summary>
DigitalPin5 = 5,
/// <summary>Digital pin 6</summary>
DigitalPin6 = 6,
/// <summary>Digital pin 7</summary>
DigitalPin7 = 7,
/// <summary>Digital pin 8</summary>
DigitalPin8 = 8,
/// <summary>Analog Pin A0 used as Digital Pin</summary>
DigitalPin14 = 14,
/// <summary>Analog Pin A1 used as Digital Pin</summary>
DigitalPin15 = 15,
/// <summary>This is Analog Pin A2 used as Digital Pin</summary>
DigitalPin16 = 16
}
}
| 34.634146 | 72 | 0.590845 | [
"MIT"
] | Anberm/iot | src/devices/GrovePi/Models/GrovePort.cs | 1,422 | 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.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipeWriterTests : PipeTest
{
public PipeWriterTests() : base(0, 0) { }
private byte[] Read()
{
Pipe.Writer.FlushAsync().GetAwaiter().GetResult();
ReadResult readResult = Pipe.Reader.ReadAsync().GetAwaiter().GetResult();
byte[] data = readResult.Buffer.ToArray();
Pipe.Reader.AdvanceTo(readResult.Buffer.End);
return data;
}
[Theory]
[InlineData(3, -1, 0)]
[InlineData(3, 0, -1)]
[InlineData(3, 0, 4)]
[InlineData(3, 4, 0)]
[InlineData(3, -1, -1)]
[InlineData(3, 4, 4)]
public void ThrowsForInvalidParameters(int arrayLength, int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[arrayLength];
for (var i = 0; i < array.Length; i++)
{
array[i] = (byte)(i + 1);
}
writer.Write(new Span<byte>(array, 0, 0));
writer.Write(new Span<byte>(array, array.Length, 0));
try
{
writer.Write(new Span<byte>(array, offset, length));
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
writer.Write(new Span<byte>(array, 0, array.Length));
Assert.Equal(array, Read());
}
[Theory]
[InlineData(0, 3)]
[InlineData(1, 1)]
[InlineData(1, 2)]
[InlineData(2, 1)]
public void CanWriteWithOffsetAndLength(int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[] { 1, 2, 3 };
writer.Write(new Span<byte>(array, offset, length));
Assert.Equal(array.Skip(offset).Take(length).ToArray(), Read());
}
[Fact]
public void CanWriteIntoHeadlessBuffer()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public void CanWriteMultipleTimes()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1 });
writer.Write(new byte[] { 2 });
writer.Write(new byte[] { 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public async Task CanWriteOverTheBlockLength()
{
Memory<byte> memory = Pipe.Writer.GetMemory();
PipeWriter writer = Pipe.Writer;
IEnumerable<byte> source = Enumerable.Range(0, memory.Length).Select(i => (byte)i);
byte[] expectedBytes = source.Concat(source).Concat(source).ToArray();
await writer.WriteAsync(expectedBytes);
Assert.Equal(expectedBytes, Read());
}
[Fact]
public void EnsureAllocatesSpan()
{
PipeWriter writer = Pipe.Writer;
var span = writer.GetSpan(10);
Assert.True(span.Length >= 10);
// 0 byte Flush would not complete the reader so we complete.
Pipe.Writer.Complete();
Assert.Equal(new byte[] { }, Read());
}
[Fact]
public void SlicesSpanAndAdvancesAfterWrite()
{
int initialLength = Pipe.Writer.GetSpan(3).Length;
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Span<byte> span = Pipe.Writer.GetSpan();
Assert.Equal(initialLength - 3, span.Length);
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataBinary(int length)
{
var data = new byte[length];
new Random(length).NextBytes(data);
PipeWriter output = Pipe.Writer;
await output.WriteAsync(data);
ReadResult result = await Pipe.Reader.ReadAsync();
ReadOnlySequence<byte> input = result.Buffer;
Assert.Equal(data, input.ToArray());
Pipe.Reader.AdvanceTo(input.End);
}
[Fact]
public async Task CanWriteNothingToBuffer()
{
PipeWriter buffer = Pipe.Writer;
buffer.GetMemory(0);
buffer.Advance(0); // doing nothing, the hard way
await buffer.FlushAsync();
}
[Fact]
public void EmptyWriteDoesNotThrow()
{
Pipe.Writer.Write(new byte[0]);
}
[Fact]
public void ThrowsOnAdvanceOverMemorySize()
{
Memory<byte> buffer = Pipe.Writer.GetMemory(1);
Assert.Throws<ArgumentOutOfRangeException>(
() => Pipe.Writer.Advance(buffer.Length + 1)
);
}
[Fact]
public void ThrowsOnAdvanceWithNoMemory()
{
PipeWriter buffer = Pipe.Writer;
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Advance(1));
}
[Fact]
public async Task WritesUsingGetSpanWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetSpan()[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
public async Task WritesUsingGetMemoryWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetMemory().Span[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "allocates too much memory")]
public async Task CompleteWithLargeWriteThrows()
{
var pipe = new Pipe();
pipe.Reader.Complete();
var task = Task.Run(
async () =>
{
await Task.Delay(10);
pipe.Writer.Complete();
}
);
try
{
for (int i = 0; i < 1000; i++)
{
var buffer = new byte[10000000];
await pipe.Writer.WriteAsync(buffer);
}
}
catch (InvalidOperationException)
{
// Complete while writing
}
await task;
}
[Fact]
public async Task WriteAsyncWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
byte[] writeBuffer = new byte[100];
for (var i = 0; i < 10000; i++)
{
await pipe.Writer.WriteAsync(writeBuffer);
}
Assert.Equal(0, pool.CurrentlyRentedBlocks);
}
[Fact]
public async Task GetMemoryFlushWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
for (var i = 0; i < 10000; i++)
{
var mem = pipe.Writer.GetMemory();
pipe.Writer.Advance(mem.Length);
await pipe.Writer.FlushAsync(default);
}
Assert.Equal(1, pool.CurrentlyRentedBlocks);
pipe.Writer.Complete();
Assert.Equal(0, pool.CurrentlyRentedBlocks);
}
}
}
| 30.412752 | 100 | 0.522013 | [
"MIT"
] | belav/runtime | src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs | 9,063 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.Outputs
{
[OutputType]
public sealed class AvailablePatchSummaryResponse
{
/// <summary>
/// The activity ID of the operation that produced this result. It is used to correlate across CRP and extension logs.
/// </summary>
public readonly string AssessmentActivityId;
/// <summary>
/// The number of critical or security patches that have been detected as available and not yet installed.
/// </summary>
public readonly int CriticalAndSecurityPatchCount;
/// <summary>
/// The errors that were encountered during execution of the operation. The details array contains the list of them.
/// </summary>
public readonly Outputs.ApiErrorResponse Error;
/// <summary>
/// The UTC timestamp when the operation began.
/// </summary>
public readonly string LastModifiedTime;
/// <summary>
/// The number of all available patches excluding critical and security.
/// </summary>
public readonly int OtherPatchCount;
/// <summary>
/// The overall reboot status of the VM. It will be true when partially installed patches require a reboot to complete installation but the reboot has not yet occurred.
/// </summary>
public readonly bool RebootPending;
/// <summary>
/// The UTC timestamp when the operation began.
/// </summary>
public readonly string StartTime;
/// <summary>
/// The overall success or failure status of the operation. It remains "InProgress" until the operation completes. At that point it will become "Unknown", "Failed", "Succeeded", or "CompletedWithWarnings."
/// </summary>
public readonly string Status;
[OutputConstructor]
private AvailablePatchSummaryResponse(
string assessmentActivityId,
int criticalAndSecurityPatchCount,
Outputs.ApiErrorResponse error,
string lastModifiedTime,
int otherPatchCount,
bool rebootPending,
string startTime,
string status)
{
AssessmentActivityId = assessmentActivityId;
CriticalAndSecurityPatchCount = criticalAndSecurityPatchCount;
Error = error;
LastModifiedTime = lastModifiedTime;
OtherPatchCount = otherPatchCount;
RebootPending = rebootPending;
StartTime = startTime;
Status = status;
}
}
}
| 37 | 213 | 0.644144 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Compute/Outputs/AvailablePatchSummaryResponse.cs | 2,886 | 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 ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECS.Model
{
/// <summary>
/// A Docker container that is part of a task.
/// </summary>
public partial class Container
{
private string _containerArn;
private int? _exitCode;
private HealthStatus _healthStatus;
private string _lastStatus;
private string _name;
private List<NetworkBinding> _networkBindings = new List<NetworkBinding>();
private List<NetworkInterface> _networkInterfaces = new List<NetworkInterface>();
private string _reason;
private string _taskArn;
/// <summary>
/// Gets and sets the property ContainerArn.
/// <para>
/// The Amazon Resource Name (ARN) of the container.
/// </para>
/// </summary>
public string ContainerArn
{
get { return this._containerArn; }
set { this._containerArn = value; }
}
// Check to see if ContainerArn property is set
internal bool IsSetContainerArn()
{
return this._containerArn != null;
}
/// <summary>
/// Gets and sets the property ExitCode.
/// <para>
/// The exit code returned from the container.
/// </para>
/// </summary>
public int ExitCode
{
get { return this._exitCode.GetValueOrDefault(); }
set { this._exitCode = value; }
}
// Check to see if ExitCode property is set
internal bool IsSetExitCode()
{
return this._exitCode.HasValue;
}
/// <summary>
/// Gets and sets the property HealthStatus.
/// <para>
/// The health status of the container. If health checks are not configured for this container
/// in its task definition, then it reports health status as <code>UNKNOWN</code>.
/// </para>
/// </summary>
public HealthStatus HealthStatus
{
get { return this._healthStatus; }
set { this._healthStatus = value; }
}
// Check to see if HealthStatus property is set
internal bool IsSetHealthStatus()
{
return this._healthStatus != null;
}
/// <summary>
/// Gets and sets the property LastStatus.
/// <para>
/// The last known status of the container.
/// </para>
/// </summary>
public string LastStatus
{
get { return this._lastStatus; }
set { this._lastStatus = value; }
}
// Check to see if LastStatus property is set
internal bool IsSetLastStatus()
{
return this._lastStatus != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the container.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property NetworkBindings.
/// <para>
/// The network bindings associated with the container.
/// </para>
/// </summary>
public List<NetworkBinding> NetworkBindings
{
get { return this._networkBindings; }
set { this._networkBindings = value; }
}
// Check to see if NetworkBindings property is set
internal bool IsSetNetworkBindings()
{
return this._networkBindings != null && this._networkBindings.Count > 0;
}
/// <summary>
/// Gets and sets the property NetworkInterfaces.
/// <para>
/// The network interfaces associated with the container.
/// </para>
/// </summary>
public List<NetworkInterface> NetworkInterfaces
{
get { return this._networkInterfaces; }
set { this._networkInterfaces = value; }
}
// Check to see if NetworkInterfaces property is set
internal bool IsSetNetworkInterfaces()
{
return this._networkInterfaces != null && this._networkInterfaces.Count > 0;
}
/// <summary>
/// Gets and sets the property Reason.
/// <para>
/// A short (255 max characters) human-readable string to provide additional details about
/// a running or stopped container.
/// </para>
/// </summary>
public string Reason
{
get { return this._reason; }
set { this._reason = value; }
}
// Check to see if Reason property is set
internal bool IsSetReason()
{
return this._reason != null;
}
/// <summary>
/// Gets and sets the property TaskArn.
/// <para>
/// The ARN of the task.
/// </para>
/// </summary>
public string TaskArn
{
get { return this._taskArn; }
set { this._taskArn = value; }
}
// Check to see if TaskArn property is set
internal bool IsSetTaskArn()
{
return this._taskArn != null;
}
}
} | 29.838095 | 102 | 0.55841 | [
"Apache-2.0"
] | GitGaby/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/Container.cs | 6,266 | C# |
using LNF.Billing;
using LNF.Billing.Reports.ServiceUnitBilling;
using LNF.CommonTools;
using sselFinOps.AppCode.DAL;
using System;
using System.Configuration;
using System.Data;
using System.Linq;
namespace sselFinOps.AppCode.SUB
{
public class RoomReport : ReportBase
{
public RoomReport(DateTime startPeriod, DateTime endPeriod) : base(startPeriod, endPeriod) { }
protected override void FillDataTable(DataTable dt)
{
BillingUnit summaryUnit = summaryUnits.First();
Compile mCompile = new Compile();
DataTable dtRoomDB = mCompile.CalcCost("Room", string.Empty, "ChargeTypeID", 5, EndPeriod.AddMonths(-1), 0, 0, Compile.AggType.CliAcctType);
DataTable dtClientWithCharges = mCompile.GetTable(1);
double roomCapCost = mCompile.CapCost;
//*****************************************************************************
//2008-01-22 The code below is an EXTRA step for calculating the cost of room charge
// Right now the strategy is not to change Compile.CalcCost at all and if I want to
// add new features that would affect CalcCost, I would rather do it after CalcCost is called.
// But future new design is required else the system will get too complicated.
//2208-05-15 the reason why we are doing this extra step is to show NAP rooms (as of now, it's DC Test lab and Chem room)
//with correct monthly fee on the JE
//dtNAPRoomForAllChargeType's columns
//CostID
//ChargeTypeID
//TableNameOrDescript
//RoomID
//AcctPer
//AddVal
//RoomCost
//effDate
//Get all active NAP Rooms with their costs, all chargetypes are returned
//This is a temporary table, it's used to derive the really useful table below
DataTable dtNAPRoomForAllChargeType = BLL.RoomManager.GetAllNAPRoomsWithCosts(EndPeriod);
//filter out the chargetype so that we only have Internal costs with each NAP room
DataRow[] drsNAPRoomForInternal = dtNAPRoomForAllChargeType.Select("ChargeTypeID = 5");
//Loop through each room and find out this specified month's apportionment data.
foreach (DataRow dr1 in drsNAPRoomForInternal)
{
DataTable dtApportionData = BLL.RoomApportionDataManager.GetNAPRoomApportionDataByPeriod(StartPeriod, EndPeriod, dr1.Field<int>("RoomID"));
foreach (DataRow dr2 in dtApportionData.Rows)
{
DataRow[] drs = dtRoomDB.Select(string.Format("ClientID = {0} AND AccountID = {1} AND RoomID = {2}", dr2["ClientID"], dr2["AccountID"], dr2["RoomID"]));
if (drs.Length == 1)
drs[0].SetField("TotalCalcCost", (dr2.Field<double>("Percentage") * dr1.Field<double>("RoomCost")) / 100);
}
}
dtRoomDB.Columns.Add("DebitAccount", typeof(string));
dtRoomDB.Columns.Add("CreditAccount", typeof(string));
dtRoomDB.Columns.Add("LineDesc", typeof(string));
dtRoomDB.Columns.Add("TotalAllAccountCost", typeof(double));
//dtRoom - ClientID, AccountID, RoomID, TotalCalCost, TotalEntries, TotalHours
// cap costs - capping is per clientorg, thus apportion cappeing across charges
// note that this assumes that there is only one org for internal academic!!!
object temp;
double totalRoomCharges;
foreach (DataRow drCWC in dtClientWithCharges.Rows)
{
temp = dtRoomDB.Compute("SUM(TotalCalcCost)", string.Format("ClientID = {0}", drCWC["ClientID"]));
if (temp == null || temp == DBNull.Value)
totalRoomCharges = 0;
else
totalRoomCharges = Convert.ToDouble(temp);
if (totalRoomCharges > roomCapCost)
{
DataRow[] fdr = dtRoomDB.Select(string.Format("ClientID = {0}", drCWC["ClientID"]));
for (int i = 0; i < fdr.Length; i++)
fdr[i].SetField("TotalCalcCost", fdr[i].Field<double>("TotalCalcCost") * roomCapCost / totalRoomCharges);
}
}
DataTable dtClient = ClientDA.GetAllClient(StartPeriod, EndPeriod);
DataTable dtAccount = AccountDA.GetAllInternalAccount(StartPeriod, EndPeriod);
DataTable dtClientAccount = ClientDA.GetAllClientAccountWithManagerName(StartPeriod, EndPeriod); //used to find out manager's name
//Get the general lab account ID and lab credit account ID
GlobalCost gc = GlobalCostDA.GetGlobalCost();
//2008-05-15 very complicated code - trying to figure out the percentage distribution for monthly users, since the "TotalCalcCost" has
//been calculated based on percentage in the CalcCost function, so we need to figure out the percentage here again by findind out the total
//and divide the individual record's "TotalCalcCost'
foreach (DataRow drCWC in dtClientWithCharges.Rows)
{
DataRow[] fdr = dtRoomDB.Select(string.Format("ClientID = {0} AND RoomID = {1}", drCWC["ClientID"], (int)BLL.LabRoom.CleanRoom));
if (fdr.Length > 1)
{
//this user has multiple account for the clean room usage, so we have to find out the total of all accounts on this clean room
double tempTotal = Convert.ToDouble(dtRoomDB.Compute("SUM(TotalCalcCost)", string.Format("ClientID = {0} AND RoomID = {1}", drCWC["ClientID"], (int)BLL.LabRoom.CleanRoom)));
DataRow[] fdrRoom = dtRoomDB.Select(string.Format("ClientID = {0} AND RoomID = {1}", drCWC["ClientID"], (int)BLL.LabRoom.CleanRoom));
for (int i = 0; i < fdrRoom.Length; i++)
fdrRoom[i].SetField("TotalAllAccountCost", tempTotal); //assign the total to each record
}
}
//2008-08-28 Get Billing Type
DataTable dtBillingType = BillingTypeDA.GetAllBillingTypes();
foreach (DataRow dr in dtRoomDB.Rows)
{
dr["DebitAccount"] = dtAccount.Rows.Find(dr.Field<int>("AccountID"))["Number"];
dr["CreditAccount"] = dtAccount.Rows.Find(gc.LabCreditAccountID)["Number"];
//2007-06-19 financial manager may not be an administrator, but their username must be on JE
dr["LineDesc"] = GetLineDesc(dr, dtClient, dtBillingType);
//2008-05-15 the code below handles the clean room monthly users - it's special code that we have to get rid of when all
//billingtype are all gone
int billingTypeId = dr.Field<int>("BillingType");
if (dr.Field<BLL.LabRoom>("RoomID") == BLL.LabRoom.CleanRoom) //6 is clean room
{
if (BillingTypes.IsMonthlyUserBillingType(billingTypeId))
{
if (dr["TotalAllAccountCost"] == DBNull.Value)
{
//if TotalAllAccountCost is nothing, it means this user has only one account
//2008-10-27 but it might also that the user has only one internal account, and he apportion all hours to his external accouts
//so we must also check 'TotalHours' to make sure the user has more than 0 hours
if (dr.Field<double>("TotalHours") != 0)
dr.SetField("TotalCalcCost", BLL.BillingTypeManager.GetTotalCostByBillingType(billingTypeId, 0, 0, BLL.LabRoom.CleanRoom, 1315));
}
else
{
double total = dr.Field<double>("TotalAllAccountCost");
dr.SetField("TotalCalcCost", (dr.Field<double>("TotalCalcCost") / total) * BLL.BillingTypeManager.GetTotalCostByBillingType(billingTypeId, 0, 0, BLL.LabRoom.CleanRoom, 1315));
}
}
}
}
//****** apply filters ******
//Get the list below so that we can exclude users who spent less than X minutes in lab(Clean or Chem) in this month
DataTable dtlistClean = RoomUsageData.GetUserListLessThanXMin(StartPeriod, EndPeriod, int.Parse(ConfigurationManager.AppSettings["CleanRoomMinTimeMinute"]), "CleanRoom");
DataTable dtlistChem = RoomUsageData.GetUserListLessThanXMin(StartPeriod, EndPeriod, int.Parse(ConfigurationManager.AppSettings["ChemRoomMinTimeMinute"]), "ChemRoom");
//For performance issue, we have to calculate something first, since it's used on all rows
string depRefNum = string.Empty;
double fTotal = 0;
string creditAccount = dtAccount.Rows.Find(gc.LabCreditAccountID)["Number"].ToString();
string creditAccountShortCode = dtAccount.Rows.Find(gc.LabCreditAccountID)["ShortCode"].ToString();
//Do not show an item if the charge and xcharge accounts are the 'same' - can only happen for 941975
//Do not show items that are associated with specific accounts - need to allow users to add manually here in future
foreach (DataRow sdr in dtRoomDB.Rows)
{
if (sdr.Field<double>("TotalCalcCost") > 0)
{
var excludedAccounts = new[] { gc.LabAccountID, 143, 179, 188 };
if (!excludedAccounts.Contains(sdr.Field<int>("AccountID")) && sdr.Field<int>("BillingType") != BillingTypes.Other)
{
//2006-12-21 get rid of people who stayed in the lab less than 30 minutes in a month
string expression = string.Format("ClientID = {0}", sdr["ClientID"]);
DataRow[] foundRows;
bool flag = false;
if (sdr.Field<BLL.LabRoom>("RoomID") == BLL.LabRoom.CleanRoom) //6 = clean room
foundRows = dtlistClean.Select(expression);
else if (sdr.Field<BLL.LabRoom>("RoomID") == BLL.LabRoom.ChemRoom) //25 = chem room
foundRows = dtlistChem.Select(expression);
else //DCLab
foundRows = null;
if (foundRows == null)
flag = true; //add to the SUB
else
{
if (foundRows.Length == 0)
flag = true;
}
if (flag) //if no foundrow, we can add this client to JE
{
DataRow ndr = dt.NewRow();
DataRow drAccount = dtAccount.Rows.Find(sdr.Field<int>("AccountID"));
string debitAccount = drAccount["Number"].ToString();
string shortCode = drAccount["ShortCode"].ToString();
//get manager's name
DataRow[] drClientAccount = dtClientAccount.Select(string.Format("AccountID = {0}", sdr["AccountID"]));
if (drClientAccount.Length > 0)
depRefNum = drClientAccount[0]["ManagerName"].ToString();
else
depRefNum = "No Manager Found";
AccountNumber debitAccountNum = AccountNumber.Parse(debitAccount);
ndr["CardType"] = 1;
ndr["ShortCode"] = shortCode;
ndr["Account"] = debitAccountNum.Account;
ndr["FundCode"] = debitAccountNum.FundCode;
ndr["DeptID"] = debitAccountNum.DeptID;
ndr["ProgramCode"] = debitAccountNum.ProgramCode;
ndr["Class"] = debitAccountNum.Class;
ndr["ProjectGrant"] = debitAccountNum.ProjectGrant;
ndr["VendorID"] = "0000456136";
ndr["InvoiceDate"] = EndPeriod.AddMonths(-1).ToString("yyyy/MM/dd");
ndr["InvoiceID"] = $"{ReportSettings.CompanyName} Room Charge";
ndr["Uniqname"] = dtClient.Rows.Find(sdr.Field<int>("ClientID"))["UserName"];
ndr["DepartmentalReferenceNumber"] = depRefNum;
ndr["ItemDescription"] = GetItemDesc(sdr, dtClient, dtBillingType);
ndr["QuantityVouchered"] = "1.0000";
double chargeAmount = Math.Round(sdr.Field<double>("TotalCalcCost"), 5);
ndr["UnitOfMeasure"] = chargeAmount;
ndr["MerchandiseAmount"] = Math.Round(chargeAmount, 2);
ndr["CreditAccount"] = creditAccount;
//Used to calculate the total credit amount
fTotal += chargeAmount;
dt.Rows.Add(ndr);
}
}
}
}
//Summary row
summaryUnit.CardType = 1;
summaryUnit.ShortCode = creditAccountShortCode;
summaryUnit.Account = creditAccount.Substring(0, 6);
summaryUnit.FundCode = creditAccount.Substring(6, 5);
summaryUnit.DeptID = creditAccount.Substring(11, 6);
summaryUnit.ProgramCode = creditAccount.Substring(17, 5);
summaryUnit.ClassName = creditAccount.Substring(22, 5);
summaryUnit.ProjectGrant = creditAccount.Substring(27, 7);
summaryUnit.InvoiceDate = EndPeriod.AddMonths(-1).ToString("yyyy/MM/dd");
summaryUnit.Uniqname = ReportSettings.FinancialManagerUserName;
summaryUnit.DepartmentalReferenceNumber = depRefNum;
summaryUnit.ItemDescription = ReportSettings.FinancialManagerUserName;
summaryUnit.MerchandiseAmount = Math.Round(-fTotal, 2);
summaryUnit.CreditAccount = creditAccount;
//Clean things up manually might help performance in general
dtRoomDB.Clear();
dtClient.Clear();
dtAccount.Clear();
}
public override string GenerateExcelFile(DataTable dt)
{
return GenerateExcel(dt, "LabtimeSUB");
}
}
} | 57.057692 | 203 | 0.563802 | [
"MIT"
] | lurienanofab/sselfinops | sselFinOps.AppCode/SUB/RoomReport.cs | 14,837 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.ComputeOptimizer")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Compute Optimizer. Initial release of AWS Compute Optimizer. AWS Compute Optimizer recommends optimal AWS Compute resources to reduce costs and improve performance for your workloads.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.5")] | 48.375 | 267 | 0.757106 | [
"Apache-2.0"
] | gnurg/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/ComputeOptimizer/Properties/AssemblyInfo.cs | 1,548 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MetaDslx.CodeAnalysis.Antlr4Test.TestLanguageAnnotations
{
public class UnitTest04 : UnitTestBase01
{
public UnitTest04()
{
TestId = "04";
}
}
}
| 18.133333 | 66 | 0.647059 | [
"Apache-2.0"
] | balazssimon/meta-cs | src/Test/MetaDslx.CodeAnalysis.Antlr4.Test/TestLanguageAnnotations/UnitTest04.cs | 274 | C# |
using System;
using System.Collections.Generic;
namespace Seq.Api.Model.Diagnostics
{
public class ServerMetricsEntity : Entity
{
public ServerMetricsEntity()
{
RunningTasks = new List<RunningTaskPart>();
}
public double EventStoreDaysRecorded { get; set; }
public double EventStoreDaysCached { get; set; }
public int EventStoreEventsCached { get; set; }
public DateTime? EventStoreFirstSegmentDateUtc { get; set; }
public DateTime? EventStoreLastSegmentDateUtc { get; set; }
public long EventStoreDiskRemainingBytes { get; set; }
public int EndpointArrivalsPerMinute { get; set; }
public int EndpointInfluxPerMinute { get; set; }
public long EndpointIngestedBytesPerMinute { get; set; }
public int EndpointInvalidPayloadsPerMinute { get; set; }
public int EndpointUnauthorizedPayloadsPerMinute { get; set; }
public TimeSpan ProcessUptime { get; set; }
public long ProcessWorkingSetBytes { get; set; }
public int ProcessThreads { get; set; }
public int ProcessThreadPoolUserThreadsAvailable { get; set; }
public int ProcessThreadPoolIocpThreadsAvailable { get; set; }
public double SystemMemoryUtilization { get; set; }
public List<RunningTaskPart> RunningTasks { get; set; }
public int QueriesPerMinute { get; set; }
public int QueryCacheTimeSliceHitsPerMinute { get; set; }
public int QueryCacheInvalidationsPerMinute { get; set; }
public int DocumentStoreActiveSessions { get; set; }
public int DocumentStoreActiveTransactions { get; set; }
}
}
| 38.386364 | 70 | 0.678508 | [
"Apache-2.0"
] | nblumhardt/seq-api | src/Seq.Api/Api/Model/Diagnostics/ServerMetricsEntity.cs | 1,691 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using SlimDX;
using FDK;
using System.Linq;
namespace TJAPlayer4
{
/// <summary>
/// プライベートフォントでの描画を扱うクラス。
/// </summary>
/// <exception cref="FileNotFoundException">フォントファイルが見つからない時に例外発生</exception>
/// <exception cref="ArgumentException">スタイル指定不正時に例外発生</exception>
/// <remarks>
/// 簡単な使い方
/// CPrivateFont prvFont = new CPrivateFont( CSkin.Path( @"Graphics\fonts\mplus-1p-bold.ttf" ), 36 ); // プライベートフォント
/// とか
/// CPrivateFont prvFont = new CPrivateFont( new FontFamily("MS UI Gothic"), 36, FontStyle.Bold ); // システムフォント
/// とかした上で、
/// Bitmap bmp = prvFont.DrawPrivateFont( "ABCDE", Color.White, Color.Black ); // フォント色=白、縁の色=黒の例。縁の色は省略可能
/// とか
/// Bitmap bmp = prvFont.DrawPrivateFont( "ABCDE", Color.White, Color.Black, Color.Yellow, Color.OrangeRed ); // 上下グラデーション(Yellow→OrangeRed)
/// とかして、
/// CTexture ctBmp = CDTXMania.tテクスチャの生成( bmp, false );
/// ctBMP.t2D描画( ~~~ );
/// で表示してください。
///
/// 注意点
/// 任意のフォントでのレンダリングは結構負荷が大きいので、なるべkなら描画フレーム毎にフォントを再レンダリングするようなことはせず、
/// 一旦レンダリングしたものを描画に使い回すようにしてください。
/// また、長い文字列を与えると、返されるBitmapも横長になります。この横長画像をそのままテクスチャとして使うと、
/// 古いPCで問題を発生させやすいです。これを回避するには、一旦Bitmapとして取得したのち、256pixや512pixで分割して
/// テクスチャに定義するようにしてください。
/// </remarks>
#region In拡張子
public static class StringExtensions
{
public static bool In(this string str, params string[] param)
{
return param.Contains(str);
}
}
#endregion
public class CPrivateFont : IDisposable
{
#region [ コンストラクタ ]
public CPrivateFont( FontFamily fontfamily, int pt, FontStyle style )
{
Initialize( null, fontfamily, pt, style );
}
public CPrivateFont( FontFamily fontfamily, int pt )
{
Initialize( null, fontfamily, pt, FontStyle.Regular );
}
public CPrivateFont( string fontpath, int pt, FontStyle style )
{
Initialize( fontpath, null, pt, style );
}
public CPrivateFont( string fontpath, int pt )
{
Initialize( fontpath, null, pt, FontStyle.Regular );
}
public CPrivateFont()
{
//throw new ArgumentException("CPrivateFont: 引数があるコンストラクタを使用してください。");
}
#endregion
protected void Initialize( string fontpath, FontFamily fontfamily, int pt, FontStyle style )
{
this._pfc = null;
this._fontfamily = null;
this._font = null;
this._pt = pt;
this._rectStrings = new Rectangle(0, 0, 0, 0);
this._ptOrigin = new Point(0, 0);
this.bDispose完了済み = false;
if (fontfamily != null)
{
this._fontfamily = fontfamily;
}
else
{
try
{
this._pfc = new System.Drawing.Text.PrivateFontCollection(); //PrivateFontCollectionオブジェクトを作成する
this._pfc.AddFontFile(fontpath); //PrivateFontCollectionにフォントを追加する
_fontfamily = _pfc.Families[0];
}
catch (System.IO.FileNotFoundException)
{
Trace.TraceWarning("プライベートフォントの追加に失敗しました({0})。代わりにMS UI Gothicの使用を試みます。", fontpath);
//throw new FileNotFoundException( "プライベートフォントの追加に失敗しました。({0})", Path.GetFileName( fontpath ) );
//return;
_fontfamily = null;
}
//foreach ( FontFamily ff in _pfc.Families )
//{
// Debug.WriteLine( "fontname=" + ff.Name );
// if ( ff.Name == Path.GetFileNameWithoutExtension( fontpath ) )
// {
// _fontfamily = ff;
// break;
// }
//}
//if ( _fontfamily == null )
//{
// Trace.TraceError( "プライベートフォントの追加後、検索に失敗しました。({0})", fontpath );
// return;
//}
}
// 指定されたフォントスタイルが適用できない場合は、フォント内で定義されているスタイルから候補を選んで使用する
// 何もスタイルが使えないようなフォントなら、例外を出す。
if (_fontfamily != null)
{
if (!_fontfamily.IsStyleAvailable(style))
{
FontStyle[] FS = { FontStyle.Regular, FontStyle.Bold, FontStyle.Italic, FontStyle.Underline, FontStyle.Strikeout };
style = FontStyle.Regular | FontStyle.Bold | FontStyle.Italic | FontStyle.Underline | FontStyle.Strikeout; // null非許容型なので、代わりに全盛をNGワードに設定
foreach (FontStyle ff in FS)
{
if (this._fontfamily.IsStyleAvailable(ff))
{
style = ff;
Trace.TraceWarning("フォント{0}へのスタイル指定を、{1}に変更しました。", Path.GetFileName(fontpath), style.ToString());
break;
}
}
if (style == (FontStyle.Regular | FontStyle.Bold | FontStyle.Italic | FontStyle.Underline | FontStyle.Strikeout))
{
Trace.TraceWarning("フォント{0}は適切なスタイル{1}を選択できませんでした。", Path.GetFileName(fontpath), style.ToString());
}
}
//this._font = new Font(this._fontfamily, pt, style); //PrivateFontCollectionの先頭のフォントのFontオブジェクトを作成する
float emSize = pt * 96.0f / 72.0f;
this._font = new Font(this._fontfamily, emSize, style, GraphicsUnit.Pixel); //PrivateFontCollectionの先頭のフォントのFontオブジェクトを作成する
//HighDPI対応のため、pxサイズで指定
}
else
// フォントファイルが見つからなかった場合 (MS PGothicを代わりに指定する)
{
float emSize = pt * 96.0f / 72.0f;
this._font = new Font("MS UI Gothic", emSize, style, GraphicsUnit.Pixel); //MS PGothicのFontオブジェクトを作成する
FontFamily[] ffs = new System.Drawing.Text.InstalledFontCollection().Families;
int lcid = System.Globalization.CultureInfo.GetCultureInfo("en-us").LCID;
foreach (FontFamily ff in ffs)
{
// Trace.WriteLine( lcid ) );
if (ff.GetName(lcid) == "MS UI Gothic")
{
this._fontfamily = ff;
Trace.TraceInformation("MS UI Gothicを代わりに指定しました。");
return;
}
}
throw new FileNotFoundException("プライベートフォントの追加に失敗し、MS UI Gothicでの代替処理にも失敗しました。({0})", Path.GetFileName(fontpath));
}
}
[Flags]
public enum DrawMode
{
Normal,
Edge,
Gradation,
Vertical
}
#region [ DrawPrivateFontのオーバーロード群 ]
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <returns>描画済テクスチャ</returns>
public Bitmap DrawPrivateFont( string drawstr, Color fontColor )
{
return DrawPrivateFont( drawstr, DrawMode.Normal, fontColor, Color.White, Color.White, Color.White );
}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <returns>描画済テクスチャ</returns>
public Bitmap DrawPrivateFont( string drawstr, Color fontColor, Color edgeColor )
{
return DrawPrivateFont( drawstr, DrawMode.Edge, fontColor, edgeColor, Color.White, Color.White );
}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
//public Bitmap DrawPrivateFont( string drawstr, Color fontColor, Color gradationTopColor, Color gradataionBottomColor )
//{
// return DrawPrivateFont( drawstr, DrawMode.Gradation, fontColor, Color.White, gradationTopColor, gradataionBottomColor );
//}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
public Bitmap DrawPrivateFont( string drawstr, Color fontColor, Color edgeColor, Color gradationTopColor, Color gradataionBottomColor )
{
return DrawPrivateFont( drawstr, DrawMode.Edge | DrawMode.Gradation, fontColor, edgeColor, gradationTopColor, gradataionBottomColor );
}
#if こちらは使わない // (Bitmapではなく、CTextureを返す版)
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <returns>描画済テクスチャ</returns>
public CTexture DrawPrivateFont( string drawstr, Color fontColor )
{
Bitmap bmp = DrawPrivateFont( drawstr, DrawMode.Normal, fontColor, Color.White, Color.White, Color.White );
return CDTXMania.tテクスチャの生成( bmp, false );
}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <returns>描画済テクスチャ</returns>
public CTexture DrawPrivateFont( string drawstr, Color fontColor, Color edgeColor )
{
Bitmap bmp = DrawPrivateFont( drawstr, DrawMode.Edge, fontColor, edgeColor, Color.White, Color.White );
return CDTXMania.tテクスチャの生成( bmp, false );
}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
//public CTexture DrawPrivateFont( string drawstr, Color fontColor, Color gradationTopColor, Color gradataionBottomColor )
//{
// Bitmap bmp = DrawPrivateFont( drawstr, DrawMode.Gradation, fontColor, Color.White, gradationTopColor, gradataionBottomColor );
// return CDTXMania.tテクスチャの生成( bmp, false );
//}
/// <summary>
/// 文字列を描画したテクスチャを返す
/// </summary>
/// <param name="drawstr">描画文字列</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
public CTexture DrawPrivateFont( string drawstr, Color fontColor, Color edgeColor, Color gradationTopColor, Color gradataionBottomColor )
{
Bitmap bmp = DrawPrivateFont( drawstr, DrawMode.Edge | DrawMode.Gradation, fontColor, edgeColor, gradationTopColor, gradataionBottomColor );
return CDTXMania.tテクスチャの生成( bmp, false );
}
#endif
#endregion
/// <summary>
/// 文字列を描画したテクスチャを返す(メイン処理)
/// </summary>
/// <param name="rectDrawn">描画された領域</param>
/// <param name="ptOrigin">描画文字列</param>
/// <param name="drawstr">描画文字列</param>
/// <param name="drawmode">描画モード</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
protected Bitmap DrawPrivateFont( string drawstr, DrawMode drawmode, Color fontColor, Color edgeColor, Color gradationTopColor, Color gradationBottomColor )
{
if ( this._fontfamily == null || drawstr == null || drawstr == "" )
{
// nullを返すと、その後bmp→texture処理や、textureのサイズを見て__の処理で全部例外が発生することになる。
// それは非常に面倒なので、最小限のbitmapを返してしまう。
// まずはこの仕様で進めますが、問題有れば(上位側からエラー検出が必要であれば)例外を出したりエラー状態であるプロパティを定義するなり検討します。
if ( drawstr != "" )
{
Trace.TraceWarning( "DrawPrivateFont()の入力不正。最小値のbitmapを返します。" );
}
_rectStrings = new Rectangle( 0, 0, 0, 0 );
_ptOrigin = new Point( 0, 0 );
return new Bitmap(1, 1);
}
bool bEdge = ( ( drawmode & DrawMode.Edge ) == DrawMode.Edge );
bool bGradation = ( ( drawmode & DrawMode.Gradation ) == DrawMode.Gradation );
// 縁取りの縁のサイズは、とりあえずフォントの大きさの1/4とする
//int nEdgePt = (bEdge)? _pt / 4 : 0;
//int nEdgePt = (bEdge) ? (_pt / 3) : 0; // 縁取りが少なすぎるという意見が多かったため変更。 (AioiLight)
int nEdgePt = (bEdge) ? (10 * _pt / TJAPlayer4.Skin.Font_Edge_Ratio) : 0; //SkinConfigにて設定可能に(rhimm)
// 描画サイズを測定する
Size stringSize = System.Windows.Forms.TextRenderer.MeasureText( drawstr, this._font, new Size( int.MaxValue, int.MaxValue ),
System.Windows.Forms.TextFormatFlags.NoPrefix |
System.Windows.Forms.TextFormatFlags.NoPadding
);
stringSize.Width += 10; //2015.04.01 kairera0467 ROTTERDAM NATIONの描画サイズがうまくいかんので。
//取得した描画サイズを基に、描画先のbitmapを作成する
Bitmap bmp = new Bitmap( stringSize.Width + nEdgePt * 2, stringSize.Height + nEdgePt * 2 );
bmp.MakeTransparent();
Graphics g = Graphics.FromImage( bmp );
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Far; // 画面下部(垂直方向位置)
sf.Alignment = StringAlignment.Center; // 画面中央(水平方向位置)
sf.FormatFlags = StringFormatFlags.NoWrap; // どんなに長くて単語の区切りが良くても改行しない (AioiLight)
sf.Trimming = StringTrimming.None; // どんなに長くてもトリミングしない (AioiLight)
// レイアウト枠
Rectangle r = new Rectangle( 0, 0, stringSize.Width + nEdgePt * 2 + (TJAPlayer4.Skin.Text_Correction_X * stringSize.Width / 100), stringSize.Height + nEdgePt * 2 + (TJAPlayer4.Skin.Text_Correction_Y * stringSize.Height / 100));
if ( bEdge ) // 縁取り有りの描画
{
// DrawPathで、ポイントサイズを使って描画するために、DPIを使って単位変換する
// (これをしないと、単位が違うために、小さめに描画されてしまう)
float sizeInPixels = _font.SizeInPoints * g.DpiY / 72; // 1 inch = 72 points
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddString( drawstr, this._fontfamily, (int) this._font.Style, sizeInPixels, r, sf );
// 縁取りを描画する
Pen p = new Pen( edgeColor, nEdgePt );
p.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
g.DrawPath( p, gp );
// 塗りつぶす
Brush br;
if ( bGradation )
{
br = new LinearGradientBrush( r, gradationTopColor, gradationBottomColor, LinearGradientMode.Vertical );
}
else
{
br = new SolidBrush( fontColor );
}
g.FillPath( br, gp );
if ( br != null ) br.Dispose(); br = null;
if ( p != null ) p.Dispose(); p = null;
if ( gp != null ) gp.Dispose(); gp = null;
}
else
{
// 縁取りなしの描画
System.Windows.Forms.TextRenderer.DrawText( g, drawstr, _font, new Point( 0, 0 ), fontColor );
}
#if debug表示
g.DrawRectangle( new Pen( Color.White, 1 ), new Rectangle( 1, 1, stringSize.Width-1, stringSize.Height-1 ) );
g.DrawRectangle( new Pen( Color.Green, 1 ), new Rectangle( 0, 0, bmp.Width - 1, bmp.Height - 1 ) );
#endif
_rectStrings = new Rectangle( 0, 0, stringSize.Width, stringSize.Height );
_ptOrigin = new Point( nEdgePt * 2, nEdgePt * 2 );
#region [ リソースを解放する ]
if ( sf != null ) sf.Dispose(); sf = null;
if ( g != null ) g.Dispose(); g = null;
#endregion
return bmp;
}
/// <summary>
/// 文字列を描画したテクスチャを返す(メイン処理)
/// </summary>
/// <param name="rectDrawn">描画された領域</param>
/// <param name="ptOrigin">描画文字列</param>
/// <param name="drawstr">描画文字列</param>
/// <param name="drawmode">描画モード</param>
/// <param name="fontColor">描画色</param>
/// <param name="edgeColor">縁取色</param>
/// <param name="gradationTopColor">グラデーション 上側の色</param>
/// <param name="gradationBottomColor">グラデーション 下側の色</param>
/// <returns>描画済テクスチャ</returns>
protected Bitmap DrawPrivateFont_V( string drawstr, Color fontColor, Color edgeColor, bool bVertical )
{
if ( this._fontfamily == null || drawstr == null || drawstr == "" )
{
// nullを返すと、その後bmp→texture処理や、textureのサイズを見て__の処理で全部例外が発生することになる。
// それは非常に面倒なので、最小限のbitmapを返してしまう。
// まずはこの仕様で進めますが、問題有れば(上位側からエラー検出が必要であれば)例外を出したりエラー状態であるプロパティを定義するなり検討します。
if ( drawstr != "" )
{
Trace.TraceWarning( "DrawPrivateFont()の入力不正。最小値のbitmapを返します。" );
}
_rectStrings = new Rectangle( 0, 0, 0, 0 );
_ptOrigin = new Point( 0, 0 );
return new Bitmap(1, 1);
}
//StreamWriter stream = stream = new StreamWriter("Test.txt", false);
//try
//{
// stream = new StreamWriter("Test.txt", false);
//}
//catch (Exception ex)
//{
// stream.Close();
// stream = new StreamWriter("Test.txt", false);
//}
string[] strName = new string[ drawstr.Length ];
for( int i = 0; i < drawstr.Length; i++ ) strName[i] = drawstr.Substring(i, 1);
#region[ キャンバスの大きさ予測 ]
//大きさを計算していく。
int nHeight = 0;
for( int i = 0; i < strName.Length; i++ )
{
Size strSize = System.Windows.Forms.TextRenderer.MeasureText( strName[ i ], this._font, new Size( int.MaxValue, int.MaxValue ),
System.Windows.Forms.TextFormatFlags.NoPrefix |
System.Windows.Forms.TextFormatFlags.NoPadding );
//stringformatは最初にやっていてもいいだろう。
StringFormat sFormat = new StringFormat();
sFormat.LineAlignment = StringAlignment.Center; // 画面下部(垂直方向位置)
sFormat.Alignment = StringAlignment.Center; // 画面中央(水平方向位置)
//できるだけ正確な値を計算しておきたい...!
Bitmap bmpDummy = new Bitmap( 150, 150 ); //とりあえず150
Graphics gCal = Graphics.FromImage( bmpDummy );
Rectangle rect正確なサイズ = this.MeasureStringPrecisely( gCal, strName[ i ], this._font, strSize, sFormat );
int n余白サイズ = strSize.Height - rect正確なサイズ.Height;
Rectangle rect = new Rectangle( 0, -n余白サイズ + 2, 46, ( strSize.Height + 16 ));
if( strName[ i ] == "ー" || strName[ i ] == "-" || strName[ i ] == "~" || strName[ i ] == "<" || strName[ i ] == ">" || strName[ i ] == "(" || strName[ i ] == ")" || strName[ i ] == "「" || strName[ i ] == "」" || strName[ i ] == "[" || strName[ i ] == "]" )
{
nHeight += ( rect正確なサイズ.Width ) + 4;
}
else if( strName[ i ] == "_" ){ nHeight += ( rect正確なサイズ.Height ) + 6; }
else if( strName[ i ] == " " )
{ nHeight += ( 12 ); }
else { nHeight += ( rect正確なサイズ.Height ) + 10; }
//念のため解放
bmpDummy.Dispose();
gCal.Dispose();
//stream.WriteLine( "文字の大きさ{0},大きさ合計{1}", ( rect正確なサイズ.Height ) + 6, nHeight );
}
#endregion
Bitmap bmpCambus = new Bitmap( 46, nHeight );
Graphics Gcambus = Graphics.FromImage( bmpCambus );
//キャンバス作成→1文字ずつ作成してキャンバスに描画という形がよさそうかな?
int nNowPos = 0;
int nAdded = 0;
int nEdge補正X = 0;
int nEdge補正Y = 0;
if (this._pt < 18)
nAdded = nAdded - 2;
for (int i = 0; i < strName.Length; i++)
{
Size strSize = System.Windows.Forms.TextRenderer.MeasureText(strName[i], this._font, new Size(int.MaxValue, int.MaxValue),
System.Windows.Forms.TextFormatFlags.NoPrefix |
System.Windows.Forms.TextFormatFlags.NoPadding);
//stringformatは最初にやっていてもいいだろう。
StringFormat sFormat = new StringFormat();
sFormat.LineAlignment = StringAlignment.Center; // 画面下部(垂直方向位置)
sFormat.Alignment = StringAlignment.Near; // 画面中央(水平方向位置)
//できるだけ正確な値を計算しておきたい...!
Bitmap bmpDummy = new Bitmap(150, 150); //とりあえず150
Graphics gCal = Graphics.FromImage(bmpDummy);
Rectangle rect正確なサイズ = this.MeasureStringPrecisely(gCal, strName[i], this._font, strSize, sFormat);
int n余白サイズ = strSize.Height - rect正確なサイズ.Height;
//Bitmap bmpV = new Bitmap( 36, ( strSize.Height + 12 ) - 6 );
Bitmap bmpV = new Bitmap((rect正確なサイズ.Width + 12) + nAdded, (rect正確なサイズ.Height) + 12);
bmpV.MakeTransparent();
Graphics gV = Graphics.FromImage(bmpV);
gV.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
if (strName[i].In(TJAPlayer4.Skin.SongSelect_CorrectionX_Chara))
{
nEdge補正X = TJAPlayer4.Skin.SongSelect_CorrectionX_Chara_Value;
}
else
{
nEdge補正X = 0;
}
if (strName[i].In(TJAPlayer4.Skin.SongSelect_CorrectionY_Chara))
{
nEdge補正Y = TJAPlayer4.Skin.SongSelect_CorrectionY_Chara_Value;
}
else
{
nEdge補正Y = 0;
}
//X座標、Y座標それぞれについて、SkinConfig内でズレを直したい文字を , で区切って列挙して、
//補正値を記入することで、特定のそれらの文字について一括で座標をずらす。
//現時点では補正値をX,Y各座標について1個ずつしか取れない(複数対1)ので、
//文字を列挙して、同じ数だけそれぞれの文字の補正値を記入できるような枠組をつくりたい。(20181205 rhimm)
Rectangle rect = new Rectangle(-3 - nAdded + (nEdge補正X * _pt / 100), -rect正確なサイズ.Y - 2 + (nEdge補正Y * _pt / 100), (strSize.Width + 12), (strSize.Height + 12));
//Rectangle rect = new Rectangle( 0, -rect正確なサイズ.Y - 2, 36, rect正確なサイズ.Height + 10);
// DrawPathで、ポイントサイズを使って描画するために、DPIを使って単位変換する
// (これをしないと、単位が違うために、小さめに描画されてしまう)
float sizeInPixels = _font.SizeInPoints * gV.DpiY / 72; // 1 inch = 72 points
System.Drawing.Drawing2D.GraphicsPath gpV = new System.Drawing.Drawing2D.GraphicsPath();
gpV.AddString(strName[i], this._fontfamily, (int)this._font.Style, sizeInPixels, rect, sFormat);
// 縁取りを描画する
//int nEdgePt = (_pt / 3); // 縁取りをフォントサイズ基準に変更
int nEdgePt = (10 * _pt / TJAPlayer4.Skin.Font_Edge_Ratio_Vertical); // SkinConfigにて設定可能に(rhimm)
Pen pV = new Pen(edgeColor, nEdgePt);
pV.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
gV.DrawPath(pV, gpV);
// 塗りつぶす
Brush brV;
{
brV = new SolidBrush(fontColor);
}
gV.FillPath(brV, gpV);
if (brV != null) brV.Dispose(); brV = null;
if (pV != null) pV.Dispose(); pV = null;
if (gpV != null) gpV.Dispose(); gpV = null;
if (gV != null) gV.Dispose(); gV = null;
int n補正 = 0;
int nY補正 = 0;
if (strName[i] == "ー" || strName[i] == "-" || strName[i] == "~")
{
bmpV.RotateFlip(RotateFlipType.Rotate90FlipNone);
n補正 = 2;
if (this._pt < 20)
n補正 = 0;
//nNowPos = nNowPos - 2;
}
else if (strName[i] == "<" || strName[i] == ">" || strName[i] == "(" || strName[i] == ")" || strName[i] == "[" || strName[i] == "]" || strName[i] == "」" || strName[i] == ")" || strName[i] == "』")
{
bmpV.RotateFlip(RotateFlipType.Rotate90FlipNone);
n補正 = 2;
if (this._pt < 20)
{
n補正 = 0;
//nNowPos = nNowPos - 4;
}
}
else if (strName[i] == "「" || strName[i] == "(" || strName[i] == "『")
{
bmpV.RotateFlip(RotateFlipType.Rotate90FlipNone);
n補正 = 2;
if (this._pt < 20)
{
n補正 = 2;
//nNowPos = nNowPos;
}
}
else if (strName[i] == "・")
{
n補正 = -8;
if (this._pt < 20)
{
n補正 = -8;
//nNowPos = nNowPos;
}
}
else if (strName[i] == ".")
{
n補正 = 8;
if (this._pt < 20)
{
n補正 = 8;
//nNowPos = nNowPos;
}
}
else if (strName[i].In(TJAPlayer4.Skin.SongSelect_Rotate_Chara))
{
bmpV.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
//個別の文字に関して、カンマで区切ってSkinConfigに記入したものを回転させる(20181205 rhimm)
//else if( strName[ i ] == "_" )
// nNowPos = nNowPos + 20;
else if( strName[ i ] == " " )
nNowPos = nNowPos + 10;
//bmpV.Save( "String" + i.ToString() + ".png" );
if( i == 0 )
{
nNowPos = 4;
}
Gcambus.DrawImage( bmpV, (bmpCambus.Width / 2) - (bmpV.Width / 2) + n補正, nNowPos + nY補正 );
nNowPos += bmpV.Size.Height - 6;
if( bmpV != null ) bmpV.Dispose(); bmpV = null;
if( gCal != null ) gCal.Dispose(); gCal = null;
//bmpCambus.Save( "test.png" );
//if( this._pt < 20 )
// bmpCambus.Save( "test_S.png" );
_rectStrings = new Rectangle( 0, 0, strSize.Width, strSize.Height );
_ptOrigin = new Point( 6 * 2, 6 * 2 );
//stream.WriteLine( "黒無しサイズ{0},余白{1},黒あり予測サイズ{2},ポ↑ジ↓{3}",rect正確なサイズ.Height, n余白サイズ, rect正確なサイズ.Height + 8, nNowPos );
}
//stream.Close();
if( Gcambus != null ) Gcambus.Dispose();
//return bmp;
return bmpCambus;
}
///// <summary>
///// 文字列を描画したテクスチャを返す(メイン処理)
///// </summary>
///// <param name="rectDrawn">描画された領域</param>
///// <param name="ptOrigin">描画文字列</param>
///// <param name="drawstr">描画文字列</param>
///// <param name="drawmode">描画モード</param>
///// <param name="fontColor">描画色</param>
///// <param name="edgeColor">縁取色</param>
///// <param name="gradationTopColor">グラデーション 上側の色</param>
///// <param name="gradationBottomColor">グラデーション 下側の色</param>
///// <returns>描画済テクスチャ</returns>
//protected Bitmap DrawPrivateFont_V( string drawstr, Color fontColor, Color edgeColor, bool bVertical )
//{
// if ( this._fontfamily == null || drawstr == null || drawstr == "" )
// {
// // nullを返すと、その後bmp→texture処理や、textureのサイズを見て__の処理で全部例外が発生することになる。
// // それは非常に面倒なので、最小限のbitmapを返してしまう。
// // まずはこの仕様で進めますが、問題有れば(上位側からエラー検出が必要であれば)例外を出したりエラー状態であるプロパティを定義するなり検討します。
// if ( drawstr != "" )
// {
// Trace.TraceWarning( "DrawPrivateFont()の入力不正。最小値のbitmapを返します。" );
// }
// _rectStrings = new Rectangle( 0, 0, 0, 0 );
// _ptOrigin = new Point( 0, 0 );
// return new Bitmap(1, 1);
// }
// //StreamWriter stream = stream = new StreamWriter("Test.txt", false);
// //try
// //{
// // stream = new StreamWriter("Test.txt", false);
// //}
// //catch (Exception ex)
// //{
// // stream.Close();
// // stream = new StreamWriter("Test.txt", false);
// //}
// string[] strName = new string[] { "焼","肉","定","食", "X", "G", "t", "e", "s", "t" };
// strName = new string[ drawstr.Length ];
// for( int i = 0; i < drawstr.Length; i++ ) strName[i] = drawstr.Substring(i, 1);
// Bitmap bmpCambus = new Bitmap( 48, ( drawstr.Length * 31 ) );
// Graphics Gcambus = Graphics.FromImage( bmpCambus );
// //キャンバス作成→1文字ずつ作成してキャンバスに描画という形がよさそうかな?
// int nStartPos = 0;
// int nNowPos = 0;
// //forループで1文字ずつbitmap作成?
// for( int i = 0; i < strName.Length; i++ )
// {
// Size strSize = System.Windows.Forms.TextRenderer.MeasureText( strName[ i ], this._font, new Size( int.MaxValue, int.MaxValue ),
// System.Windows.Forms.TextFormatFlags.NoPrefix |
// System.Windows.Forms.TextFormatFlags.NoPadding );
// //Bitmap bmpV = new Bitmap( strSize.Width + 12, ( strSize.Height + 12 ) - 6 );
// Bitmap bmpV = new Bitmap( 36, ( strSize.Height + 12 ) - 6 );
// bmpV.MakeTransparent();
// Graphics gV = Graphics.FromImage( bmpV );
// gV.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// StringFormat sFormat = new StringFormat();
// sFormat.LineAlignment = StringAlignment.Center; // 画面下部(垂直方向位置)
// sFormat.Alignment = StringAlignment.Center; // 画面中央(水平方向位置)
// //Rectangle rect = new Rectangle( 0, 0, strSize.Width + 12, ( strSize.Height + 12 ));
// Rectangle rect = new Rectangle( 0, 0, 36, ( strSize.Height + 12 ));
// // DrawPathで、ポイントサイズを使って描画するために、DPIを使って単位変換する
// // (これをしないと、単位が違うために、小さめに描画されてしまう)
// float sizeInPixels = _font.SizeInPoints * gV.DpiY / 72; // 1 inch = 72 points
// System.Drawing.Drawing2D.GraphicsPath gpV = new System.Drawing.Drawing2D.GraphicsPath();
// gpV.AddString( strName[ i ], this._fontfamily, (int) this._font.Style, sizeInPixels, rect, sFormat );
// Rectangle rect正確なサイズ = this.MeasureStringPrecisely( gV, strName[ i ], this._font, strSize, sFormat );
// // 縁取りを描画する
// Pen pV = new Pen( edgeColor, 6 );
// pV.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
// gV.DrawPath( pV, gpV );
// // 塗りつぶす
// Brush brV;
// {
// brV = new SolidBrush( fontColor );
// }
// gV.FillPath( brV, gpV );
// if ( brV != null ) brV.Dispose(); brV = null;
// if ( pV != null ) pV.Dispose(); pV = null;
// if ( gpV != null ) gpV.Dispose(); gpV = null;
// int n補正 = 0;
// //bmpV.Save( "String" + i.ToString() + ".png" );
// if( strName[ i ] == "ー" || strName[ i ] == "-" || strName[ i ] == "~")
// {
// bmpV.RotateFlip( RotateFlipType.Rotate90FlipNone );
// nNowPos = nNowPos + 20;
// n補正 = 2;
// }
// else if( strName[ i ] == "<" || strName[ i ] == ">" || strName[ i ] == "(" || strName[ i ] == ")" )
// {
// bmpV.RotateFlip( RotateFlipType.Rotate90FlipNone );
// nNowPos = nNowPos + 8;
// n補正 = 2;
// }
// else if( strName[ i ] == "_" )
// nNowPos = nNowPos + 20;
// else if( strName[ i ] == " " )
// nNowPos = nNowPos + 10;
// int n余白サイズ = strSize.Height - rect正確なサイズ.Height;
// if( i == 0 )
// {
// nStartPos = -n余白サイズ + 2;
// nNowPos = -n余白サイズ + 2;
// Gcambus.DrawImage( bmpV, ( bmpCambus.Size.Width - bmpV.Size.Width ) + n補正, nStartPos );
// //nNowPos += ( rect正確なサイズ.Height + 6 );
// }
// else
// {
// nNowPos += ( strSize.Height - n余白サイズ ) + 4;
// Gcambus.DrawImage( bmpV, ( bmpCambus.Size.Width - bmpV.Size.Width ) + n補正, nNowPos );
// }
// if ( bmpV != null ) bmpV.Dispose();
// //bmpCambus.Save( "test.png" );
// _rectStrings = new Rectangle( 0, 0, strSize.Width, strSize.Height );
// _ptOrigin = new Point( 6 * 2, 6 * 2 );
// //stream.WriteLine( "黒無しサイズ{0},余白{1},黒あり予測サイズ{2},ポ↑ジ↓{3}",rect正確なサイズ.Height, n余白サイズ, rect正確なサイズ.Height + 6, nNowPos );
// }
// //stream.Close();
// //return bmp;
// return bmpCambus;
//}
//------------------------------------------------
//使用:http://dobon.net/vb/dotnet/graphics/measurestring.html
/// <summary>
/// Graphics.DrawStringで文字列を描画した時の大きさと位置を正確に計測する
/// </summary>
/// <param name="g">文字列を描画するGraphics</param>
/// <param name="text">描画する文字列</param>
/// <param name="font">描画に使用するフォント</param>
/// <param name="proposedSize">これ以上大きいことはないというサイズ。
/// できるだけ小さくすること。</param>
/// <param name="stringFormat">描画に使用するStringFormat</param>
/// <returns>文字列が描画される範囲。
/// 見つからなかった時は、Rectangle.Empty。</returns>
public Rectangle MeasureStringPrecisely(Graphics g,
string text, Font font, Size proposedSize, StringFormat stringFormat)
{
//解像度を引き継いで、Bitmapを作成する
Bitmap bmp = new Bitmap(proposedSize.Width, proposedSize.Height, g);
//BitmapのGraphicsを作成する
Graphics bmpGraphics = Graphics.FromImage(bmp);
//Graphicsのプロパティを引き継ぐ
bmpGraphics.TextRenderingHint = g.TextRenderingHint;
bmpGraphics.TextContrast = g.TextContrast;
bmpGraphics.PixelOffsetMode = g.PixelOffsetMode;
//文字列の描かれていない部分の色を取得する
Color backColor = bmp.GetPixel(0, 0);
//実際にBitmapに文字列を描画する
bmpGraphics.DrawString(text, font, Brushes.Black,
new RectangleF(0f, 0f, proposedSize.Width, proposedSize.Height),
stringFormat);
bmpGraphics.Dispose();
//文字列が描画されている範囲を計測する
Rectangle resultRect = MeasureForegroundArea(bmp, backColor);
bmp.Dispose();
return resultRect;
}
/// <summary>
/// 指定されたBitmapで、backColor以外の色が使われている範囲を計測する
/// </summary>
private Rectangle MeasureForegroundArea(Bitmap bmp, Color backColor)
{
int backColorArgb = backColor.ToArgb();
int maxWidth = bmp.Width;
int maxHeight = bmp.Height;
//左側の空白部分を計測する
int leftPosition = -1;
for (int x = 0; x < maxWidth; x++)
{
for (int y = 0; y < maxHeight; y++)
{
//違う色を見つけたときは、位置を決定する
if (bmp.GetPixel(x, y).ToArgb() != backColorArgb)
{
leftPosition = x;
break;
}
}
if (0 <= leftPosition)
{
break;
}
}
//違う色が見つからなかった時
if (leftPosition < 0)
{
return Rectangle.Empty;
}
//右側の空白部分を計測する
int rightPosition = -1;
for (int x = maxWidth - 1; leftPosition < x; x--)
{
for (int y = 0; y < maxHeight; y++)
{
if (bmp.GetPixel(x, y).ToArgb() != backColorArgb)
{
rightPosition = x;
break;
}
}
if (0 <= rightPosition)
{
break;
}
}
if (rightPosition < 0)
{
rightPosition = leftPosition;
}
//上の空白部分を計測する
int topPosition = -1;
for (int y = 0; y < maxHeight; y++)
{
for (int x = leftPosition; x <= rightPosition; x++)
{
if (bmp.GetPixel(x, y).ToArgb() != backColorArgb)
{
topPosition = y;
break;
}
}
if (0 <= topPosition)
{
break;
}
}
if (topPosition < 0)
{
return Rectangle.Empty;
}
//下の空白部分を計測する
int bottomPosition = -1;
for (int y = maxHeight - 1; topPosition < y; y--)
{
for (int x = leftPosition; x <= rightPosition; x++)
{
if (bmp.GetPixel(x, y).ToArgb() != backColorArgb)
{
bottomPosition = y;
break;
}
}
if (0 <= bottomPosition)
{
break;
}
}
if (bottomPosition < 0)
{
bottomPosition = topPosition;
}
//結果を返す
return new Rectangle(leftPosition, topPosition,
rightPosition - leftPosition, bottomPosition - topPosition);
}
private Rectangle MeasureForegroundArea(Bitmap bmp)
{
return MeasureForegroundArea(bmp, bmp.GetPixel(0, 0));
}
//------------------------------------------------
/// <summary>
/// 最後にDrawPrivateFont()した文字列の描画領域を取得します。
/// </summary>
public Rectangle RectStrings
{
get
{
return _rectStrings;
}
protected set
{
_rectStrings = value;
}
}
public Point PtOrigin
{
get
{
return _ptOrigin;
}
protected set
{
_ptOrigin = value;
}
}
#region [ IDisposable 実装 ]
//-----------------
public void Dispose()
{
if (!this.bDispose完了済み)
{
if (this._font != null)
{
this._font.Dispose();
this._font = null;
}
if (this._pfc != null)
{
this._pfc.Dispose();
this._pfc = null;
}
this.bDispose完了済み = true;
}
}
//-----------------
#endregion
#region [ private ]
//-----------------
protected bool bDispose完了済み;
protected Font _font;
private System.Drawing.Text.PrivateFontCollection _pfc;
private FontFamily _fontfamily;
private int _pt;
private Rectangle _rectStrings;
private Point _ptOrigin;
//-----------------
#endregion
}
}
| 37.212683 | 271 | 0.541436 | [
"MIT"
] | 269Seahorse/TJAP4 | TJAPlayer3/Common/CPrivateFont.cs | 44,927 | C# |
using System.Collections.Generic;
using System.Text;
using Avalonia.Lottie.Animation.Keyframe;
using Avalonia.Lottie.Value;
namespace Avalonia.Lottie.Model.Animatable
{
public abstract class BaseAnimatableValue<TV, TO> : IAnimatableValue<TV, TO>
{
internal readonly List<Keyframe<TV>> Keyframes;
/// <summary>
/// Create a default static animatable path.
/// </summary>
internal BaseAnimatableValue(TV value) : this(new List<Keyframe<TV>> { new(value) })
{
}
internal BaseAnimatableValue(List<Keyframe<TV>> keyframes)
{
Keyframes = keyframes;
}
public abstract IBaseKeyframeAnimation<TV, TO> CreateAnimation();
public override string ToString()
{
var sb = new StringBuilder();
if (Keyframes.Count > 0)
{
sb.Append("values=").Append("[" + string.Join(",", Keyframes) + "]");
}
return sb.ToString();
}
}
} | 28.361111 | 92 | 0.5857 | [
"Apache-2.0"
] | PieroCastillo/Avalonia.Lottie | Avalonia.Lottie/Model/Animatable/BaseAnimatableValue.cs | 1,023 | C# |
/* TILE WORLD CREATOR
* Copyright (c) 2015 doorfortyfour OG
*
* Create awesome tile worlds in seconds.
*
*
* Documentation: http://tileworldcreator.doofortyfour.com
* Like us on Facebook: http://www.facebook.com/doorfortyfour2013
* Web: http://www.doorfortyfour.com
* Contact: mail@doorfortyfour.com Contact us for help, bugs or
* share your awesome work you've made with TileWorldCreator
*/
using UnityEngine;
using System.Collections;
namespace TileWorld
{
public class TileWorldNeighbourCounter : MonoBehaviour
{
public static int CountCrossNeighbours(bool[,] map, int _x, int _y, int _step, bool _createFloor, bool invert)
{
TileWorldCreator.orientation = "";
int _count = 0;
for(int y = -_step; y < _step + 1; y ++)
{
for(int x = -_step; x < _step + 1; x ++)
{
int neighbour_x = _x + x;
int neighbour_y = _y + y;
//do not count middle point
if (x == 0 && y == 0)
{
}
else if ((x == -_step && y == 0) || (x == _step && y == 0) || (x == 0 && y == -_step) || (x == 0 && y == _step))
{
//off the edge of the map
if(neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= map.GetLength(0) || neighbour_y >= map.GetLength(1))
{
_count = _count + 1;
//north
if (x == 0 && y == -_step)
{
TileWorldCreator.orientation += "n";
}
//west
if (x == -_step && y == 0)
{
TileWorldCreator.orientation += "w";
}
//east
if (x == _step && y == 0)
{
TileWorldCreator.orientation += "e";
}
//south
if (x == 0 && y == _step)
{
TileWorldCreator.orientation += "s";
}
}
//build island
else if (!invert)
{
//if floor is deactive do not count floor cells
if (!_createFloor && map[neighbour_x, neighbour_y])
{
_count = _count + 1;
//set the orientation according to where a neighbour is
//and where we are looking
//north
if (x == 0 && y == -_step)
{
TileWorldCreator.orientation += "n";
}
//west
if (x == -_step && y == 0)
{
TileWorldCreator.orientation += "w";
}
//east
if (x == _step && y == 0)
{
TileWorldCreator.orientation += "e";
}
//south
if (x == 0 && y == _step)
{
TileWorldCreator.orientation += "s";
}
}
//count floor cells
if (_createFloor && !map[neighbour_x, neighbour_y])
{
_count = _count + 1;
//set the orientation according to where a neighbour is
//and where we are looking
//north
if (x == 0 && y == -_step)
{
TileWorldCreator.orientation += "n";
}
//west
if (x == -_step && y == 0)
{
TileWorldCreator.orientation += "w";
}
//east
if (x == _step && y == 0)
{
TileWorldCreator.orientation += "e";
}
//south
if (x == 0 && y == _step)
{
TileWorldCreator.orientation += "s";
}
}
}
//build dungeon
else if (invert)
{
//do not count floor if deactivated
if (!_createFloor && !map[neighbour_x, neighbour_y])
{
_count = _count + 1;
//set the orientation according to where a neighbour is
//and where we are looking
//north
if (x == 0 && y == -_step)
{
TileWorldCreator.orientation += "n";
}
//west
if (x == -_step && y == 0)
{
TileWorldCreator.orientation += "w";
}
//east
if (x == _step && y == 0)
{
TileWorldCreator.orientation += "e";
}
//south
if (x == 0 && y == _step)
{
TileWorldCreator.orientation += "s";
}
}
//count floor cells
if (_createFloor && map[neighbour_x, neighbour_y])
{
_count = _count + 1;
//set the orientation according to where a neighbour is
//and where we are looking
//north
if (x == 0 && y == -_step)
{
TileWorldCreator.orientation += "n";
}
//west
if (x == -_step && y == 0)
{
TileWorldCreator.orientation += "w";
}
//east
if (x == _step && y == 0)
{
TileWorldCreator.orientation += "e";
}
//south
if (x == 0 && y == _step)
{
TileWorldCreator.orientation += "s";
}
}
}
}
}
}
return _count;
}
public static int CountDiagonalNeighbours(bool[,] map, int _x, int _y, int _range, bool _createFloor, bool invert)
{
TileWorldCreator.orientation = "";
int _count = 0;
for(int y = -_range; y < _range + 1; y ++)
{
for(int x = -_range; x < _range + 1; x ++)
{
int neighbour_x = _x + x;
int neighbour_y = _y + y;
//do not count middle point
if (x == 0 && y == 0)
{
}
else if ((x == -_range && y == _range) || (x == _range && y == -_range) || (x == -_range && y == -_range) || (x == _range && y == _range))
{
//off the edge of the map
if(neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= map.GetLength(0) || neighbour_y >= map.GetLength(1))
{
}
else if (!invert)
{
//if floor is deactive do not count floor cells
if (!_createFloor && map[neighbour_x, neighbour_y])
{
_count ++;
//north west
if (x == -1 && y == 1)
{
TileWorldCreator.orientation += "nw";
}
//north east
if (x == 1 && y == 1)
{
TileWorldCreator.orientation += "ne";
}
//south west
if (x == -1 && y == -1)
{
TileWorldCreator.orientation += "sw";
}
//south east
if (x == 1 && y == -1)
{
TileWorldCreator.orientation += "se";
}
}
//count floor cells
if (_createFloor && !map[neighbour_x, neighbour_y])
{
_count ++;
//north west
if (x == -1 && y == 1)
{
TileWorldCreator.orientation += "nw";
}
//north east
if (x == 1 && y == 1)
{
TileWorldCreator.orientation += "ne";
}
//south west
if (x == -1 && y == -1)
{
TileWorldCreator.orientation += "sw";
}
//south east
if (x == 1 && y == -1)
{
TileWorldCreator.orientation += "se";
}
}
}
else if (invert)
{
////do not count floor if deactivated
if (!_createFloor && !map[neighbour_x, neighbour_y])
{
_count ++;
//north west
if (x == -1 && y == 1)
{
TileWorldCreator.orientation += "nw";
}
//north east
if (x == 1 && y == 1)
{
TileWorldCreator.orientation += "ne";
}
//south west
if (x == -1 && y == -1)
{
TileWorldCreator.orientation += "sw";
}
//south east
if (x == 1 && y == -1)
{
TileWorldCreator.orientation += "se";
}
}
//count floor cells
if (_createFloor && map[neighbour_x, neighbour_y])
{
_count ++;
//north west
if (x == -1 && y == 1)
{
TileWorldCreator.orientation += "nw";
}
//north east
if (x == 1 && y == 1)
{
TileWorldCreator.orientation += "ne";
}
//south west
if (x == -1 && y == -1)
{
TileWorldCreator.orientation += "sw";
}
//south east
if (x == 1 && y == -1)
{
TileWorldCreator.orientation += "se";
}
}
}
}
}
}
return _count;
}
public static int CountAllNeighbours(bool[,] map, int _x, int _y, int _range, bool _invert)
{
int _count = 0;
for(int y = -_range; y < _range + 1; y ++)
{
for(int x = -_range; x < _range + 1; x ++)
{
int neighbour_x = _x + x;
int neighbour_y = _y + y;
//looking at middle point do nothing
if(y == 0 && x == 0)
{
}
//off the edge of the map
else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= map.GetLength(0) || neighbour_y >= map.GetLength(1))
{
_count = _count + 1;
}
//normal check of the neighbour
else if (map[neighbour_x, neighbour_y] == _invert)
{
_count = _count + 1;
}
}
}
return _count;
}
//Count inner terrain blocks
//--------------------------
//count inner terrain blocks according to
//range / distance from the edge of the world
//does not differ much from count all neighbours
//only have to check if invert is on or off
public static int CountInnerTerrainBlocks(bool [,] map, int _x, int _y, int _range, bool _invert)
{
int _count = 0;
TileWorldCreator.orientation = "";
for(int y = -_range; y < _range + 1; y ++)
{
for(int x = -_range; x < _range + 1; x ++)
{
int neighbour_x = _x + x;
int neighbour_y = _y + y;
//do nothing when checking ourselves
if(y == 0 && x == 0)
{
}
//In case the index we're looking at it is off the edge of the map
else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_x >= map.GetLength(0) || neighbour_y >= map.GetLength(1))
{
_count ++;
}
else if (!_invert && !map[neighbour_x, neighbour_y])
{
_count ++;
}
else if (_invert && map[neighbour_x, neighbour_y])
{
_count ++;
}
}
}
return _count;
}
}
}
| 23.060538 | 143 | 0.452698 | [
"MIT"
] | 142333lzg/jynew | jyx2/Assets/Resources/TileWorldCreator/_Core/Utility/TileWorldNeighbourCounter.cs | 10,287 | C# |
using Raider.AspNetCore.Middleware.Authentication.RequestAuth.Events;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
namespace Raider.AspNetCore.Middleware.Authentication.RequestAuth
{
public class RequestAuthenticationOptions : AuthenticationSchemeOptions
{
public PathString? AccessDeniedPath { get; set; }
public PathString? UnauthorizedPath { get; set; }
public string? ReturnUrlParameter { get; set; }
public new RequestAuthenticationEvents Events
{
get => (RequestAuthenticationEvents)base.Events;
set => base.Events = value;
}
public RequestAuthenticationOptions()
{
}
}
}
| 26.666667 | 72 | 0.78125 | [
"Apache-2.0"
] | raider-net/Raider | src/Raider.AspNetCore/Middleware/Authentication/RequestAuth/RequestAuthenticationOptions.cs | 642 | C# |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections;
namespace MbUnit.Core.Reports.Serialization
{
[XmlRoot("property")]
[Serializable]
public sealed class ReportProperty
{
private string name = null;
private string value = null;
public ReportProperty()
{}
public ReportProperty(DictionaryEntry de)
{
this.name = String.Format("{0}", de.Key);
try
{
if (de.Value == null)
this.value = "null";
else
this.value = String.Format("{0}", de.Value);
}
catch (Exception ex)
{
this.value = String.Format("Error while getting value ({0})",ex.Message);
}
}
public ReportProperty(Object instance, PropertyInfo property)
{
this.name = property.Name;
try
{
object val = property.GetValue(instance, null);
if (val == null)
this.value = "null";
else
this.value = String.Format("{0}", val);
}
catch (Exception ex)
{
this.value = String.Format("Error while getting property value ({0})",ex.Message);
}
}
[XmlAttribute("name")]
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
[XmlAttribute("value")]
public string Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
public override string ToString()
{
return string.Format("{0} = {1}", this.name, this.value);
}
}
}
| 28.862385 | 99 | 0.518436 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v2 | src/mbunit/MbUnit.Framework/Core/Reports/Serialization/ReportProperty.cs | 3,148 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
namespace Azure.ResourceManager.AppService.Models
{
internal static partial class HostingEnvironmentStatusExtensions
{
public static string ToSerialString(this HostingEnvironmentStatus value) => value switch
{
HostingEnvironmentStatus.Preparing => "Preparing",
HostingEnvironmentStatus.Ready => "Ready",
HostingEnvironmentStatus.Scaling => "Scaling",
HostingEnvironmentStatus.Deleting => "Deleting",
_ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown HostingEnvironmentStatus value.")
};
public static HostingEnvironmentStatus ToHostingEnvironmentStatus(this string value)
{
if (string.Equals(value, "Preparing", StringComparison.InvariantCultureIgnoreCase)) return HostingEnvironmentStatus.Preparing;
if (string.Equals(value, "Ready", StringComparison.InvariantCultureIgnoreCase)) return HostingEnvironmentStatus.Ready;
if (string.Equals(value, "Scaling", StringComparison.InvariantCultureIgnoreCase)) return HostingEnvironmentStatus.Scaling;
if (string.Equals(value, "Deleting", StringComparison.InvariantCultureIgnoreCase)) return HostingEnvironmentStatus.Deleting;
throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown HostingEnvironmentStatus value.");
}
}
}
| 46.545455 | 138 | 0.729818 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/Models/HostingEnvironmentStatus.Serialization.cs | 1,536 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity.Metadata;
using Xunit;
namespace Microsoft.Data.Entity.SqlServer.Tests
{
public class SqlServerDatabaseBuilderTest
{
[Fact]
public void Build_creates_sequence_specified_on_property()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0")
.IncrementBy(3)
.Start(1001)
.Min(1000)
.Max(2000)
.Type<int>();
b.Sequence("S1")
.IncrementBy(7)
.Start(7001)
.Min(7000)
.Max(9000)
.Type<short>();
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0");
b.Property<short>("P").ForSqlServer().UseSequence("S1");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("S0", sequence0.Name);
Assert.Equal(typeof(int), sequence0.Type);
Assert.Equal(1001, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("S1", sequence1.Name);
Assert.Equal(typeof(short), sequence1.Type);
Assert.Equal(7001, sequence1.StartWith);
Assert.Equal(7, sequence1.IncrementBy);
}
[Fact]
public void Build_creates_sequence_with_defaults_specified_on_property()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence();
b.Key("Id");
b.ForSqlServer().Table("T", "dbo");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("EntityFrameworkDefaultSequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Sequence_specified_on_property_is_shared_if_same_name_used()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("MySequence");
b.Property<short>("P").ForSqlServer().UseSequence("MySequence");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Sequence_specified_on_property_is_shared_if_matches_previous_definition()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.Sequence("MySequence").IncrementBy(7); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("MySequence");
b.Property<short>("P").ForSqlServer().UseSequence("MySequence");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(7, sequence.IncrementBy);
}
[Fact]
public void Sequence_with_defaults_specified_on_property_is_shared()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence();
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
b.ForSqlServer().Table("T", "dbo");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("EntityFrameworkDefaultSequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Build_creates_sequence_defined_on_model()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.ForSqlServer(b =>
{
b.Sequence("MySequence").IncrementBy(7);
b.UseSequence("MySequence");
});
modelBuilder.Entity("A", b =>
{
b.Property<int>("Id").GenerateValueOnAdd();
b.Key("Id");
});
modelBuilder.Entity("B", b =>
{
b.Property<short>("Id").GenerateValueOnAdd();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(7, sequence.IncrementBy);
}
[Fact]
public void Build_creates_sequence_only_named_on_model()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.ForSqlServer().UseSequence("MySequence");
modelBuilder.Entity("A", b =>
{
b.Property<int>("Id").GenerateValueOnAdd();
b.Key("Id");
});
modelBuilder.Entity("B", b =>
{
b.Property<short>("Id").GenerateValueOnAdd();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Build_creates_sequence_defined_on_model_with_defaults()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.ForSqlServer().UseSequence();
modelBuilder.Entity("A", b =>
{
b.Property<int>("Id").GenerateValueOnAdd();
b.Key("Id");
b.ForSqlServer().Table("T0", "dbo");
});
modelBuilder.Entity("B", b =>
{
b.Property<short>("Id").GenerateValueOnAdd();
b.Key("Id");
b.ForSqlServer().Table("T1", "dbo");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("EntityFrameworkDefaultSequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Can_use_configured_default_and_configured_property_specific_sequence()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0").IncrementBy(3);
b.Sequence("S1").IncrementBy(7);
b.UseSequence("S1");
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(7, sequence1.IncrementBy);
}
[Fact]
public void Can_use_named_default_and_configured_property_specific_sequence()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0").IncrementBy(3);
b.UseSequence("S1");
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
[Fact]
public void Can_use_named_default_and_named_property_specific_sequence()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.UseSequence("S1"); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
[Fact]
public void Can_use_model_default_and_named_property_specific_sequence()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.UseSequence(); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("EntityFrameworkDefaultSequence", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
[Fact]
public void Build_creates_sequence_specified_on_property_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0", "dbOh")
.IncrementBy(3)
.Start(1001)
.Min(1000)
.Max(2000)
.Type<int>();
b.Sequence("S1", "dbOh")
.IncrementBy(7)
.Start(7001)
.Min(7000)
.Max(9000)
.Type<short>();
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence("S1", "dbOh");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("dbOh.S0", sequence0.Name);
Assert.Equal(typeof(int), sequence0.Type);
Assert.Equal(1001, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("dbOh.S1", sequence1.Name);
Assert.Equal(typeof(short), sequence1.Type);
Assert.Equal(7001, sequence1.StartWith);
Assert.Equal(7, sequence1.IncrementBy);
}
[Fact]
public void Sequence_specified_on_property_is_shared_if_same_name_used_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("MySequence", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence("MySequence", "dbOh");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("dbOh.MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Sequence_specified_on_property_is_shared_if_matches_previous_definition_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.Sequence("MySequence", "dbOh").IncrementBy(7); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("MySequence", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence("MySequence", "dbOh");
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("dbOh.MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(7, sequence.IncrementBy);
}
[Fact]
public void Build_creates_sequence_defined_on_model_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.ForSqlServer(b =>
{
b.Sequence("MySequence", "dbOh").IncrementBy(7);
b.UseSequence("MySequence", "dbOh");
});
modelBuilder.Entity("A", b =>
{
b.Property<int>("Id").GenerateValueOnAdd();
b.Key("Id");
});
modelBuilder.Entity("B", b =>
{
b.Property<short>("Id").GenerateValueOnAdd();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("dbOh.MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(7, sequence.IncrementBy);
}
[Fact]
public void Build_creates_sequence_only_named_on_model_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder.ForSqlServer().UseSequence("MySequence", "dbOh");
modelBuilder.Entity("A", b =>
{
b.Property<int>("Id").GenerateValueOnAdd();
b.Key("Id");
});
modelBuilder.Entity("B", b =>
{
b.Property<short>("Id").GenerateValueOnAdd();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(1, database.Sequences.Count);
var sequence = database.Sequences[0];
Assert.Equal("dbOh.MySequence", sequence.Name);
Assert.Equal(typeof(long), sequence.Type);
Assert.Equal(1, sequence.StartWith);
Assert.Equal(10, sequence.IncrementBy);
}
[Fact]
public void Can_use_configured_default_and_configured_property_specific_sequence_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0", "dbOh").IncrementBy(3);
b.Sequence("S1", "dbToo").IncrementBy(7);
b.UseSequence("S1", "dbToo");
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("dbOh.S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("dbToo.S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(7, sequence1.IncrementBy);
}
[Fact]
public void Can_use_named_default_and_configured_property_specific_sequence_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b =>
{
b.Sequence("S0", "dbOh").IncrementBy(3);
b.UseSequence("S1", "dbToo");
})
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("dbOh.S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(3, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("dbToo.S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
[Fact]
public void Can_use_named_default_and_named_property_specific_sequence_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.UseSequence("S1", "dbToo"); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("dbOh.S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("dbToo.S1", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
[Fact]
public void Can_use_model_default_and_named_property_specific_sequence_with_schema()
{
var modelBuilder = new BasicModelBuilder();
modelBuilder
.ForSqlServer(
b => { b.UseSequence(); })
.Entity("A",
b =>
{
b.Property<int>("Id").ForSqlServer().UseSequence("S0", "dbOh");
b.Property<short>("P").ForSqlServer().UseSequence();
b.Key("Id");
});
var databaseBuilder = new SqlServerDatabaseBuilder(new SqlServerTypeMapper());
var database = databaseBuilder.GetDatabase(modelBuilder.Model);
Assert.Equal(2, database.Sequences.Count);
var sequence0 = database.Sequences[0];
Assert.Equal("dbOh.S0", sequence0.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence0.IncrementBy);
var sequence1 = database.Sequences[1];
Assert.Equal("EntityFrameworkDefaultSequence", sequence1.Name);
Assert.Equal(typeof(long), sequence0.Type);
Assert.Equal(1, sequence0.StartWith);
Assert.Equal(10, sequence1.IncrementBy);
}
}
}
| 37.49866 | 111 | 0.507078 | [
"Apache-2.0"
] | matteo-mosca-easydom/EntityFramework | test/EntityFramework.SqlServer.Tests/SqlServerDatabaseBuilderTest.cs | 27,976 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
public class RenameTrackingTaggerProviderTests
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnCreation()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInBlankFile()
{
var code = @"$$";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtEnd()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtBeginning()
{
var code = @"
class $$C
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("AB");
await state.AssertTag("C", "ABC");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingInMiddle()
{
var code = @"
class AB$$CD
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("ZZ");
await state.AssertTag("ABCD", "ABZZCD");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromEnd()
{
var code = @"
class ABC$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AB");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromBeginning()
{
var code = @"
class $$ABC
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Delete();
await state.AssertTag("ABC", "BC");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromMiddle()
{
var code = @"
class AB$$C
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AC");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnClassKeyword()
{
var code = @"
class$$ ABCD
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAtMethodArgument()
{
var code = @"
class ABCD
{
void Foo(int x)
{
int abc = 3;
Foo($$
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("a");
await state.AssertNoTag();
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingSessionContinuesAfterViewingTag()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cats");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInString()
{
var code = @"
class C
{
void Foo()
{
string s = ""abc$$""
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesAtSignAsCSharpEscape()
{
var code = @"
class $$C
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("@");
await state.AssertTag("C", "@C");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesSquareBracketsAsVisualBasicEscape()
{
var code = @"
Class $$C
End Class";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertTag("C", "[C]");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnSquareBracketsInCSharp()
{
var code = @"
class $$C
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesUnicode()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
await state.AssertTag("C", "C\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughKeyword()
{
var code = @"
class i$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("n");
await state.AssertNoTag();
state.EditorOperations.InsertText("t");
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("i", "ints");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughIllegalStartCharacter()
{
var code = @"
class $$abc
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("9");
await state.AssertNoTag();
state.MoveCaret(-1);
state.EditorOperations.InsertText("t");
await state.AssertTag("abc", "t9abc");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnBothSidesOfIdentifier()
{
var code = @"
class $$Def
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("Abc");
await state.AssertTag("Def", "AbcDef");
state.MoveCaret(3);
state.EditorOperations.InsertText("Ghi");
await state.AssertTag("Def", "AbcDefGhi");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughSameIdentifier()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyString()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyStringWithCaretMove()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
state.MoveCaret(-4);
state.MoveCaret(4);
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotThroughEmptyStringResumeOnDifferentSpace()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
// Move to previous space
state.MoveCaret(-1);
state.EditorOperations.InsertText("D");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierSuffix()
{
var code = @"
class Identifi[|er|]$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "cation");
await state.AssertTag("Identifier", "Identification");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierPrefix()
{
var code = @"
class $$[|Ident|]ifier
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Complex");
await state.AssertTag("Identifier", "Complexifier");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierCompletely()
{
var code = @"
class [|Cat|]$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Dog");
await state.AssertTag("Cat", "Dog");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAfterInvoke()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingInvokeAndChangeBackToOriginal()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
state.EditorOperations.Backspace();
await state.AssertTag("Cats", "Cat");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoOnceAndStartNewSession()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catxyz");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceAndContinueSession()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Catabc");
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catabcxyz");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingRedoAlwaysClearsState()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo();
await state.AssertNoTag();
state.Redo();
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceRedoTwiceUndoStillWorks()
{
var code = @"
class Cat$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo(2);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
// Resume rename tracking session
state.Undo();
await state.AssertTag("Cat", "Cats");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$);
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsNamedArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$: x);
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_Namespace()
{
var code = @"
namespace NS
{
class C
{
static void M()
{
NS$$.C.M();
}
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("A");
await state.AssertTag("NS", "NSA");
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotifiesThirdPartiesOfRenameOperation()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
state.AssertNoNotificationMessage();
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHonorsThirdPartyRequestsForCancellationBeforeRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp, onBeforeGlobalSymbolRenamedReturnValue: false))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
// Make sure the rename didn't proceed
Assert.Equal(0, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
await state.AssertNoTag();
var expectedCode = @"
class Cat
{
public Cat()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
state.AssertNotificationMessage();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingAlertsAboutThirdPartyRequestsForCancellationAfterRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp, onAfterGlobalSymbolRenamedReturnValue: false))
{
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
state.AssertNotificationMessage();
// Make sure the rename completed
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
[WpfFact, WorkItem(530469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530469")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenStartedFromTextualWordInTrivia()
{
var code = @"
Module Program
Sub Main()
Dim [x$$ = 1
End Sub
End Module";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
}
[WpfFact, WorkItem(530495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530495")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenCaseCorrectingReference()
{
var code = @"
Module Program
Sub Main()
$$main()
End Sub
End Module";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.Delete();
await state.AssertTag("main", "ain");
state.EditorOperations.InsertText("M");
await state.AssertNoTag();
}
}
[WpfFact, WorkItem(599508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/599508")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenNewIdentifierReferenceBinds()
{
var code = @"
Module Program
Sub Main()
$$[|main|]()
End Sub
Sub Foo()
End Sub
End Module";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Fo");
await state.AssertTag("main", "Fo");
state.EditorOperations.InsertText("o");
await state.AssertNoTag();
}
}
[WpfFact, WorkItem(530400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530400")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembers()
{
var code = @"
Enum E
$$
End Enum";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
}
[WpfFact, WorkItem(1028072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028072")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public void RenameTrackingDoesNotThrowAggregateException()
{
var waitForResult = false;
Task<RenameTrackingTaggerProvider.TriggerIdentifierKind> notRenamable = Task.FromResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.NotRenamable);
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(notRenamable, waitForResult, CancellationToken.None));
var source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source.TrySetResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.RenamableReference);
Assert.True(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
source.TrySetCanceled();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.Throws<OperationCanceledException>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, new CancellationToken(canceled: true)));
source.TrySetException(new Exception());
Assert.Throws<AggregateException>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
}
[WpfFact, WorkItem(1063943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063943")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotFromReferenceWithWrongNumberOfArguments()
{
var code = @"
class C
{
void M(int x)
{
M$$();
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("eow");
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task CancelRenameTracking()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.SendEscape();
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembersEvenAfterCancellation()
{
var code = @"
Enum E
$$
End Enum";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
state.SendEscape();
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
}
}
[WpfFact]
[WorkItem(540, "https://github.com/dotnet/roslyn/issues/540")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDoesNotProvideDiagnosticAfterCancellation()
{
var code = @"
class C$$
{
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
state.SendEscape();
await state.AssertNoTag();
Assert.Empty(await state.GetDocumentDiagnosticsAsync());
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodGroupReference()
{
var code = @"
class C
{
void M()
{
nameof(M$$).ToString();
}
void M(int x)
{
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
void Mat(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_NoOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_WithOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.TextBuffer.CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromReferenceToMetadata_NoTag()
{
var code = @"
class C
{
void M()
{
var x = nameof(ToString$$);
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.InsertText("z");
await state.AssertNoTag();
}
}
[WpfFact]
[WorkItem(762964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762964")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_NoTagWhenFirstEditChangesReferenceToAnotherSymbol()
{
var code = @"
class C
{
void M()
{
int abc = 7;
int ab = 8;
int z = abc$$;
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToVarInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("va");
await state.AssertTag("C", "va");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
state.EditorOperations.InsertText("r");
await state.AssertNoTag();
Assert.Empty(await state.GetDocumentDiagnosticsAsync());
state.EditorOperations.InsertText("p");
await state.AssertTag("C", "varp");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
}
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameFromVarInCSharp()
{
var code = @"
class C
{
void M()
{
var$$ c = new C();
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Empty(await state.GetDocumentDiagnosticsAsync());
}
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CanRenameToVarInVisualBasic()
{
var code = @"
Class C
Sub M()
Dim x as C$$
End Sub
End Class";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.VisualBasic))
{
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("var");
await state.AssertTag("C", "var");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
}
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToDynamicInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using (var state = await RenameTrackingTestState.CreateAsync(code, LanguageNames.CSharp))
{
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("dynami");
await state.AssertTag("C", "dynami");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
Assert.Empty(await state.GetDocumentDiagnosticsAsync());
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "dynamics");
Assert.NotEmpty(await state.GetDocumentDiagnosticsAsync());
}
}
}
}
| 32.041701 | 308 | 0.57585 | [
"Apache-2.0"
] | HaloFour/roslyn | src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs | 38,420 | 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("lab_just_do_it_dotnetframwork_api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("lab_just_do_it_dotnetframwork_api")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("045c9260-bc09-4d6b-b198-a186dba17505")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.111111 | 84 | 0.758523 | [
"MIT"
] | TheEletricboy/2019-09-C-sharp-Labs | Labs/lab_just_do_it_dotnetframwork_api/Properties/AssemblyInfo.cs | 1,411 | C# |
using System;
namespace Core.Model.Services.Navigation
{
public class FavoritesService
{
public FavoritesService()
{
}
}
}
| 14.545455 | 40 | 0.6 | [
"Apache-2.0"
] | QotoQot/Octospace | Core/Model/Services/Navigation/FavoritesService.cs | 162 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoverCraftPlayerController : MonoBehaviour {
HoverCraft hoverCraft;
void Awake () {
hoverCraft = GetComponent<HoverCraft> ();
}
void FixedUpdate () {
float xAxis = Input.GetAxis ("Horizontal");
float yAxis = Input.GetAxis ("Vertical");
hoverCraft.throtal = yAxis;
hoverCraft.torque = GameMath.Map (-xAxis,-1f, 1f, 0f, 1f);
}
}
| 22.05 | 61 | 0.718821 | [
"MIT"
] | Basher207/NeuralNet | Neural stuff/NeuralNet/Assets/Scripts/Specific/HoverCraft/HoverCraftPlayerController.cs | 443 | C# |
using System.Collections;
using System.Collections.Generic;
using GraphProcessor;
using UnityEngine;
public class SIGMiscellaneousNode : SIGNode
{
public const string MISCELLANEOUS = "Miscellaneous";
}
[System.Serializable, NodeMenuItem(MISCELLANEOUS + "/Texture Preview")]
public class TexturePreviewNode : SIGMiscellaneousNode
{
[SerializeField, ShowAsDrawer, Input("Texture")]
public Texture texture;
[Output("Pass Through")] public Texture passThrough;
protected override void Process(SIGProcessingContext context)
{
passThrough = texture;
}
}
| 24.5 | 71 | 0.756803 | [
"MIT"
] | FreshlyBrewedCode/SIG | Packages/de.frebreco.SIG.Core/Runtime/Nodes/Miscellaneous/TexturePreviewNode.cs | 588 | C# |
using System;
namespace CommunityCenter.Models.RBAC
{
public class fn_rbac_HS_PORT
{
public int ResourceID { get; set; }
public int GroupID { get; set; }
public int RevisionID { get; set; }
public int? AgentID { get; set; }
public DateTime TimeStamp { get; set; }
public int? Alias0 { get; set; }
public string Caption0 { get; set; }
public string Description0 { get; set; }
public string EndingAddress0 { get; set; }
public DateTime? InstallDate0 { get; set; }
public string Name0 { get; set; }
public string StartingAddress0 { get; set; }
public string Status0 { get; set; }
}
}
| 19.805556 | 52 | 0.584853 | [
"MIT"
] | Eph-It/MEM.CommunityCenter | CommunityCenter/CommunityCenter.Models/RBAC/fn_rbac_HS_PORT.cs | 715 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.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.RDS.Model
{
/// <summary>
/// Container for the parameters to the CreateDBClusterParameterGroup operation.
/// Creates a new DB cluster parameter group.
///
///
/// <para>
/// Parameters in a DB cluster parameter group apply to all of the instances in a DB cluster.
/// </para>
///
/// <para>
/// A DB cluster parameter group is initially created with the default parameters for
/// the database engine used by instances in the DB cluster. To provide custom values
/// for any of the parameters, you must modify the group after creating it using <code>ModifyDBClusterParameterGroup</code>.
/// Once you've created a DB cluster parameter group, you need to associate it with your
/// DB cluster using <code>ModifyDBCluster</code>. When you associate a new DB cluster
/// parameter group with a running DB cluster, you need to reboot the DB instances in
/// the DB cluster without failover for the new DB cluster parameter group and associated
/// settings to take effect.
/// </para>
/// <important>
/// <para>
/// After you create a DB cluster parameter group, you should wait at least 5 minutes
/// before creating your first DB cluster that uses that DB cluster parameter group as
/// the default parameter group. This allows Amazon RDS to fully complete the create action
/// before the DB cluster parameter group is used as the default for a new DB cluster.
/// This is especially important for parameters that are critical when creating the default
/// database for a DB cluster, such as the character set for the default database defined
/// by the <code>character_set_database</code> parameter. You can use the <i>Parameter
/// Groups</i> option of the <a href="https://console.aws.amazon.com/rds/">Amazon RDS
/// console</a> or the <code>DescribeDBClusterParameters</code> action to verify that
/// your DB cluster parameter group has been created or modified.
/// </para>
/// </important>
/// <para>
/// For more information on Amazon Aurora, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html">
/// What Is Amazon Aurora?</a> in the <i>Amazon Aurora User Guide.</i>
/// </para>
/// <note>
/// <para>
/// This action only applies to Aurora DB clusters.
/// </para>
/// </note>
/// </summary>
public partial class CreateDBClusterParameterGroupRequest : AmazonRDSRequest
{
private string _dbClusterParameterGroupName;
private string _dbParameterGroupFamily;
private string _description;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property DBClusterParameterGroupName.
/// <para>
/// The name of the DB cluster parameter group.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must match the name of an existing DB cluster parameter group.
/// </para>
/// </li> </ul> <note>
/// <para>
/// This value is stored as a lowercase string.
/// </para>
/// </note>
/// </summary>
[AWSProperty(Required=true)]
public string DBClusterParameterGroupName
{
get { return this._dbClusterParameterGroupName; }
set { this._dbClusterParameterGroupName = value; }
}
// Check to see if DBClusterParameterGroupName property is set
internal bool IsSetDBClusterParameterGroupName()
{
return this._dbClusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property DBParameterGroupFamily.
/// <para>
/// The DB cluster parameter group family name. A DB cluster parameter group can be associated
/// with one and only one DB cluster parameter group family, and can be applied only to
/// a DB cluster running a database engine and engine version compatible with that DB
/// cluster parameter group family.
/// </para>
///
/// <para>
/// <b>Aurora MySQL</b>
/// </para>
///
/// <para>
/// Example: <code>aurora5.6</code>, <code>aurora-mysql5.7</code>
/// </para>
///
/// <para>
/// <b>Aurora PostgreSQL</b>
/// </para>
///
/// <para>
/// Example: <code>aurora-postgresql9.6</code>
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string DBParameterGroupFamily
{
get { return this._dbParameterGroupFamily; }
set { this._dbParameterGroupFamily = value; }
}
// Check to see if DBParameterGroupFamily property is set
internal bool IsSetDBParameterGroupFamily()
{
return this._dbParameterGroupFamily != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description for the DB cluster parameter group.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Tags to assign to the DB cluster parameter group.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 37.952381 | 148 | 0.591524 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/CreateDBClusterParameterGroupRequest.cs | 7,173 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace PokemonROMEditor.Models
{
public class Map
{
public Map(string name, TileSet ts)
{
MapName = name;
TileSetID = ts;
}
public string MapName { get; }
public int Height { get; set; }
public int Width { get; set; }
public int[] MapBlockValues { get; set; }
private TileSet tileSetID;
public TileSet TileSetID
{
get { return tileSetID; }
set
{
tileSetID = value;
OnTileSetChanged();
}
}
public ObservableCollection<MapObject> MapObjects { get; set; }
public int Connections { get; set; } //this is temporary until we start working with the connection data.
public int Signs { get; set; }
public ObservableCollection<MapWarp> WarpsLeaving { get; set; }
public ObservableCollection<MapWarp> WarpsArriving { get; set; }
public event EventHandler TileSetChanged;
protected virtual void OnTileSetChanged()
{
TileSetChanged?.Invoke(this, new EventArgs());
}
}
public class BlockSet
{
public string SourceFile { get; set; }
public int[] BlockDefinitions { get; set; }
public ObservableCollection<Bitmap> Tiles { get; set; }
}
public class MapTile
{
public MapTile(int id, BitmapSource image)
{
TileID = id;
TileImage = image;
}
public int TileID { get; set; }
public BitmapSource TileImage { get; set; }
}
public class MapObject
{
public event EventHandler SpriteChanged;
public MapObject()
{
// Setting up some default values. Not all data will be used for every object
PokemonObj = new EnemyPokemon();
PokemonObj.PokedexID = 1;
PokemonObj.Level = 1;
Item = ItemType.ANTIDOTE;
TrainerGroupNum = 0;
TrainerNum = 1;
}
private int spriteID;
public int SpriteID
{
get
{
return spriteID;
}
set
{
spriteID = value;
OnSpriteChanged();
}
}
public MapObjectType ObjectType { get; set; }
private int yPosition;
public int YPosition
{
get { return yPosition; }
set
{
yPosition = value;
OnSpriteChanged();
}
}
private int xPosition;
public int XPosition
{
get { return xPosition; }
set
{
xPosition = value;
OnSpriteChanged();
}
}
public MapObjectMovementType Movement { get; set; }
public MapObjectFacing Facing { get; set; }
public ItemType Item { get; set; }
public EnemyPokemon PokemonObj { get; set; }
public int TrainerGroupNum { get; set; }
public int TrainerNum { get; set; }
protected virtual void OnSpriteChanged()
{
SpriteChanged?.Invoke(this, new EventArgs());
}
}
public class MapWarp
{
public event EventHandler PositionChanged;
private int yPosition;
public int YPosition
{
get { return yPosition; }
set { yPosition = value; OnPositionChanged(); }
}
private int xPosition;
public int XPosition
{
get { return xPosition; }
set { xPosition = value; OnPositionChanged(); }
}
public int DestinationWarpID { get; set; }
public int MapID { get; set; }
protected virtual void OnPositionChanged()
{
PositionChanged?.Invoke(this, new EventArgs());
}
}
public class MapObjectSprite
{
public string SpriteName { get; set; }
public string FileName { get; set; }
public Bitmap SpriteBitmap { get; set; }
}
}
| 26.391566 | 113 | 0.537777 | [
"MIT"
] | JoaoMSerra/PokemonROMEditor | src/PokemonROMEditor/Models/Map.cs | 4,383 | 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("Akka.Transport.DotNetty")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Akka.Transport.DotNetty")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d18da104-7e74-4af6-8ef2-6dc0e5cdf878")]
// 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.351351 | 84 | 0.7463 | [
"Apache-2.0"
] | Horusiath/Akka.Transport | src/Akka.Transport.DotNetty/Properties/AssemblyInfo.cs | 1,422 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TemplateTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TemplateTest")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("FDE574E1-3DDE-46BC-9AA8-A4130100D0CA")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.722222 | 84 | 0.741532 | [
"MIT"
] | VladShyrokyi/template-message-sdk | TemplateTest/Properties/AssemblyInfo.cs | 1,361 | C# |
namespace Org.BouncyCastle.Crypto.Tls
{
/// <summary>
/// RFC 5246 7.2
/// </summary>
public abstract class AlertDescription
{
/**
* This message notifies the recipient that the sender will not send any more messages on this
* connection. Note that as of TLS 1.1, failure to properly close a connection no longer
* requires that a session not be resumed. This is a change from TLS 1.0 ("The session becomes
* unresumable if any connection is terminated without proper close_notify messages with level
* equal to warning.") to conform with widespread implementation practice.
*/
public const byte close_notify = 0;
/**
* An inappropriate message was received. This alert is always fatal and should never be
* observed in communication between proper implementations.
*/
public const byte unexpected_message = 10;
/**
* This alert is returned if a record is received with an incorrect MAC. This alert also MUST be
* returned if an alert is sent because a TLSCiphertext decrypted in an invalid way: either it
* wasn't an even multiple of the block length, or its padding values, when checked, weren't
* correct. This message is always fatal and should never be observed in communication between
* proper implementations (except when messages were corrupted in the network).
*/
public const byte bad_record_mac = 20;
/**
* This alert was used in some earlier versions of TLS, and may have permitted certain attacks
* against the CBC mode [CBCATT]. It MUST NOT be sent by compliant implementations.
*/
public const byte decryption_failed = 21;
/**
* A TLSCiphertext record was received that had a length more than 2^14+2048 bytes, or a record
* decrypted to a TLSCompressed record with more than 2^14+1024 bytes. This message is always
* fatal and should never be observed in communication between proper implementations (except
* when messages were corrupted in the network).
*/
public const byte record_overflow = 22;
/**
* The decompression function received improper input (e.g., data that would expand to excessive
* length). This message is always fatal and should never be observed in communication between
* proper implementations.
*/
public const byte decompression_failure = 30;
/**
* Reception of a handshake_failure alert message indicates that the sender was unable to
* negotiate an acceptable set of security parameters given the options available. This is a
* fatal error.
*/
public const byte handshake_failure = 40;
/**
* This alert was used in SSLv3 but not any version of TLS. It MUST NOT be sent by compliant
* implementations.
*/
public const byte no_certificate = 41;
/**
* A certificate was corrupt, contained signatures that did not verify correctly, etc.
*/
public const byte bad_certificate = 42;
/**
* A certificate was of an unsupported type.
*/
public const byte unsupported_certificate = 43;
/**
* A certificate was revoked by its signer.
*/
public const byte certificate_revoked = 44;
/**
* A certificate has expired or is not currently valid.
*/
public const byte certificate_expired = 45;
/**
* Some other (unspecified) issue arose in processing the certificate, rendering it
* unacceptable.
*/
public const byte certificate_unknown = 46;
/**
* A field in the handshake was out of range or inconsistent with other fields. This message is
* always fatal.
*/
public const byte illegal_parameter = 47;
/**
* A valid certificate chain or partial chain was received, but the certificate was not accepted
* because the CA certificate could not be located or couldn't be matched with a known, trusted
* CA. This message is always fatal.
*/
public const byte unknown_ca = 48;
/**
* A valid certificate was received, but when access control was applied, the sender decided not
* to proceed with negotiation. This message is always fatal.
*/
public const byte access_denied = 49;
/**
* A message could not be decoded because some field was out of the specified range or the
* length of the message was incorrect. This message is always fatal and should never be
* observed in communication between proper implementations (except when messages were corrupted
* in the network).
*/
public const byte decode_error = 50;
/**
* A handshake cryptographic operation failed, including being unable to correctly verify a
* signature or validate a Finished message. This message is always fatal.
*/
public const byte decrypt_error = 51;
/**
* This alert was used in some earlier versions of TLS. It MUST NOT be sent by compliant
* implementations.
*/
public const byte export_restriction = 60;
/**
* The protocol version the client has attempted to negotiate is recognized but not supported.
* (For example, old protocol versions might be avoided for security reasons.) This message is
* always fatal.
*/
public const byte protocol_version = 70;
/**
* Returned instead of handshake_failure when a negotiation has failed specifically because the
* server requires ciphers more secure than those supported by the client. This message is
* always fatal.
*/
public const byte insufficient_security = 71;
/**
* An internal error unrelated to the peer or the correctness of the protocol (such as a memory
* allocation failure) makes it impossible to continue. This message is always fatal.
*/
public const byte internal_error = 80;
/**
* This handshake is being canceled for some reason unrelated to a protocol failure. If the user
* cancels an operation after the handshake is complete, just closing the connection by sending
* a close_notify is more appropriate. This alert should be followed by a close_notify. This
* message is generally a warning.
*/
public const byte user_canceled = 90;
/**
* Sent by the client in response to a hello request or by the server in response to a client
* hello after initial handshaking. Either of these would normally lead to renegotiation; when
* that is not appropriate, the recipient should respond with this alert. At that point, the
* original requester can decide whether to proceed with the connection. One case where this
* would be appropriate is where a server has spawned a process to satisfy a request; the
* process might receive security parameters (key length, authentication, etc.) at startup, and
* it might be difficult to communicate changes to these parameters after that point. This
* message is always a warning.
*/
public const byte no_renegotiation = 100;
/**
* Sent by clients that receive an extended server hello containing an extension that they did
* not put in the corresponding client hello. This message is always fatal.
*/
public const byte unsupported_extension = 110;
/*
* RFC 3546
*/
/**
* This alert is sent by servers who are unable to retrieve a certificate chain from the URL
* supplied by the client (see Section 3.3). This message MAY be fatal - for example if client
* authentication is required by the server for the handshake to continue and the server is
* unable to retrieve the certificate chain, it may send a fatal alert.
*/
public const byte certificate_unobtainable = 111;
/**
* This alert is sent by servers that receive a server_name extension request, but do not
* recognize the server name. This message MAY be fatal.
*/
public const byte unrecognized_name = 112;
/**
* This alert is sent by clients that receive an invalid certificate status response (see
* Section 3.6). This message is always fatal.
*/
public const byte bad_certificate_status_response = 113;
/**
* This alert is sent by servers when a certificate hash does not match a client provided
* certificate_hash. This message is always fatal.
*/
public const byte bad_certificate_hash_value = 114;
/*
* RFC 4279
*/
/**
* If the server does not recognize the PSK identity, it MAY respond with an
* "unknown_psk_identity" alert message.
*/
public const byte unknown_psk_identity = 115;
/*
* draft-ietf-tls-downgrade-scsv-00
*/
/**
* If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest protocol version
* supported by the server is higher than the version indicated in ClientHello.client_version,
* the server MUST respond with an inappropriate_fallback alert.
*/
public const byte inappropriate_fallback = 86;
public static string GetName(byte alertDescription)
{
switch (alertDescription)
{
case close_notify:
return "close_notify";
case unexpected_message:
return "unexpected_message";
case bad_record_mac:
return "bad_record_mac";
case decryption_failed:
return "decryption_failed";
case record_overflow:
return "record_overflow";
case decompression_failure:
return "decompression_failure";
case handshake_failure:
return "handshake_failure";
case no_certificate:
return "no_certificate";
case bad_certificate:
return "bad_certificate";
case unsupported_certificate:
return "unsupported_certificate";
case certificate_revoked:
return "certificate_revoked";
case certificate_expired:
return "certificate_expired";
case certificate_unknown:
return "certificate_unknown";
case illegal_parameter:
return "illegal_parameter";
case unknown_ca:
return "unknown_ca";
case access_denied:
return "access_denied";
case decode_error:
return "decode_error";
case decrypt_error:
return "decrypt_error";
case export_restriction:
return "export_restriction";
case protocol_version:
return "protocol_version";
case insufficient_security:
return "insufficient_security";
case internal_error:
return "internal_error";
case user_canceled:
return "user_canceled";
case no_renegotiation:
return "no_renegotiation";
case unsupported_extension:
return "unsupported_extension";
case certificate_unobtainable:
return "certificate_unobtainable";
case unrecognized_name:
return "unrecognized_name";
case bad_certificate_status_response:
return "bad_certificate_status_response";
case bad_certificate_hash_value:
return "bad_certificate_hash_value";
case unknown_psk_identity:
return "unknown_psk_identity";
case inappropriate_fallback:
return "inappropriate_fallback";
default:
return "UNKNOWN";
}
}
public static string GetText(byte alertDescription)
{
return GetName(alertDescription) + "(" + alertDescription + ")";
}
}
}
| 41.445902 | 104 | 0.621232 | [
"BSD-3-Clause"
] | ConnectionMaster/OutlookPrivacyPlugin | 3rdParty/bccrypto-net-05282015/crypto/src/crypto/tls/AlertDescription.cs | 12,641 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoFixture;
using AutoFixture.AutoMoq;
using Moq;
using NUnit.Framework;
namespace IqOptionApiDotNet.Tests {
public abstract class TestFor<TUnit> where TUnit : class
{
public virtual bool IsUsingFakeEngineContext { get; } = true;
protected IFixture Fixture { get; private set; }
private Lazy<TUnit> _lazyUnit;
protected TUnit Unit => _lazyUnit.Value;
[SetUp]
public virtual void EveryTimeSetup()
{
_lazyUnit = new Lazy<TUnit>(CreateUnit);
}
protected virtual TUnit CreateUnit()
{
return Fixture.Create<TUnit>();
}
[SetUp]
public void TestForSetup()
{
Fixture = new Fixture().Customize(new AutoMoqCustomization());
}
protected T A<T>()
{
return Fixture.Create<T>();
}
protected List<T> Many<T>(int count = 3)
{
return Fixture.CreateMany<T>(count).ToList();
}
protected Mock<T> Mock<T>()
where T : class
{
return new Mock<T>();
}
protected T Inject<T>(T instance)
where T : class
{
Fixture.Inject(instance);
return instance;
}
protected Mock<T> InjectMock<T>(params object[] args)
where T : class
{
var mock = new Mock<T>(args);
Fixture.Inject(mock.Object);
return mock;
}
protected Mock<Func<T>> CreateFailingFunction<T>(T result, params Exception[] exceptions)
{
var function = new Mock<Func<T>>();
var exceptionStack = new Stack<Exception>(exceptions.Reverse());
function
.Setup(f => f())
.Returns(() =>
{
if (exceptionStack.Any())
{
throw exceptionStack.Pop();
}
return result;
});
return function;
}
protected T Any<T>()
{
return It.IsAny<T>();
}
}
} | 24.659341 | 97 | 0.497326 | [
"MIT"
] | JorgeBeserra/IqOptionApiDotNet | tests/IqOptionApiDotNet.Tests/TestFor.cs | 2,244 | C# |
//==============================================================
// Copyright (C) 2021 Inc. All rights reserved.
//
//==============================================================
// Create by chongdaoyang at 2021/2/22 13:37:00.
// Version 1.0
// CHONGDAOYANGPC
//==============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cdy.Tag
{
/// <summary>
///
/// </summary>
public interface IAPINotify
{
void NotifyDatabaseChanged(bool realtag,bool histag,bool security);
}
}
| 25.56 | 75 | 0.467919 | [
"Apache-2.0"
] | cdy816/mars | RunTime/DBRuntime/Api/IAPINotify.cs | 641 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.TestSuite {
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.Messages.Runtime;
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute()]
public partial class OpenFileTestCase : PtfTestClassBase {
public OpenFileTestCase() {
this.SetSwitch("ProceedControlTimeout", "100");
this.SetSwitch("QuiescenceTimeout", "2000000");
}
#region Expect Delegates
public delegate void GetOSInfoDelegate1(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PlatformType platformType);
#endregion
#region Event Metadata
static System.Reflection.MethodBase GetOSInfoInfo = TestManagerHelpers.GetMethodInfo(typeof(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.IFSAAdapter), "GetOSInfo", typeof(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PlatformType).MakeByRefType());
#endregion
#region Adapter Instances
private Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.IFSAAdapter IFSAAdapterInstance;
#endregion
#region Class Initialization and Cleanup
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute()]
public static void ClassInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext context) {
PtfTestClassBase.Initialize(context);
}
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute()]
public static void ClassCleanup() {
PtfTestClassBase.Cleanup();
}
#endregion
#region Test Initialization and Cleanup
protected override void TestInitialize() {
this.InitializeTestManager();
this.IFSAAdapterInstance = ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.IFSAAdapter)(this.GetAdapter(typeof(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.IFSAAdapter))));
}
protected override void TestCleanup() {
base.TestCleanup();
this.CleanupTestManager();
}
#endregion
#region Test Starting in S0
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS0() {
this.Manager.BeginTest("OpenFileTestCaseS0");
this.Manager.Comment("reaching state \'S0\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S1\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S62\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp0;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp0);
this.Manager.Comment("reaching state \'S93\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp0, "securityContext of GetSystemConfig, state S93");
this.Manager.Comment("reaching state \'S124\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp1;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,None,StreamIsNotFound,IsNot" +
"SymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FILE_LIST_DIRECT" +
"ORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp1 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R366");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]If any of the bits in the mask 0x0CE0FE00 are set,
the operation MUST be failed with STATUS_ACCESS_DENIED.");
this.Manager.Checkpoint("MS-FSA_R377");
this.Manager.Checkpoint("[In Application Requests an Open of a File ,Pseudocode for the operation is as fo" +
"llows:\r\n Phase 1 - Parameter Validation:]If DesiredAccess is " +
"zero, the operation MUST be failed with STATUS_ACCESS_DENIED.");
this.Manager.Comment("reaching state \'S156\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_DENIED\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_DENIED, temp1, "return of OpenExistingFile, state S156");
this.Manager.Comment("reaching state \'S188\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S10
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS10() {
this.Manager.BeginTest("OpenFileTestCaseS10");
this.Manager.Comment("reaching state \'S10\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S11\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S67\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp2;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp2);
this.Manager.Comment("reaching state \'S98\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp2, "securityContext of GetSystemConfig, state S98");
this.Manager.Comment("reaching state \'S129\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp3;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,DIRECTORY_FILE|NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)" +
"\'");
temp3 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(65u)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R368");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_DIRECTORY_FILE && CreateOptions.FILE_NON_DIRECTORY_FILE.");
this.Manager.Comment("reaching state \'S161\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp3, "return of OpenExistingFile, state S161");
this.Manager.Comment("reaching state \'S193\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S12
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS12() {
this.Manager.BeginTest("OpenFileTestCaseS12");
this.Manager.Comment("reaching state \'S12\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S13\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S68\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp4;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp4);
this.Manager.Comment("reaching state \'S99\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp4, "securityContext of GetSystemConfig, state S99");
this.Manager.Comment("reaching state \'S130\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp5;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,SYNCHRONOUS_IO_ALERT,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp5 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.SYNCHRONOUS_IO_ALERT, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R369");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_SYNCHRONOUS_IO_ALERT && !DesiredAccess.SYNCHRONIZE.");
this.Manager.Comment("reaching state \'S162\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp5, "return of OpenExistingFile, state S162");
this.Manager.Comment("reaching state \'S194\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S14
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS14() {
this.Manager.BeginTest("OpenFileTestCaseS14");
this.Manager.Comment("reaching state \'S14\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S15\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S69\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp6;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp6);
this.Manager.Comment("reaching state \'S100\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp6, "securityContext of GetSystemConfig, state S100");
this.Manager.Comment("reaching state \'S131\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp7;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,SYNCHRONOUS_IO_NONALERT,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp7 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.SYNCHRONOUS_IO_NONALERT, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2373");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If Create.FILE_SYNCHRONOUS_IO_NONALERT&& !DesiredAccess.SYNCHRONIZE.");
this.Manager.Comment("reaching state \'S163\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp7, "return of OpenExistingFile, state S163");
this.Manager.Comment("reaching state \'S195\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S16
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS16() {
this.Manager.BeginTest("OpenFileTestCaseS16");
this.Manager.Comment("reaching state \'S16\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S17\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S70\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp8;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp8);
this.Manager.Comment("reaching state \'S101\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp8, "securityContext of GetSystemConfig, state S101");
this.Manager.Comment("reaching state \'S132\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp9;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,DELETE_ON_CLOSE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp9 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.DELETE_ON_CLOSE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R371");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_DELETE_ON_CLOSE && !DesiredAccess.DELETE.");
this.Manager.Comment("reaching state \'S164\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp9, "return of OpenExistingFile, state S164");
this.Manager.Comment("reaching state \'S196\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S18
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS18() {
this.Manager.BeginTest("OpenFileTestCaseS18");
this.Manager.Comment("reaching state \'S18\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S19\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S71\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp10;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp10);
this.Manager.Comment("reaching state \'S102\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp10, "securityContext of GetSystemConfig, state S102");
this.Manager.Comment("reaching state \'S133\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp11;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,SYNCHRONOUS_IO_ALERT|SYNCHRONOUS_IO_NONALERT,OPEN_IF,NULL,NOR" +
"MAL,NORMAL)\'");
temp11 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(48u)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R373");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_SYNCHRONOUS_IO_ALERT && Create.FILE_SYNCHRONOUS_IO_NONALERT.");
this.Manager.Comment("reaching state \'S165\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp11, "return of OpenExistingFile, state S165");
this.Manager.Comment("reaching state \'S197\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S2
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS2() {
this.Manager.BeginTest("OpenFileTestCaseS2");
this.Manager.Comment("reaching state \'S2\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S3\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S63\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp12;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp12);
this.Manager.Comment("reaching state \'S94\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp12, "securityContext of GetSystemConfig, state S94");
this.Manager.Comment("reaching state \'S125\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp13;
this.Manager.Comment("executing step \'call OpenExistingFile(NOT_VALID_VALUE,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,NOT_VALID_VALUE,F" +
"ILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp13 = this.IFSAAdapterInstance.OpenExistingFile(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess.NOT_VALID_VALUE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess.NOT_VALID_VALUE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2370");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If ShareAccess are not valid values for a file object as specified in [MS-SMB2] section 2.2.13.");
this.Manager.Comment("reaching state \'S157\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp13, "return of OpenExistingFile, state S157");
this.Manager.Comment("reaching state \'S189\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S20
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS20() {
this.Manager.BeginTest("OpenFileTestCaseS20");
this.Manager.Comment("reaching state \'S20\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S21\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S72\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp14;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp14);
this.Manager.Comment("reaching state \'S103\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp14, "securityContext of GetSystemConfig, state S103");
this.Manager.Comment("reaching state \'S134\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp15;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,DIRECTORY_FILE,OVERWRITE,NULL,NORMAL,NORMAL)\'");
temp15 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OVERWRITE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2375");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_DIRECTORY_FILE && CreateDisposition == OVERWRITE.");
this.Manager.Comment("reaching state \'S166\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp15, "return of OpenExistingFile, state S166");
this.Manager.Comment("reaching state \'S198\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S22
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS22() {
this.Manager.BeginTest("OpenFileTestCaseS22");
this.Manager.Comment("reaching state \'S22\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S23\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S73\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp16;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp16);
this.Manager.Comment("reaching state \'S104\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp16, "securityContext of GetSystemConfig, state S104");
this.Manager.Comment("reaching state \'S135\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp17;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,DIRECTORY_FILE,SUPERSEDE,NULL,NORMAL,NORMAL)\'");
temp17 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2374");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_DIRECTORY_FILE && CreateDisposition == SUPERSEDE .");
this.Manager.Comment("reaching state \'S167\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp17, "return of OpenExistingFile, state S167");
this.Manager.Comment("reaching state \'S199\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S24
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS24() {
this.Manager.BeginTest("OpenFileTestCaseS24");
this.Manager.Comment("reaching state \'S24\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S25\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S74\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp18;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp18);
this.Manager.Comment("reaching state \'S105\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp18, "securityContext of GetSystemConfig, state S105");
this.Manager.Comment("reaching state \'S136\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp19;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,DIRECTORY_FILE,OVERWRITE_IF,NULL,NORMAL,NORMAL)\'");
temp19 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OVERWRITE_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2376");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_DIRECTORY_FILE && CreateDisposition == OVERWRITE_IF).");
this.Manager.Comment("reaching state \'S168\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp19, "return of OpenExistingFile, state S168");
this.Manager.Comment("reaching state \'S200\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S26
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS26() {
this.Manager.BeginTest("OpenFileTestCaseS26");
this.Manager.Comment("reaching state \'S26\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S27\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S75\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp20;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp20);
this.Manager.Comment("reaching state \'S106\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp20, "securityContext of GetSystemConfig, state S106");
this.Manager.Comment("reaching state \'S137\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp21;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,COMPLETE_IF_OPLOCKED|RESERVE_OPFILTER,OPEN_IF,NULL,NORMAL,NOR" +
"MAL)\'");
temp21 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1048832u)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R375");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.COMPLETE_IF_OPLOCKED && CreateOptions.FILE_RESERVE_OPFILTER.");
this.Manager.Comment("reaching state \'S169\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp21, "return of OpenExistingFile, state S169");
this.Manager.Comment("reaching state \'S201\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S28
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS28() {
this.Manager.BeginTest("OpenFileTestCaseS28");
this.Manager.Comment("reaching state \'S28\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S29\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S76\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp22;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp22);
this.Manager.Comment("reaching state \'S107\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp22, "securityContext of GetSystemConfig, state S107");
this.Manager.Comment("reaching state \'S138\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp23;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_ADD_SUBDIRECTORY,Strea" +
"mIsNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ" +
",FILE_LIST_DIRECTORY,NO_INTERMEDIATE_BUFFERING,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp23 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.FILE_ADD_SUBDIRECTORY, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NO_INTERMEDIATE_BUFFERING, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R376");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Phase 1 - Parameter Validation:]
The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions.FILE_NO_INTERMEDIATE_BUFFERING && DesiredAccess.FILE_APPEND_DATA.");
this.Manager.Comment("reaching state \'S170\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp23, "return of OpenExistingFile, state S170");
this.Manager.Comment("reaching state \'S202\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S30
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS30() {
this.Manager.BeginTest("OpenFileTestCaseS30");
this.Manager.Comment("reaching state \'S30\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S31\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S77\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp24;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp24);
this.Manager.Comment("reaching state \'S108\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp24, "securityContext of GetSystemConfig, state S108");
this.Manager.Comment("reaching state \'S139\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp25;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,NotPathNameValid,NON_DIRECTORY_FILE,FILE_SH" +
"ARE_READ,FILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp25 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R379");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_OBJECT_NAME_INVALID under any of the following conditions:
If PathName is not valid as specified in [MS-FSCC] section 2.1.5.");
this.Manager.Comment("reaching state \'S171\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_INVALID\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_INVALID, temp25, "return of OpenExistingFile, state S171");
this.Manager.Comment("reaching state \'S203\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S32
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS32() {
this.Manager.BeginTest("OpenFileTestCaseS32");
this.Manager.Comment("reaching state \'S32\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S33\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S78\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp26;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp26);
this.Manager.Comment("reaching state \'S109\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp26, "securityContext of GetSystemConfig, state S109");
this.Manager.Comment("reaching state \'S140\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp27;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,BackslashName,NON_DIRECTORY_FILE,FILE_SHARE" +
"_READ,FILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp27 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R380");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_OBJECT_NAME_INVALID under any of the following conditions:
If PathName contains a trailing backslash and CreateOptions.FILE_NON_DIRECTORY_FILE is TRUE.");
this.Manager.Comment("reaching state \'S172\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_INVALID\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_INVALID, temp27, "return of OpenExistingFile, state S172");
this.Manager.Comment("reaching state \'S204\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S36
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS36() {
this.Manager.BeginTest("OpenFileTestCaseS36");
this.Manager.Comment("reaching state \'S36\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S37\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S80\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp36;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp36);
this.Manager.Comment("reaching state \'S111\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp36, "securityContext of GetSystemConfig, state S111");
this.Manager.Comment("reaching state \'S143\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp37;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,IsPrefixLinkNotFound,DIRECTORY_FILE,FILE_SH" +
"ARE_READ,FILE_LIST_DIRECTORY,DIRECTORY_FILE,OPEN,NULL,NORMAL,NORMAL)\'");
temp37 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.IsPrefixLinkNotFound, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R513");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Else:[If such a link is not found:]
If CreateDisposition == FILE_OPEN, the operation MUST be failed with STATUS_OBJECT_NAME_NOT_FOUND.");
this.Manager.Comment("reaching state \'S175\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_NOT_FOUND\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_NOT_FOUND, temp37, "return of OpenExistingFile, state S175");
this.Manager.Comment("reaching state \'S207\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S38
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS38() {
this.Manager.BeginTest("OpenFileTestCaseS38");
this.Manager.Comment("reaching state \'S38\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S39\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S81\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp38;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp38);
this.Manager.Comment("reaching state \'S112\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp38, "securityContext of GetSystemConfig, state S112");
this.Manager.Comment("reaching state \'S144\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp39;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OVERWRITE,NULL,NORMAL,NORMAL)\'");
temp39 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OVERWRITE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2395");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Else:[If such a link is not found:]If CreateDisposition == FILE_OVERWRITE),
the operation MUST be failed with STATUS_OBJECT_NAME_NOT_FOUND.");
this.Manager.Comment("reaching state \'S176\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_NOT_FOUND\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_NOT_FOUND, temp39, "return of OpenExistingFile, state S176");
this.Manager.Comment("reaching state \'S208\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S4
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS4() {
this.Manager.BeginTest("OpenFileTestCaseS4");
this.Manager.Comment("reaching state \'S4\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S5\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S64\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp40;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp40);
this.Manager.Comment("reaching state \'S95\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp40, "securityContext of GetSystemConfig, state S95");
this.Manager.Comment("reaching state \'S126\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp41;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,NOT_VALID_VALUE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp41 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NOT_VALID_VALUE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2371");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateOptions are not valid values for a file object as specified in [MS-SMB2] section 2.2.13.");
this.Manager.Comment("reaching state \'S158\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp41, "return of OpenExistingFile, state S158");
this.Manager.Comment("reaching state \'S190\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S40
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS40() {
this.Manager.BeginTest("OpenFileTestCaseS40");
this.Manager.Comment("reaching state \'S40\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S41\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S82\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp42;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp42);
this.Manager.Comment("reaching state \'S113\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp42, "securityContext of GetSystemConfig, state S113");
this.Manager.Comment("reaching state \'S145\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp43;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FILE_LI" +
"ST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp43 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R399");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,
Pseudocode for the operation is as follows:Phase 6 - Location of file:]
Pseudocode for this search:For i = 1 to n-1:If Link.File.IsSymbolicLink is TRUE,
the operation MUST be failed with Status set to STATUS_STOPPED_ON_SYMLINK .");
this.Manager.Comment("reaching state \'S177\'");
this.Manager.Comment("checking step \'return OpenExistingFile/STOPPED_ON_SYMLINK\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.STOPPED_ON_SYMLINK, temp43, "return of OpenExistingFile, state S177");
this.Manager.Comment("reaching state \'S209\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S42
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS42() {
this.Manager.BeginTest("OpenFileTestCaseS42");
this.Manager.Comment("reaching state \'S42\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S43\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S83\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp44;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp44);
this.Manager.Comment("reaching state \'S114\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp44, "securityContext of GetSystemConfig, state S114");
this.Manager.Comment("reaching state \'S146\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp45;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsNotSymbolicLink,DataFile,OpenFileNotNull,NON_DIRECTORY_FILE,FILE_SHARE_" +
"READ,FILE_LIST_DIRECTORY,DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NORMAL)\'");
temp45 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.OpenFileNotNull, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R2396");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Phase 7 -- Type of file to open:]
If FileTypeToOpen is DirectoryFile and Open.File is not NULL and Open.File.FileType is not DirectoryFile:
else[If CreateDisposition != FILE_CREATE] the operation MUST be failed with STATUS_NOT_A_DIRECTORY.");
this.Manager.Comment("reaching state \'S178\'");
this.Manager.Comment("checking step \'return OpenExistingFile/NOT_A_DIRECTORY\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.NOT_A_DIRECTORY, temp45, "return of OpenExistingFile, state S178");
this.Manager.Comment("reaching state \'S210\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S44
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS44() {
this.Manager.BeginTest("OpenFileTestCaseS44");
this.Manager.Comment("reaching state \'S44\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S45\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S84\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp46;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp46);
this.Manager.Comment("reaching state \'S115\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp46, "securityContext of GetSystemConfig, state S115");
this.Manager.Comment("reaching state \'S147\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp47;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_ADD_SUBDIRECTORY,Strea" +
"mIsFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FI" +
"LE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,READONLY,NORMAL)\'");
temp47 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.FILE_ADD_SUBDIRECTORY, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R53");
this.Manager.Checkpoint(@"[In Algorithm to Check Access to an Existing File,Pseudocode for these checks is as follows:]
If Open.File.FileType is DataFile and (File.FileAttributes.FILE_ATTRIBUTE_READONLY && (DesiredAccess.FILE_WRITE_DATA )), then return STATUS_ACCESS_DENIED.");
this.Manager.Comment("reaching state \'S179\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_DENIED\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_DENIED, temp47, "return of OpenExistingFile, state S179");
this.Manager.Comment("reaching state \'S211\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S46
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS46() {
this.Manager.BeginTest("OpenFileTestCaseS46");
this.Manager.Comment("reaching state \'S46\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S47\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S85\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp48;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp48);
this.Manager.Comment("reaching state \'S116\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp48, "securityContext of GetSystemConfig, state S116");
this.Manager.Comment("reaching state \'S148\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp49;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_ADD_FILE,StreamIsFound" +
",IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FILE_LIST_" +
"DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,READONLY,NORMAL)\'");
temp49 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.FILE_ADD_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R2422");
this.Manager.Checkpoint(@"[In Algorithm to Check Access to an Existing File]Pseudocode for these checks is as follows:
If Open.File.FileType is DataFile and (File.FileAttributes.FILE_ATTRIBUTE_READONLY && (DesiredAccess.FILE_APPEND_DATA)),
then return STATUS_ACCESS_DENIED.");
this.Manager.Comment("reaching state \'S180\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_DENIED\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_DENIED, temp49, "return of OpenExistingFile, state S180");
this.Manager.Comment("reaching state \'S212\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S48
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS48() {
this.Manager.BeginTest("OpenFileTestCaseS48");
this.Manager.Comment("reaching state \'S48\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S49\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S86\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp50;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp50);
this.Manager.Comment("reaching state \'S117\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp50, "securityContext of GetSystemConfig, state S117");
this.Manager.Comment("reaching state \'S149\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp51;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,DELETE,StreamIsFound,IsNotS" +
"ymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FILE_LIST_DIRECTO" +
"RY,DELETE_ON_CLOSE,OPEN,NULL,READONLY,NORMAL)\'");
temp51 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.DELETE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.DELETE_ON_CLOSE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R54");
this.Manager.Checkpoint("[In Algorithm to Check Access to an Existing File,Pseudocode for these checks is " +
"as follows:]\r\n If ((File.FileAttributes.FILE_ATTRIBUTE_READON" +
"LY) && CreateOptions.FILE_DELETE_ON_CLOSE), then return STATUS_CANNOT_DELETE.");
this.Manager.Comment("reaching state \'S181\'");
this.Manager.Comment("checking step \'return OpenExistingFile/CANNOT_DELETE\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.CANNOT_DELETE, temp51, "return of OpenExistingFile, state S181");
this.Manager.Comment("reaching state \'S213\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S50
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS50() {
this.Manager.BeginTest("OpenFileTestCaseS50");
this.Manager.Comment("reaching state \'S50\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S51\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S87\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp52;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp52);
this.Manager.Comment("reaching state \'S118\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp52, "securityContext of GetSystemConfig, state S118");
this.Manager.Comment("reaching state \'S150\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp53;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_DELETE,FILE_LIST_DIRECTORY,Strea" +
"mIsFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,DE" +
"LETE,NON_DIRECTORY_FILE,OPEN,NULL,NORMAL,NORMAL)\'");
temp53 = this.IFSAAdapterInstance.OpenExistingFile(Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess.FILE_SHARE_DELETE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.DELETE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R65");
this.Manager.Checkpoint("[In Algorithm to Check Access to an Existing File,Pseudocode for these checks is " +
"as follows:,\r\n if the sharing conflicts check has no violation]Re" +
"turn STATUS_SUCCESS.");
this.Manager.Checkpoint("MS-FSA_R656");
this.Manager.Checkpoint("[In Algorithm to Check Sharing Access to an Existing Stream or Directory]\r\n " +
" Pseudocode for these checks is as follows,if the sharing checks has no" +
" violation]Return STATUS_SUCCESS.");
this.Manager.Checkpoint("MS-FSA_R631");
this.Manager.Checkpoint("[In Open of an Existing File,Pseudocode for these checks is as follows:]\r\n " +
" The object store MUST return :CreateAction set to FILE_OPENED.");
this.Manager.Checkpoint("MS-FSA_R630");
this.Manager.Checkpoint("[In Open of an Existing File,Pseudocode for these checks is as follows:]\r\n " +
" The object store MUST return:Status set to STATUS_SUCCESS.");
this.Manager.Comment("reaching state \'S182\'");
this.Manager.Comment("checking step \'return OpenExistingFile/SUCCESS\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus)(0)), temp53, "return of OpenExistingFile, state S182");
this.Manager.Comment("reaching state \'S214\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S52
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS52() {
this.Manager.BeginTest("OpenFileTestCaseS52");
this.Manager.Comment("reaching state \'S52\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S53\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S88\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp54;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp54);
this.Manager.Comment("reaching state \'S119\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp54, "securityContext of GetSystemConfig, state S119");
this.Manager.Comment("reaching state \'S151\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp55;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_ADD_FILE,StreamIsFound" +
",IsNotSymbolicLink,DataFile,Normal,DIRECTORY_FILE,FILE_SHARE_READ,FILE_LIST_DIRE" +
"CTORY,DIRECTORY_FILE,OPEN_IF,NULL,READONLY,NORMAL)\'");
temp55 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess.FILE_ADD_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R65");
this.Manager.Checkpoint("[In Algorithm to Check Access to an Existing File,Pseudocode for these checks is " +
"as follows:,\r\n if the sharing conflicts check has no violation]Re" +
"turn STATUS_SUCCESS.");
this.Manager.Checkpoint("MS-FSA_R639");
this.Manager.Checkpoint(@"[In Open of an Existing File,Pseudocode for the operation is as follows:
If FileTypeToOpen is DirectoryFile:If CreateDisposition is FILE_OPEN then:]
If this [Perform sharing access checks as described in section 3.1.5.1.2.2.]fails, the request MUST be failed with the same status.");
this.Manager.Comment("reaching state \'S183\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_VIOLATION\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_VIOLATION, temp55, "return of OpenExistingFile, state S183");
this.Manager.Comment("reaching state \'S215\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S54
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS54() {
this.Manager.BeginTest("OpenFileTestCaseS54");
this.Manager.Comment("reaching state \'S54\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S55\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S89\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp56;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp56);
this.Manager.Comment("reaching state \'S120\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp56, "securityContext of GetSystemConfig, state S120");
this.Manager.Comment("reaching state \'S152\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp57;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsNotSymbolicLink,DataFile,Normal,DIRECTORY_FILE,FILE_SHARE_WRITE,FILE_LI" +
"ST_DIRECTORY,DIRECTORY_FILE,OPEN,NULL,NORMAL,NORMAL)\'");
temp57 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess.FILE_SHARE_WRITE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R65");
this.Manager.Checkpoint("[In Algorithm to Check Access to an Existing File,Pseudocode for these checks is " +
"as follows:,\r\n if the sharing conflicts check has no violation]Re" +
"turn STATUS_SUCCESS.");
this.Manager.Checkpoint("MS-FSA_R636");
this.Manager.Checkpoint(@"[In Open of an Existing File,Pseudocode for the operation is as follows:
If OpenFileType is DirectoryFile:If CreateDisposition is FILE_OPEN_IF then:]
If this[Perform access checks as described in section 3.1.5.1.2.1.] fails, the request MUST be failed with the same status.");
this.Manager.Comment("reaching state \'S184\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_VIOLATION\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_VIOLATION, temp57, "return of OpenExistingFile, state S184");
this.Manager.Comment("reaching state \'S216\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S56
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS56() {
this.Manager.BeginTest("OpenFileTestCaseS56");
this.Manager.Comment("reaching state \'S56\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S57\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S90\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp58;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp58);
this.Manager.Comment("reaching state \'S121\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp58, "securityContext of GetSystemConfig, state S121");
this.Manager.Comment("reaching state \'S153\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp59;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,FILE" +
"_LIST_DIRECTORY,NON_DIRECTORY_FILE,CREATE,NULL,NORMAL,NORMAL)\'");
temp59 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.CREATE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R584");
this.Manager.Checkpoint(@"[In Open of an Existing File,Pseudocode for the operation is as follows:
Else if FileTypeToOpen is DataFile,If Stream was found,]If CreateDisposition is FILE_CREATE,
then the operation MUST be failed with STATUS_OBJECT_NAME_COLLISION.");
this.Manager.Comment("reaching state \'S185\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_COLLISION\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_COLLISION, temp59, "return of OpenExistingFile, state S185");
this.Manager.Comment("reaching state \'S217\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S58
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS58() {
this.Manager.BeginTest("OpenFileTestCaseS58");
this.Manager.Comment("reaching state \'S58\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S59\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S91\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp60;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp60);
this.Manager.Comment("reaching state \'S122\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp60, "securityContext of GetSystemConfig, state S122");
this.Manager.Comment("reaching state \'S154\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp61;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsNotSymbolicLink,DataFile,StreamNameNull,NON_DIRECTORY_FILE,FILE_SHARE_R" +
"EAD,FILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OVERWRITE_IF,NULL,SYSTEM,NORMAL)\'");
temp61 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.StreamNameNull, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OVERWRITE_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.SYSTEM, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R488");
this.Manager.Checkpoint(@"[In Open of an Existing File,Pseudocode for these checks is as follows:
Else if FileTypeToOpen is DataFile,If Stream was found,Else (CreateDisposition is not FILE_OPEN and is not FILE_OPEN_IF),
If Stream.Name is empty:]If File.FileAttributes.FILE_ATTRIBUTE_SYSTEM is TRUE
and DesiredFileAttributes.FILE_ATTRIBUTE_SYSTEM is FALSE, then the operation MUST be failed with STATUS_ACCESS_DENIED.");
this.Manager.Comment("reaching state \'S186\'");
this.Manager.Comment("checking step \'return OpenExistingFile/ACCESS_DENIED\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.ACCESS_DENIED, temp61, "return of OpenExistingFile, state S186");
this.Manager.Comment("reaching state \'S218\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S6
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS6() {
this.Manager.BeginTest("OpenFileTestCaseS6");
this.Manager.Comment("reaching state \'S6\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S7\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S65\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp62;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp62);
this.Manager.Comment("reaching state \'S96\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp62, "securityContext of GetSystemConfig, state S96");
this.Manager.Comment("reaching state \'S127\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp63;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,NOT_VALID_VALUE,NULL,NORMAL,NORMAL)\'");
temp63 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.NOT_VALID_VALUE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R2372");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If CreateDisposition are not valid values for a file object as specified in [MS-SMB2] section 2.2.13.");
this.Manager.Comment("reaching state \'S159\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp63, "return of OpenExistingFile, state S159");
this.Manager.Comment("reaching state \'S191\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S60
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS60() {
this.Manager.BeginTest("OpenFileTestCaseS60");
this.Manager.Comment("reaching state \'S60\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S61\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S92\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp64;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp64);
this.Manager.Comment("reaching state \'S123\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp64, "securityContext of GetSystemConfig, state S123");
this.Manager.Comment("reaching state \'S155\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp65;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sFound,IsNotSymbolicLink,DataFile,OpenFileNotNull,NON_DIRECTORY_FILE,FILE_SHARE_" +
"READ,FILE_LIST_DIRECTORY,DIRECTORY_FILE,CREATE,NULL,NORMAL,NORMAL)\'");
temp65 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(0)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.OpenFileNotNull, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.CREATE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL);
this.Manager.Checkpoint("MS-FSA_R405");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 6 -- Location of file:] Pseudocode for this search:For i = 1 to n-1:
If Open.GrantedAccess.FILE_TRAVERSE is not set and AccessCheck( SecurityContext, Link.File.SecurityDescriptor, FILE_TRAVERSE )
returns FALSE, the operation is not failed with STATUS_ACCESS_DENIED in Windows.");
this.Manager.Checkpoint("MS-FSA_R414");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File , Pseudocode for the operation is as follows:
Phase 7 -- Type of file to open:]If FileTypeToOpen is DirectoryFile and Open.File is not NULL
and Open.File.FileType is not DirectoryFile:If CreateDisposition == FILE_CREATE then the operation MUST be failed with STATUS_OBJECT_NAME_COLLISION.");
this.Manager.Comment("reaching state \'S187\'");
this.Manager.Comment("checking step \'return OpenExistingFile/OBJECT_NAME_COLLISION\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.OBJECT_NAME_COLLISION, temp65, "return of OpenExistingFile, state S187");
this.Manager.Comment("reaching state \'S219\'");
this.Manager.EndTest();
}
#endregion
#region Test Starting in S8
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Model)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Fsa)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.OpenFile)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.NonSmb)]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCategory(Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter.TestCategories.Positive)]
public void OpenFileTestCaseS8() {
this.Manager.BeginTest("OpenFileTestCaseS8");
this.Manager.Comment("reaching state \'S8\'");
this.Manager.Comment("executing step \'call FsaInitial()\'");
this.IFSAAdapterInstance.FsaInitial();
this.Manager.Comment("reaching state \'S9\'");
this.Manager.Comment("checking step \'return FsaInitial\'");
this.Manager.Comment("reaching state \'S66\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext temp66;
this.Manager.Comment("executing step \'call GetSystemConfig(out _)\'");
this.IFSAAdapterInstance.GetSystemConfig(out temp66);
this.Manager.Comment("reaching state \'S97\'");
this.Manager.Comment("checking step \'return GetSystemConfig/[out SSecurityContext(privilegeSet=SeRestor" +
"ePrivilege,isSecurityContextSIDsContainWellKnown=False,isImplementsEncryption=Fa" +
"lse)]\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(this.Manager, this.Make<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SSecurityContext>(new string[] {
"privilegeSet",
"isSecurityContextSIDsContainWellKnown",
"isImplementsEncryption"}, new object[] {
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.PrivilegeSet.SeRestorePrivilege,
false,
false}), temp66, "securityContext of GetSystemConfig, state S97");
this.Manager.Comment("reaching state \'S128\'");
Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus temp67;
this.Manager.Comment("executing step \'call OpenExistingFile(FILE_SHARE_READ,FILE_LIST_DIRECTORY,StreamI" +
"sNotFound,IsNotSymbolicLink,DataFile,Normal,NON_DIRECTORY_FILE,FILE_SHARE_READ,F" +
"ILE_LIST_DIRECTORY,NON_DIRECTORY_FILE,OPEN_IF,NULL,NORMAL,NOT_VALID_VALUE)\'");
temp67 = this.IFSAAdapterInstance.OpenExistingFile(((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamFoundType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.SymbolicLinkType)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileType)(0)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileNameStatus.Normal, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.ShareAccess)(1)), ((Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAccess)(1)), Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateOptions.NON_DIRECTORY_FILE, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.CreateDisposition.OPEN_IF, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.StreamTypeNameToOpen.NULL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NORMAL, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.FileAttribute.NOT_VALID_VALUE);
this.Manager.Checkpoint("MS-FSA_R404");
this.Manager.Checkpoint(@"[In Application Requests an Open of a File ,Pseudocode for the operation is as follows:
Phase 1 - Parameter Validation:]The operation MUST be failed with STATUS_INVALID_PARAMETER under any of the following conditions:
If FileAttributes are not valid values for a file object as specified in [MS-SMB2] section 2.2.13.");
this.Manager.Comment("reaching state \'S160\'");
this.Manager.Comment("checking step \'return OpenExistingFile/INVALID_PARAMETER\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus>(this.Manager, Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter.MessageStatus.INVALID_PARAMETER, temp67, "return of OpenExistingFile, state S160");
this.Manager.Comment("reaching state \'S192\'");
this.Manager.EndTest();
}
#endregion
}
}
| 106.415276 | 1,188 | 0.721053 | [
"MIT"
] | G-arj/WindowsProtocolTestSuites | TestSuites/FileServer/src/FSAModel/TestSuite/OpenFileTestCase.cs | 165,795 | C# |
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Mvc;
namespace AttendeeList
{
[Route("/api/[controller]")]
public class PlatformController : Controller
{
[HttpGet]
public string Get()
{
return RuntimeInformation.OSDescription;
}
}
} | 20.666667 | 52 | 0.635484 | [
"MIT"
] | AnzhelikaKravchuk/aspnetcore-concepts-workshop | Labs/Code/App/AttendeeList/Controllers/PlatformController.cs | 310 | C# |
using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.Work.Events
{
/// <summary>
/// <para>表示 INFO.remark_device_name 事件的数据。</para>
/// <para>REF: https://open.work.weixin.qq.com/api/doc/90002/90151/90751 </para>
/// </summary>
public class RemarkDeviceNameEvent : WechatWorkEvent, WechatWorkEvent.Types.IXmlSerializable
{
/// <summary>
/// 获取或设置服务商 CorpId。
/// </summary>
[System.Xml.Serialization.XmlElement("ServiceCorpId")]
public string ServiceCorpId { get; set; } = default!;
/// <summary>
/// 获取或设置设备备注名称。
/// </summary>
[System.Xml.Serialization.XmlElement("RemarkName")]
public string RemarkName { get; set; } = default!;
}
}
| 31.16 | 96 | 0.62516 | [
"MIT"
] | KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Work/Events/Device/RemarkDeviceNameEvent.cs | 839 | C# |
namespace ClienteWcfData
{
partial class frmAddAlumno
{
/// <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.txtBoxNameAdd = new System.Windows.Forms.TextBox();
this.txtBoxSurnameAdd = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.btnSaveAdd = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.txtBoxEmailAdd = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtBoxNameAdd
//
this.txtBoxNameAdd.Location = new System.Drawing.Point(307, 149);
this.txtBoxNameAdd.Name = "txtBoxNameAdd";
this.txtBoxNameAdd.Size = new System.Drawing.Size(201, 26);
this.txtBoxNameAdd.TabIndex = 0;
//
// txtBoxSurnameAdd
//
this.txtBoxSurnameAdd.Location = new System.Drawing.Point(307, 195);
this.txtBoxSurnameAdd.Name = "txtBoxSurnameAdd";
this.txtBoxSurnameAdd.Size = new System.Drawing.Size(201, 26);
this.txtBoxSurnameAdd.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(208, 154);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(51, 20);
this.label1.TabIndex = 2;
this.label1.Text = "Name";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(208, 201);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(74, 20);
this.label2.TabIndex = 3;
this.label2.Text = "Surname";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Palatino Linotype", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(322, 67);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(148, 38);
this.label4.TabIndex = 5;
this.label4.Text = "Add Form";
//
// btnSaveAdd
//
this.btnSaveAdd.Location = new System.Drawing.Point(531, 297);
this.btnSaveAdd.Name = "btnSaveAdd";
this.btnSaveAdd.Size = new System.Drawing.Size(75, 29);
this.btnSaveAdd.TabIndex = 6;
this.btnSaveAdd.Text = "Save";
this.btnSaveAdd.UseVisualStyleBackColor = true;
this.btnSaveAdd.Click += new System.EventHandler(this.btnSaveAdd_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(208, 250);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(46, 20);
this.label3.TabIndex = 8;
this.label3.Text = "email";
//
// txtBoxEmailAdd
//
this.txtBoxEmailAdd.Location = new System.Drawing.Point(307, 244);
this.txtBoxEmailAdd.Name = "txtBoxEmailAdd";
this.txtBoxEmailAdd.Size = new System.Drawing.Size(201, 26);
this.txtBoxEmailAdd.TabIndex = 7;
//
// frmAddAlumno
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtBoxEmailAdd);
this.Controls.Add(this.btnSaveAdd);
this.Controls.Add(this.label4);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtBoxSurnameAdd);
this.Controls.Add(this.txtBoxNameAdd);
this.Name = "frmAddAlumno";
this.Text = "frmAddAlumno";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtBoxNameAdd;
private System.Windows.Forms.TextBox txtBoxSurnameAdd;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button btnSaveAdd;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtBoxEmailAdd;
}
} | 41.185714 | 160 | 0.565383 | [
"MIT"
] | Fantasmy/WcfDataClient | ClienteWcfData/frmAddAlumno.Designer.cs | 5,768 | C# |
using Baraka.Services.Streaming.Core;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace Baraka.Services.Streaming
{
// https://markheath.net/post/fire-and-forget-audio-playback-with
public class CachedSound
{
public float[] AudioData { get; private set; }
public WaveFormat WaveFormat { get; private set; }
public CachedSound(byte[] data)
{
using (var ms = new MemoryStream(data))
using (var audioFileReader = new AudioStreamReader(ms))
{
var resampler = new WdlResamplingSampleProvider(audioFileReader, 44100);
WaveFormat = resampler.WaveFormat;
var wholeFile = new List<float>((int)(audioFileReader.Length / 4));
var readBuffer = new float[WaveFormat.SampleRate * WaveFormat.Channels];
int samplesRead;
while ((samplesRead = resampler.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
wholeFile.AddRange(readBuffer.Take(samplesRead));
}
AudioData = wholeFile.ToArray();
}
}
}
}
| 34.722222 | 92 | 0.6088 | [
"BSD-3-Clause"
] | Jomtek/Baraka | Baraka/Services/Streaming/Core/CachedSound.cs | 1,252 | C# |
// Copyright © 2021 Soft-Fx. All rights reserved.
// Author: Andrei Hilevich
//
// 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/.
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpRpc
{
public class ConsoleLogger : IRpcLogger
{
private bool _printStack;
public ConsoleLogger(bool verbose, bool printStackTrace)
{
VerboseEnabled = verbose;
_printStack = printStackTrace;
}
public bool VerboseEnabled { get; }
public void Info(string component, string msg)
{
Console.WriteLine(component + " " + msg);
}
public void Verbose(string component, string msg)
{
Console.WriteLine(component + " " + msg);
}
public void Warn(string component, string msg, Exception ex)
{
Console.WriteLine(component + " " + msg);
if (ex != null && _printStack)
Console.WriteLine(ex.ToString());
}
public void Error(string component, string msg, Exception ex)
{
Console.Error.WriteLine(component + " " + msg);
if (ex != null && _printStack)
Console.WriteLine(ex.ToString());
}
}
}
| 27.862745 | 69 | 0.589022 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | GonzoSpire/SharpRpc | src/SharpRpc/Logging/ConsoleLogger.cs | 1,424 | C# |
using System;
using MvcContrib.FluentHtml;
using MvcContrib.UnitTests.FluentHtml.Fakes;
using MvcContrib.UnitTests.FluentHtml.Helpers;
using NUnit.Framework;
using MvcContrib.FluentHtml.Html;
namespace MvcContrib.UnitTests.FluentHtml
{
[TestFixture]
public class ViewDataContainerExtensionsTests
{
private FakeViewDataContainer target;
private FakeModel fake;
[SetUp]
public void SetUp()
{
target = new FakeViewDataContainer();
fake = new FakeModel
{
Title = "Test Title",
Date = DateTime.Now,
Done = true,
Id = 123,
Person = new FakeChildModel
{
FirstName = "Mick",
LastName = "Jagger"
},
Numbers = new [] {1, 3}
};
target.ViewData["fake"] = fake;
}
[Test]
public void can_get_textbox_with_value_from_simple_property()
{
var element = target.TextBox("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_textbox_with_value_from_complex_property()
{
var element = target.TextBox("fake.Person.FirstName");
element.ValueAttributeShouldEqual(fake.Person.FirstName);
}
[Test]
public void can_get_checkbox_with_checked()
{
var element = target.CheckBox("fake.Done");
element.AttributeShouldEqual(HtmlAttribute.Checked, HtmlAttribute.Checked);
}
[Test]
public void can_get_file_upload()
{
var element = target.FileUpload("test");
element.ShouldNotBeNull();
}
[Test]
public void can_get_label_with_value()
{
var element = target.Label("fake.Title");
element.AttributeShouldEqual(HtmlAttribute.For, "fake_Title");
element.InnerTextShouldEqual(fake.Title);
}
[Test]
public void can_get_literal_with_value()
{
var element = target.Literal("foo bar");
element.InnerTextShouldEqual("foo bar");
}
[Test]
public void can_get_literal_with_name_and_value()
{
var element = target.Literal("name", "foo bar");
element.InnerTextShouldEqual("foo bar");
element.AttributeShouldEqual("name", "name");
}
[Test]
public void can_get_form_literal_with_value()
{
var element = target.FormLiteral("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_hidden_with_value()
{
var element = target.Hidden("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_select()
{
var element = target.Select("fake.Id");
element.SelectedValues.ShouldCount(1);
var enumerator = element.SelectedValues.GetEnumerator();
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Id);
}
[Test]
public void can_get_multi_select()
{
var element = target.MultiSelect("fake.Numbers");
element.SelectedValues.ShouldCount(2);
var enumerator = element.SelectedValues.GetEnumerator();
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Numbers[0]);
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Numbers[1]);
}
[Test]
public void can_get_password_with_value()
{
var element = target.Password("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_submit_button_with_value()
{
var element = target.SubmitButton("Push Me");
element.ValueAttributeShouldEqual("Push Me");
}
[Test]
public void can_get_text_area_with_value()
{
var element = target.TextArea("fake.Title");
element.InnerTextShouldEqual(fake.Title);
}
[Test]
public void can_get_radio_set_with_selected_value()
{
var element = target.RadioSet("fake.Id");
element.SelectedValues.ShouldCount(1);
var enumerator = element.SelectedValues.GetEnumerator();
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Id);
}
[Test]
public void can_get_radio_button()
{
target.RadioButton("Id").AttributeShouldEqual(HtmlAttribute.Name, "Id");
}
[Test]
public void can_get_checkboxlist_with_selected_values()
{
var element = target.CheckBoxList("fake.Numbers");
element.SelectedValues.ShouldCount(2);
var enumerator = element.SelectedValues.GetEnumerator();
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Numbers[0]);
enumerator.MoveNext();
enumerator.Current.ShouldEqual(fake.Numbers[1]);
}
[Test]
public void can_get_numberbox_with_value()
{
var element = target.NumberBox("fake.Id");
element.ValueAttributeShouldEqual(fake.Id.ToString());
}
[Test]
public void can_get_searchbox_with_value()
{
var element = target.SearchBox("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_rangebox_with_value()
{
var element = target.RangeBox("fake.Id");
element.ValueAttributeShouldEqual(fake.Id.ToString());
}
[Test]
public void can_get_telephonebox_with_value()
{
var element = target.TelephoneBox("fake.TelephoneNumber");
element.ValueAttributeShouldEqual(fake.TelephoneNumber);
}
[Test]
public void can_get_datepicker_with_value()
{
var element = target.DatePicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_monthpicker_with_value()
{
var element = target.MonthPicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_weekpicker_with_value()
{
var element = target.WeekPicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_datetimepicker_with_value()
{
var element = target.DateTimePicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_datetimelocalpicker_with_value()
{
var element = target.DateTimeLocalPicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_timepicker_with_value()
{
var element = target.TimePicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_colorpicker_with_value()
{
var element = target.ColorPicker("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_urlbox_with_value()
{
var element = target.UrlBox("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_emailbox_with_value()
{
var element = target.EmailBox("fake.Title");
element.ValueAttributeShouldEqual(fake.Title);
}
[Test]
public void can_get_datalist()
{
var element = target.DataList("x");
element.ShouldNotBeNull();
}
}
}
| 24.350554 | 78 | 0.714805 | [
"Apache-2.0"
] | joaofx/mvccontrib | src/MVCContrib.UnitTests/FluentHtml/ViewDataContainerExtensionsTests.cs | 6,599 | C# |
namespace TeleConsult.Data.Repositories
{
using System.Linq;
using Microsoft.Practices.Unity;
using TeleConsult.Data.Models;
public class DiagnosisRepository : BaseRepository<Diagnosis>
{
[InjectionConstructor]
public DiagnosisRepository(ITeleConsultDbContext context)
: base(context)
{
}
public string GetDiagnosisByCode(string code)
{
var result = this.All().FirstOrDefault(d => d.Code == code);
if (result != null)
{
return result.Description;
}
return string.Empty;
}
}
}
| 23.25 | 72 | 0.574501 | [
"MIT"
] | penjurov/TeleConsult | Data/TeleConsult.Data/Repositories/DiagnosisRepository.cs | 653 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Lamar.IoC.Frames;
using Lamar.IoC.Resolvers;
using LamarCodeGeneration;
using LamarCodeGeneration.Model;
using Microsoft.Extensions.DependencyInjection;
using LamarCodeGeneration.Util;
namespace Lamar.IoC.Instances
{
public abstract class Instance
{
public abstract Func<Scope, object> ToResolver(Scope topScope);
public bool IsOnlyOneOfServiceType { get; set; }
public ServiceDescriptor ToDescriptor()
{
return new ServiceDescriptor(ServiceType, this);
}
public string DefaultArgName()
{
var argName = Variable.DefaultArgName(ServiceType);
if (ServiceType.IsGenericType)
{
argName += "_of_" + ServiceType.GetGenericArguments().Select(t => t.NameInCode().Sanitize()).Join("_");
}
return IsOnlyOneOfServiceType ? argName : argName + HashCode(ServiceType, Name).ToString().Replace("-", "_");
}
internal IEnumerable<Assembly> ReferencedAssemblies()
{
yield return ServiceType.Assembly;
yield return ImplementationType.Assembly;
if (ServiceType.IsGenericType)
{
foreach (var type in ServiceType.GetGenericArguments())
{
yield return type.Assembly;
}
}
if (ImplementationType.IsGenericType)
{
foreach (var type in ImplementationType.GetGenericArguments())
{
yield return type.Assembly;
}
}
}
public Type ServiceType { get; }
public Type ImplementationType { get; }
public static Instance For(ServiceDescriptor service)
{
if (service.ImplementationInstance is Instance instance) return instance;
if (service.ImplementationInstance != null) return new ObjectInstance(service.ServiceType, service.ImplementationInstance);
if (service.ImplementationFactory != null) return new LambdaInstance(service.ServiceType, service.ImplementationFactory, service.Lifetime);
return new ConstructorInstance(service.ServiceType, service.ImplementationType, service.Lifetime);
}
public static bool CanBeCastTo(Type implementationType, Type serviceType)
{
if (implementationType == null) return false;
if (implementationType == serviceType) return true;
if (serviceType.IsOpenGeneric())
{
return GenericsPluginGraph.CanBeCast(serviceType, implementationType);
}
if (implementationType.IsOpenGeneric())
{
return false;
}
return serviceType.GetTypeInfo().IsAssignableFrom(implementationType.GetTypeInfo());
}
protected Instance(Type serviceType, Type implementationType, ServiceLifetime lifetime)
{
if (!CanBeCastTo(implementationType, serviceType))
{
throw new ArgumentOutOfRangeException(nameof(implementationType), $"{implementationType.FullNameInCode()} cannot be cast to {serviceType.FullNameInCode()}");
}
ServiceType = serviceType;
Lifetime = lifetime;
ImplementationType = implementationType;
Name = "default";
}
public abstract object Resolve(Scope scope);
/// <summary>
/// Resolve the service as if it were only going to ever be resolved once
/// </summary>
/// <param name="scope"></param>
/// <returns></returns>
public virtual object QuickResolve(Scope scope)
{
return Resolve(scope);
}
public int Hash { get; set; }
public virtual bool RequiresServiceProvider => Dependencies.Any(x => x.RequiresServiceProvider);
public ServiceLifetime Lifetime { get; set; } = ServiceLifetime.Transient;
public string Name
{
get => _name;
set
{
_name = value;
Hash = GetHashCode();
}
}
public bool HasPlanned { get; protected internal set; }
public bool PlanningSucceeded { get; protected internal set; }
public void CreatePlan(ServiceGraph services)
{
if (HasPlanned) return;
try
{
services.StartingToPlan(this);
}
catch (Exception e)
{
ErrorMessages.Add(e.Message);
services.FinishedPlanning();
HasPlanned = true;
return;
}
// Can't do the planning on open generic types 'cause bad stuff happens
if (!ServiceType.IsOpenGeneric())
{
foreach (var policy in services.InstancePolicies)
{
policy.Apply(this);
}
var atts = ImplementationType.GetAllAttributes<LamarAttribute>();
foreach (var att in atts)
{
att.Alter(this);
if (this is IConfiguredInstance)
{
att.Alter(this.As<IConfiguredInstance>());
}
}
var dependencies = createPlan(services) ?? Enumerable.Empty<Instance>();
if (dependencies.Any(x => x.Dependencies.Contains(this)))
{
throw new InvalidOperationException("Bi-directional dependencies detected to " + ToString());
}
Dependencies = dependencies.Concat(dependencies.SelectMany(x => x.Dependencies)).Distinct().ToArray();
}
services.ClearPlanning();
PlanningSucceeded = ErrorMessages.Count == 0;
HasPlanned = true;
}
public virtual void Reset()
{
HasPlanned = false;
PlanningSucceeded = false;
ErrorMessages.Clear();
}
public abstract Variable CreateVariable(BuildMode mode, ResolverVariables variables, bool isRoot);
public virtual Variable CreateInlineVariable(ResolverVariables variables)
{
return CreateVariable(BuildMode.Dependency, variables, false);
}
protected virtual IEnumerable<Instance> createPlan(ServiceGraph services)
{
return Enumerable.Empty<Instance>();
}
public readonly IList<string> ErrorMessages = new List<string>();
private string _name = "default";
public Instance[] Dependencies { get; protected set; } = new Instance[0];
/// <summary>
/// Is this instance known to be dependent upon the dependencyType?
/// </summary>
/// <param name="dependencyType"></param>
/// <returns></returns>
public bool DependsOn(Type dependencyType)
{
return Dependencies.Any(x => x.ServiceType == dependencyType || x.ImplementationType == dependencyType);
}
public bool IsDefault { get; set; } = false;
protected bool tryGetService(Scope scope, out object service)
{
return scope.Services.TryGetValue(Hash, out service);
}
protected void store(Scope scope, object service)
{
scope.Services.Add(Hash, service);
}
/// <summary>
/// Tries to describe how this instance would be resolved at runtime
/// </summary>
/// <param name="rootScope"></param>
internal virtual string GetBuildPlan(Scope rootScope) => ToString();
public sealed override int GetHashCode()
{
unchecked
{
return HashCode(ServiceType, Name);
}
}
public static int HashCode(Type serviceType, string name = null)
{
return (serviceType.GetHashCode() * 397) ^ (name ?? "default").GetHashCode();
}
public virtual Instance CloseType(Type serviceType, Type[] templateTypes)
{
return null;
}
/// <summary>
/// Only used to track naming within inline dependencies
/// </summary>
internal Instance Parent { get; set; }
public bool IsInlineDependency()
{
return Parent != null;
}
protected string inlineSetterName()
{
var name = Name;
var parent = Parent;
while (parent != null)
{
name = parent.Name + "_" + name;
parent = parent.Parent;
}
return "func_" + name.Sanitize();
}
}
}
| 30.910653 | 173 | 0.561089 | [
"MIT"
] | AaronAllBright/lamar | src/Lamar/IoC/Instances/Instance.cs | 8,997 | C# |
//
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Vladimir Krasnov <vladimirk@mainsoft.com>
//
//
// Copyright (c) 2002-2005 Mainsoft Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace GHTTests.System_Web_dll.System_Web_UI_WebControls
{
public class DataGrid_UpdateCommandName
: GHTBaseWeb
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected GHTWebControls.GHTSubTest GHTSubTest1;
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Page_Load(object sender, System.EventArgs e)
{
//Put user code to initialize the page here
System.Web.UI.HtmlControls.HtmlForm frm = (HtmlForm)this.FindControl("Form1");
GHTTestBegin(frm);
GHTActiveSubTest = GHTSubTest1;
try
{
GHTSubTestAddResult(DataGrid.UpdateCommandName);
}
catch (Exception ex)
{
GHTSubTestUnexpectedExceptionCaught(ex);
}
GHTTestEnd();
}
}
}
| 29.860465 | 81 | 0.73053 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Web/Test/mainsoft/MainsoftWebApp/System_Web_UI_WebControls/DataGrid/DataGrid_UpdateCommandName.aspx.cs | 2,568 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.Distance_Between_Points
{
class Program
{
static void Main(string[] args)
{
var point1 = Console.ReadLine()
.Split(' ')
.Select(double.Parse)
.ToArray();
var point2 = Console.ReadLine()
.Split(' ')
.Select(double.Parse)
.ToArray();
Point p1 = new Point();
p1.X = point1[0];
p1.Y = point1[1];
Point p2 = new Point();
p2.X = point2[0];
p2.Y = point2[1];
Console.WriteLine($"{Point.CalcDistance(p1, p2):F3}");
}
//class Point
//{
// public double X { get; set; }
// public double Y { get; set; }
// static public double CalcDistance(Point p1, Point p2)
// {
// var sideA = Math.Pow(p1.X - p2.X, 2);
// var sideB = Math.Pow(p1.Y - p2.Y, 2);
// return Math.Sqrt(sideA + sideB);
// }
//}
}
}
| 27.511628 | 67 | 0.457312 | [
"MIT"
] | DimovDimo/softuni-00-programming-fundamentals-january-2018 | 17.OBJECTS AND CLASSES/17.OBJECTS AND CLASS/04. Distance Between Points/04. Distance Between Points.cs | 1,185 | C# |
using System;
namespace Zephyr.Data
{
internal partial class DbCommand
{
public T ExecuteReturnLastId<T>(string identityColumnName = null)
{
if (Data.Context.Data.Provider.RequiresIdentityColumn && string.IsNullOrEmpty(identityColumnName))
throw new FluentDataException("The identity column must be given");
var value = Data.Context.Data.Provider.ExecuteReturnLastId<T>(this, identityColumnName);
T lastId;
if (value.GetType() == typeof(T))
lastId = (T)value;
else
lastId = (T)Convert.ChangeType(value, typeof(T));
return lastId;
}
}
}
| 24.166667 | 101 | 0.72069 | [
"MIT"
] | zhupangithub/WEBERP | Code/Zephyr.Net/Zephyr.Data/Command/PartialClasses/ExecuteReturnLastId.cs | 582 | 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.Text;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class BringUpTest
{
const int Pass = 100;
const int Fail = -1;
public static int Main()
{
if (TestInterfaceCache() == Fail)
return Fail;
if (TestAVInInterfaceCache() == Fail)
return Fail;
if (TestMultipleInterfaces() == Fail)
return Fail;
if (TestArrayInterfaces() == Fail)
return Fail;
if (TestVariantInterfaces() == Fail)
return Fail;
if (TestSpecialArrayInterfaces() == Fail)
return Fail;
if (TestIterfaceCallOptimization() == Fail)
return Fail;
TestDefaultInterfaceMethods.Run();
TestDefaultInterfaceVariance.Run();
TestVariantInterfaceOptimizations.Run();
TestSharedIntefaceMethods.Run();
TestCovariantReturns.Run();
TestDynamicInterfaceCastable.Run();
return Pass;
}
private static MyInterface[] MakeInterfaceArray()
{
MyInterface[] itfs = new MyInterface[50];
itfs[0] = new Foo0();
itfs[1] = new Foo1();
itfs[2] = new Foo2();
itfs[3] = new Foo3();
itfs[4] = new Foo4();
itfs[5] = new Foo5();
itfs[6] = new Foo6();
itfs[7] = new Foo7();
itfs[8] = new Foo8();
itfs[9] = new Foo9();
itfs[10] = new Foo10();
itfs[11] = new Foo11();
itfs[12] = new Foo12();
itfs[13] = new Foo13();
itfs[14] = new Foo14();
itfs[15] = new Foo15();
itfs[16] = new Foo16();
itfs[17] = new Foo17();
itfs[18] = new Foo18();
itfs[19] = new Foo19();
itfs[20] = new Foo20();
itfs[21] = new Foo21();
itfs[22] = new Foo22();
itfs[23] = new Foo23();
itfs[24] = new Foo24();
itfs[25] = new Foo25();
itfs[26] = new Foo26();
itfs[27] = new Foo27();
itfs[28] = new Foo28();
itfs[29] = new Foo29();
itfs[30] = new Foo30();
itfs[31] = new Foo31();
itfs[32] = new Foo32();
itfs[33] = new Foo33();
itfs[34] = new Foo34();
itfs[35] = new Foo35();
itfs[36] = new Foo36();
itfs[37] = new Foo37();
itfs[38] = new Foo38();
itfs[39] = new Foo39();
itfs[40] = new Foo40();
itfs[41] = new Foo41();
itfs[42] = new Foo42();
itfs[43] = new Foo43();
itfs[44] = new Foo44();
itfs[45] = new Foo45();
itfs[46] = new Foo46();
itfs[47] = new Foo47();
itfs[48] = new Foo48();
itfs[49] = new Foo49();
return itfs;
}
#region Interface Dispatch Cache Test
private static int TestInterfaceCache()
{
MyInterface[] itfs = MakeInterfaceArray();
StringBuilder sb = new StringBuilder();
int counter = 0;
for (int i = 0; i < 50; i++)
{
sb.Append(itfs[i].GetAString());
counter += itfs[i].GetAnInt();
}
string expected = "Foo0Foo1Foo2Foo3Foo4Foo5Foo6Foo7Foo8Foo9Foo10Foo11Foo12Foo13Foo14Foo15Foo16Foo17Foo18Foo19Foo20Foo21Foo22Foo23Foo24Foo25Foo26Foo27Foo28Foo29Foo30Foo31Foo32Foo33Foo34Foo35Foo36Foo37Foo38Foo39Foo40Foo41Foo42Foo43Foo44Foo45Foo46Foo47Foo48Foo49";
if (!expected.Equals(sb.ToString()))
{
Console.WriteLine("Concatenating strings from interface calls failed.");
Console.Write("Expected: ");
Console.WriteLine(expected);
Console.Write(" Actual: ");
Console.WriteLine(sb.ToString());
return Fail;
}
if (counter != 1225)
{
Console.WriteLine("Summing ints from interface calls failed.");
Console.WriteLine("Expected: 1225");
Console.Write("Actual: ");
Console.WriteLine(counter);
return Fail;
}
return 100;
}
private static int TestAVInInterfaceCache()
{
MyInterface[] itfs = MakeInterfaceArray();
MyInterface[] testArray = new MyInterface[itfs.Length * 2];
for (int i = 0; i < itfs.Length; i++)
{
testArray[i * 2 + 1] = itfs[i];
}
int numExceptions = 0;
// Make sure AV in dispatch helpers is translated to NullRef
for (int i = 0; i < testArray.Length; i++)
{
try
{
testArray[i].GetAnInt();
}
catch (NullReferenceException)
{
numExceptions++;
}
}
// Make sure there's no trouble with unwinding out of the dispatch helper
InterfaceWithManyParameters testInstance = null;
for (int i = 0; i < 3; i++)
{
try
{
testInstance.ManyParameters(0, 0, 0, 0, 0, 0, 0, 0);
}
catch (NullReferenceException)
{
numExceptions++;
}
if (testInstance == null)
testInstance = new ClassWithManyParameters();
else
testInstance = null;
}
return numExceptions == itfs.Length + 2 ? Pass : Fail;
}
interface MyInterface
{
int GetAnInt();
string GetAString();
}
interface InterfaceWithManyParameters
{
int ManyParameters(int a, int b, int c, int d, int e, int f, int g, int h);
}
class ClassWithManyParameters : InterfaceWithManyParameters
{
public int ManyParameters(int a, int b, int c, int d, int e, int f, int g, int h) => 42;
}
class Foo0 : MyInterface { public int GetAnInt() { return 0; } public string GetAString() { return "Foo0"; } }
class Foo1 : MyInterface { public int GetAnInt() { return 1; } public string GetAString() { return "Foo1"; } }
class Foo2 : MyInterface { public int GetAnInt() { return 2; } public string GetAString() { return "Foo2"; } }
class Foo3 : MyInterface { public int GetAnInt() { return 3; } public string GetAString() { return "Foo3"; } }
class Foo4 : MyInterface { public int GetAnInt() { return 4; } public string GetAString() { return "Foo4"; } }
class Foo5 : MyInterface { public int GetAnInt() { return 5; } public string GetAString() { return "Foo5"; } }
class Foo6 : MyInterface { public int GetAnInt() { return 6; } public string GetAString() { return "Foo6"; } }
class Foo7 : MyInterface { public int GetAnInt() { return 7; } public string GetAString() { return "Foo7"; } }
class Foo8 : MyInterface { public int GetAnInt() { return 8; } public string GetAString() { return "Foo8"; } }
class Foo9 : MyInterface { public int GetAnInt() { return 9; } public string GetAString() { return "Foo9"; } }
class Foo10 : MyInterface { public int GetAnInt() { return 10; } public string GetAString() { return "Foo10"; } }
class Foo11 : MyInterface { public int GetAnInt() { return 11; } public string GetAString() { return "Foo11"; } }
class Foo12 : MyInterface { public int GetAnInt() { return 12; } public string GetAString() { return "Foo12"; } }
class Foo13 : MyInterface { public int GetAnInt() { return 13; } public string GetAString() { return "Foo13"; } }
class Foo14 : MyInterface { public int GetAnInt() { return 14; } public string GetAString() { return "Foo14"; } }
class Foo15 : MyInterface { public int GetAnInt() { return 15; } public string GetAString() { return "Foo15"; } }
class Foo16 : MyInterface { public int GetAnInt() { return 16; } public string GetAString() { return "Foo16"; } }
class Foo17 : MyInterface { public int GetAnInt() { return 17; } public string GetAString() { return "Foo17"; } }
class Foo18 : MyInterface { public int GetAnInt() { return 18; } public string GetAString() { return "Foo18"; } }
class Foo19 : MyInterface { public int GetAnInt() { return 19; } public string GetAString() { return "Foo19"; } }
class Foo20 : MyInterface { public int GetAnInt() { return 20; } public string GetAString() { return "Foo20"; } }
class Foo21 : MyInterface { public int GetAnInt() { return 21; } public string GetAString() { return "Foo21"; } }
class Foo22 : MyInterface { public int GetAnInt() { return 22; } public string GetAString() { return "Foo22"; } }
class Foo23 : MyInterface { public int GetAnInt() { return 23; } public string GetAString() { return "Foo23"; } }
class Foo24 : MyInterface { public int GetAnInt() { return 24; } public string GetAString() { return "Foo24"; } }
class Foo25 : MyInterface { public int GetAnInt() { return 25; } public string GetAString() { return "Foo25"; } }
class Foo26 : MyInterface { public int GetAnInt() { return 26; } public string GetAString() { return "Foo26"; } }
class Foo27 : MyInterface { public int GetAnInt() { return 27; } public string GetAString() { return "Foo27"; } }
class Foo28 : MyInterface { public int GetAnInt() { return 28; } public string GetAString() { return "Foo28"; } }
class Foo29 : MyInterface { public int GetAnInt() { return 29; } public string GetAString() { return "Foo29"; } }
class Foo30 : MyInterface { public int GetAnInt() { return 30; } public string GetAString() { return "Foo30"; } }
class Foo31 : MyInterface { public int GetAnInt() { return 31; } public string GetAString() { return "Foo31"; } }
class Foo32 : MyInterface { public int GetAnInt() { return 32; } public string GetAString() { return "Foo32"; } }
class Foo33 : MyInterface { public int GetAnInt() { return 33; } public string GetAString() { return "Foo33"; } }
class Foo34 : MyInterface { public int GetAnInt() { return 34; } public string GetAString() { return "Foo34"; } }
class Foo35 : MyInterface { public int GetAnInt() { return 35; } public string GetAString() { return "Foo35"; } }
class Foo36 : MyInterface { public int GetAnInt() { return 36; } public string GetAString() { return "Foo36"; } }
class Foo37 : MyInterface { public int GetAnInt() { return 37; } public string GetAString() { return "Foo37"; } }
class Foo38 : MyInterface { public int GetAnInt() { return 38; } public string GetAString() { return "Foo38"; } }
class Foo39 : MyInterface { public int GetAnInt() { return 39; } public string GetAString() { return "Foo39"; } }
class Foo40 : MyInterface { public int GetAnInt() { return 40; } public string GetAString() { return "Foo40"; } }
class Foo41 : MyInterface { public int GetAnInt() { return 41; } public string GetAString() { return "Foo41"; } }
class Foo42 : MyInterface { public int GetAnInt() { return 42; } public string GetAString() { return "Foo42"; } }
class Foo43 : MyInterface { public int GetAnInt() { return 43; } public string GetAString() { return "Foo43"; } }
class Foo44 : MyInterface { public int GetAnInt() { return 44; } public string GetAString() { return "Foo44"; } }
class Foo45 : MyInterface { public int GetAnInt() { return 45; } public string GetAString() { return "Foo45"; } }
class Foo46 : MyInterface { public int GetAnInt() { return 46; } public string GetAString() { return "Foo46"; } }
class Foo47 : MyInterface { public int GetAnInt() { return 47; } public string GetAString() { return "Foo47"; } }
class Foo48 : MyInterface { public int GetAnInt() { return 48; } public string GetAString() { return "Foo48"; } }
class Foo49 : MyInterface { public int GetAnInt() { return 49; } public string GetAString() { return "Foo49"; } }
#endregion
#region Implicit Interface Test
private static int TestMultipleInterfaces()
{
TestClass<int> testInt = new TestClass<int>(5);
MyInterface myInterface = testInt as MyInterface;
if (!myInterface.GetAString().Equals("TestClass"))
{
Console.Write("On type TestClass, MyInterface.GetAString() returned ");
Console.Write(myInterface.GetAString());
Console.WriteLine(" Expected: TestClass");
return Fail;
}
if (myInterface.GetAnInt() != 1)
{
Console.Write("On type TestClass, MyInterface.GetAnInt() returned ");
Console.Write(myInterface.GetAnInt());
Console.WriteLine(" Expected: 1");
return Fail;
}
Interface<int> itf = testInt as Interface<int>;
if (itf.GetT() != 5)
{
Console.Write("On type TestClass, Interface<int>::GetT() returned ");
Console.Write(itf.GetT());
Console.WriteLine(" Expected: 5");
return Fail;
}
return Pass;
}
interface Interface<T>
{
T GetT();
}
class TestClass<T> : MyInterface, Interface<T>
{
T _t;
public TestClass(T t)
{
_t = t;
}
public T GetT()
{
return _t;
}
public int GetAnInt()
{
return 1;
}
public string GetAString()
{
return "TestClass";
}
}
#endregion
#region Array Interfaces Test
private static int TestArrayInterfaces()
{
{
object stringArray = new string[] { "A", "B", "C", "D" };
Console.WriteLine("Testing IEnumerable<T> on array...");
string result = String.Empty;
foreach (var s in (System.Collections.Generic.IEnumerable<string>)stringArray)
result += s;
if (result != "ABCD")
{
Console.WriteLine("Failed.");
return Fail;
}
}
{
object stringArray = new string[] { "A", "B", "C", "D" };
Console.WriteLine("Testing IEnumerable on array...");
string result = String.Empty;
foreach (var s in (System.Collections.IEnumerable)stringArray)
result += s;
if (result != "ABCD")
{
Console.WriteLine("Failed.");
return Fail;
}
}
{
object intArray = new int[5, 5];
Console.WriteLine("Testing IList on MDArray...");
if (((System.Collections.IList)intArray).Count != 25)
{
Console.WriteLine("Failed.");
return Fail;
}
}
return Pass;
}
#endregion
#region Variant interface tests
interface IContravariantInterface<in T>
{
string DoContravariant(T value);
}
interface ICovariantInterface<out T>
{
T DoCovariant(object value);
}
class TypeWithVariantInterfaces<T> : IContravariantInterface<T>, ICovariantInterface<T>
{
public string DoContravariant(T value)
{
return value.ToString();
}
public T DoCovariant(object value)
{
return value is T ? (T)value : default(T);
}
}
static IContravariantInterface<string> s_contravariantObject = new TypeWithVariantInterfaces<object>();
static ICovariantInterface<object> s_covariantObject = new TypeWithVariantInterfaces<string>();
static IEnumerable<int> s_arrayCovariantObject = (IEnumerable<int>)(object)new uint[] { 5, 10, 15 };
private static int TestVariantInterfaces()
{
if (s_contravariantObject.DoContravariant("Hello") != "Hello")
return Fail;
if (s_covariantObject.DoCovariant("World") as string != "World")
return Fail;
int sum = 0;
foreach (var e in s_arrayCovariantObject)
sum += e;
if (sum != 30)
return Fail;
return Pass;
}
class SpecialArrayBase { }
class SpecialArrayDerived : SpecialArrayBase { }
// NOTE: ICollection is not a variant interface, but arrays can cast with it as if it was
static ICollection<SpecialArrayBase> s_specialDerived = new SpecialArrayDerived[42];
static ICollection<uint> s_specialInt = (ICollection<uint>)(object)new int[85];
private static int TestSpecialArrayInterfaces()
{
if (s_specialDerived.Count != 42)
return Fail;
if (s_specialInt.Count != 85)
return Fail;
return Pass;
}
#endregion
#region Interface call optimization tests
public interface ISomeInterface
{
int SomeValue { get; }
}
public abstract class SomeAbstractBaseClass : ISomeInterface
{
public abstract int SomeValue { get; }
}
public class SomeClass : SomeAbstractBaseClass
{
public override int SomeValue
{
[MethodImpl(MethodImplOptions.NoInlining)]
get { return 14; }
}
}
private static int TestIterfaceCallOptimization()
{
ISomeInterface test = new SomeClass();
int v = test.SomeValue;
return (v == 14) ? Pass : Fail;
}
#endregion
class TestDefaultInterfaceMethods
{
interface IFoo
{
int GetNumber() => 42;
}
interface IBar : IFoo
{
int IFoo.GetNumber() => 43;
}
class Foo : IFoo { }
class Bar : IBar { }
class Baz : IFoo
{
public int GetNumber() => 100;
}
interface IFoo<T>
{
Type GetInterfaceType() => typeof(IFoo<T>);
}
class Foo<T> : IFoo<T> { }
public static void Run()
{
Console.WriteLine("Testing default interface methods...");
if (((IFoo)new Foo()).GetNumber() != 42)
throw new Exception();
if (((IFoo)new Bar()).GetNumber() != 43)
throw new Exception();
if (((IFoo)new Baz()).GetNumber() != 100)
throw new Exception();
if (((IFoo<object>)new Foo<object>()).GetInterfaceType() != typeof(IFoo<object>))
throw new Exception();
if (((IFoo<int>)new Foo<int>()).GetInterfaceType() != typeof(IFoo<int>))
throw new Exception();
}
}
class TestDefaultInterfaceVariance
{
class Foo : IVariant<string>, IVariant<object>
{
string IVariant<object>.Frob() => "Hello class";
}
interface IVariant<in T>
{
string Frob() => "Hello default";
}
public static void Run()
{
Console.WriteLine("Testing default interface variant ordering...");
if (((IVariant<object>)new Foo()).Frob() != "Hello class")
throw new Exception();
if (((IVariant<string>)new Foo()).Frob() != "Hello class")
throw new Exception();
if (((IVariant<ValueType>)new Foo()).Frob() != "Hello class")
throw new Exception();
}
}
class TestSharedIntefaceMethods
{
interface IInnerValueGrabber
{
string GetInnerValue();
}
interface IFace<T> : IInnerValueGrabber
{
string GrabValue(T x) => $"'{GetInnerValue()}' over '{typeof(T)}' with '{x}'";
}
class Base<T> : IFace<T>, IInnerValueGrabber
{
public string InnerValue;
public string GetInnerValue() => InnerValue;
}
class Derived<T, U> : Base<T>, IFace<U> { }
struct Yadda : IFace<object>, IInnerValueGrabber
{
public string InnerValue;
public string GetInnerValue() => InnerValue;
}
class Atom1 { public override string ToString() => "The Atom1"; }
class Atom2 { public override string ToString() => "The Atom2"; }
public static void Run()
{
Console.WriteLine("Testing default interface methods and shared code...");
var x = new Derived<Atom1, Atom2>() { InnerValue = "My inner value" };
string r1 = ((IFace<Atom1>)x).GrabValue(new Atom1());
if (r1 != "'My inner value' over 'BringUpTest+TestSharedIntefaceMethods+Atom1' with 'The Atom1'")
throw new Exception();
string r2 = ((IFace<Atom2>)x).GrabValue(new Atom2());
if (r2 != "'My inner value' over 'BringUpTest+TestSharedIntefaceMethods+Atom2' with 'The Atom2'")
throw new Exception();
IFace<object> o = new Yadda() { InnerValue = "SomeString" };
string r3 = o.GrabValue("Hello there");
if (r3 != "'SomeString' over 'System.Object' with 'Hello there'")
throw new Exception();
}
}
class TestCovariantReturns
{
interface IFoo
{
}
class Foo : IFoo
{
public readonly string State;
public Foo(string state) => State = state;
}
class Base
{
public virtual IFoo GetFoo() => throw new NotImplementedException();
}
class Derived : Base
{
public override Foo GetFoo() => new Foo("Derived");
}
class SuperDerived : Derived
{
public override Foo GetFoo() => new Foo("SuperDerived");
}
class BaseWithUnusedVirtual
{
public virtual IFoo GetFoo() => throw new NotImplementedException();
}
class DerivedWithOverridenUnusedVirtual : BaseWithUnusedVirtual
{
public override Foo GetFoo() => new Foo("DerivedWithOverridenUnusedVirtual");
}
class SuperDerivedWithOverridenUnusedVirtual : DerivedWithOverridenUnusedVirtual
{
public override Foo GetFoo() => new Foo("SuperDerivedWithOverridenUnusedVirtual");
}
interface IInterfaceWithCovariantReturn
{
IFoo GetFoo();
}
class ClassImplementingInterface : IInterfaceWithCovariantReturn
{
public virtual IFoo GetFoo() => throw new NotImplementedException();
}
class DerivedClassImplementingInterface : ClassImplementingInterface
{
public override Foo GetFoo() => new Foo("DerivedClassImplementingInterface");
}
public static void Run()
{
Console.WriteLine("Testing covariant returns...");
{
Base b = new Derived();
if (((Foo)b.GetFoo()).State != "Derived")
throw new Exception();
}
{
Base b = new SuperDerived();
if (((Foo)b.GetFoo()).State != "SuperDerived")
throw new Exception();
}
{
Derived d = new SuperDerived();
if (d.GetFoo().State != "SuperDerived")
throw new Exception();
}
{
DerivedWithOverridenUnusedVirtual b = new DerivedWithOverridenUnusedVirtual();
if (b.GetFoo().State != "DerivedWithOverridenUnusedVirtual")
throw new Exception();
}
{
DerivedWithOverridenUnusedVirtual b = new SuperDerivedWithOverridenUnusedVirtual();
if (b.GetFoo().State != "SuperDerivedWithOverridenUnusedVirtual")
throw new Exception();
}
{
IInterfaceWithCovariantReturn i = new DerivedClassImplementingInterface();
if (((Foo)i.GetFoo()).State != "DerivedClassImplementingInterface")
throw new Exception();
}
}
}
class TestVariantInterfaceOptimizations
{
static IEnumerable<Other> s_others = (IEnumerable<Other>)(object)new This[3] { (This)33, (This)66, (This)1 };
enum This : sbyte { }
enum Other : sbyte { }
sealed class MySealedClass { }
interface IContravariantInterface<in T>
{
string DoContravariant(T value);
}
interface ICovariantInterface<out T>
{
T DoCovariant(object value);
}
class CoAndContravariantOverSealed : IContravariantInterface<object>, ICovariantInterface<MySealedClass>
{
public string DoContravariant(object value) => "Hello";
public MySealedClass DoCovariant(object value) => null;
}
public static void Run()
{
Console.WriteLine("Testing variant optimizations...");
int sum = 0;
foreach (var other in s_others)
{
sum += (int)other;
}
if (sum != 100)
throw new Exception();
ICovariantInterface<object> i1 = new CoAndContravariantOverSealed();
i1.DoCovariant(null);
IContravariantInterface<MySealedClass> i2 = new CoAndContravariantOverSealed();
i2.DoContravariant(null);
}
}
class TestDynamicInterfaceCastable
{
class CastableClass<TInterface, TImpl> : IDynamicInterfaceCastable
{
RuntimeTypeHandle IDynamicInterfaceCastable.GetInterfaceImplementation(RuntimeTypeHandle interfaceType)
=> interfaceType.Equals(typeof(TInterface).TypeHandle) ? typeof(TImpl).TypeHandle : default;
bool IDynamicInterfaceCastable.IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented)
=> interfaceType.Equals(typeof(TInterface).TypeHandle);
}
interface IInterface
{
string GetCookie();
}
[DynamicInterfaceCastableImplementation]
interface IInterfaceCastableImpl : IInterface
{
string IInterface.GetCookie() => "IInterfaceCastableImpl";
}
[DynamicInterfaceCastableImplementation]
interface IInterfaceCastableImpl<T> : IInterface
{
string IInterface.GetCookie() => typeof(T).Name;
}
interface IInterfaceImpl : IInterface
{
string IInterface.GetCookie() => "IInterfaceImpl";
}
[DynamicInterfaceCastableImplementation]
interface IInterfaceIndirectCastableImpl : IInterfaceImpl { }
public static void Run()
{
Console.WriteLine("Testing IDynamicInterfaceCastable...");
{
IInterface o = (IInterface)new CastableClass<IInterface, IInterfaceCastableImpl>();
if (o.GetCookie() != "IInterfaceCastableImpl")
throw new Exception();
}
{
IInterface o = (IInterface)new CastableClass<IInterface, IInterfaceImpl>();
bool success = false;
try
{
o.GetCookie();
}
catch (InvalidOperationException)
{
success = true;
}
if (!success)
throw new Exception();
}
{
IInterface o = (IInterface)new CastableClass<IInterface, IInterfaceIndirectCastableImpl>();
if (o.GetCookie() != "IInterfaceImpl")
throw new Exception();
}
{
IInterface o = (IInterface)new CastableClass<IInterface, IInterfaceCastableImpl<int>>();
if (o.GetCookie() != "Int32")
throw new Exception();
}
}
}
}
| 34.124384 | 269 | 0.566819 | [
"MIT"
] | 333fred/runtime | src/tests/nativeaot/SmokeTests/Interfaces/Interfaces.cs | 27,709 | C# |
using TMPro;
using UnityEngine;
namespace AdrianKovatana
{
public class GameTimerUI : MonoBehaviour
{
#pragma warning disable
[SerializeField]
private FloatVariable _currentTime;
[Header("UI Text")]
[SerializeField]
private TextMeshProUGUI _textHours;
[SerializeField]
private TextMeshProUGUI _textMinutes;
[SerializeField]
private TextMeshProUGUI _textSeconds;
[SerializeField]
private TextMeshProUGUI _textMilliseconds;
#pragma warning restore
private void Update()
{
UpdateUI();
}
public void UpdateUI()
{
_textHours.text = GetHours();
_textMinutes.text = ":" + GetMinutes();
_textSeconds.text = ":" + GetSeconds();
_textMilliseconds.text = ":" + GetMilliseconds();
}
public string GetHours()
{
return ((int)(_currentTime.value / 3600f) % 24).ToString("D2");
}
public string GetMinutes()
{
return ((int)(_currentTime.value / 60f) % 60).ToString("D2");
}
public string GetSeconds()
{
return ((int)(_currentTime.value % 60f)).ToString("D2");
}
public string GetMilliseconds()
{
return ((int)(_currentTime.value * 1000f) % 1000).ToString("D3");
}
}
}
| 24.912281 | 77 | 0.555634 | [
"MIT"
] | adriank1/ludum-dare-44 | Ludum Dare 44/Assets/MyAssets/Scripts/GameTimerUI.cs | 1,422 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VpnSitesConfigurationOperations operations.
/// </summary>
internal partial class VpnSitesConfigurationOperations : IServiceOperations<NetworkManagementClient>, IVpnSitesConfigurationOperations
{
/// <summary>
/// Initializes a new instance of the VpnSitesConfigurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VpnSitesConfigurationOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gives the sas-url to download the configurations for vpn-sites in a
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='virtualWANName'>
/// The name of the VirtualWAN for which configuration of all vpn-sites is
/// needed.
/// </param>
/// <param name='request'>
/// Parameters supplied to download vpn-sites configuration.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DownloadWithHttpMessagesAsync(string resourceGroupName, string virtualWANName, GetVpnSitesConfigurationRequest request, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDownloadWithHttpMessagesAsync(resourceGroupName, virtualWANName, request, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gives the sas-url to download the configurations for vpn-sites in a
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='virtualWANName'>
/// The name of the VirtualWAN for which configuration of all vpn-sites is
/// needed.
/// </param>
/// <param name='request'>
/// Parameters supplied to download vpn-sites configuration.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDownloadWithHttpMessagesAsync(string resourceGroupName, string virtualWANName, GetVpnSitesConfigurationRequest request, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualWANName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualWANName");
}
if (request == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "request");
}
if (request != null)
{
request.Validate();
}
string apiVersion = "2019-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualWANName", virtualWANName);
tracingParameters.Add("request", request);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDownload", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualWANName}", System.Uri.EscapeDataString(virtualWANName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(request != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(request, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 45.025455 | 295 | 0.590292 | [
"MIT"
] | HaoQian-MS/azure-sdk-for-net | sdk/network/Microsoft.Azure.Management.Network/src/Generated/VpnSitesConfigurationOperations.cs | 12,382 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Calamari.Commands.Support;
using Calamari.Common.Commands;
using Calamari.Common.Features.Packages;
using Calamari.Common.Features.Packages.NuGet;
using Calamari.Integration.Packages;
using Calamari.Integration.Packages.NuGet;
using Calamari.Tests.Fixtures.Util;
using Calamari.Tests.Helpers;
using NUnit.Framework;
namespace Calamari.Tests.Fixtures.Integration.Packages
{
[TestFixture]
public class CombinedPackageExtractorFixture : CalamariFixture
{
[Test]
[TestCaseSource(nameof(PackageNameTestCases))]
public void GettingFileByExtension(string filename, Type expectedType)
{
var extractor = new CombinedPackageExtractor(new InMemoryLog()).GetExtractor(filename);
Assert.AreEqual(expectedType, extractor.GetType());
}
static IEnumerable<object> PackageNameTestCases()
{
var fileNames = new[]
{
"foo.1.0.0",
"foo.1.0.0-tag",
"foo.1.0.0-tag-release.tag",
"foo.1.0.0+buildmeta",
"foo.1.0.0-tag-release.tag+buildmeta",
};
var extractorMapping = new (string extension, Type extractor)[]
{
("zip", typeof(ZipPackageExtractor)),
("nupkg", typeof(NupkgExtractor)),
("tar", typeof(TarPackageExtractor)),
("tar.gz", typeof(TarGzipPackageExtractor)),
("tar.bz2", typeof(TarBzipPackageExtractor)),
};
foreach (var filename in fileNames)
{
foreach (var (extension, type) in extractorMapping)
{
yield return new TestCaseData($"{filename}.{extension}", type);
}
}
}
[Test]
[ExpectedException(typeof(CommandException), ExpectedMessage = "Package is missing file extension. This is needed to select the correct extraction algorithm.")]
public void FileWithNoExtensionThrowsError()
{
new CombinedPackageExtractor(new InMemoryLog()).GetExtractor("blah");
}
[Test]
[ExpectedException(typeof(CommandException), ExpectedMessage = "Unsupported file extension `.7z`")]
public void FileWithUnsupportedExtensionThrowsError()
{
new CombinedPackageExtractor(new InMemoryLog()).GetExtractor("blah.1.0.0.7z");
}
}
}
| 34.888889 | 168 | 0.61465 | [
"Apache-2.0"
] | lilwa29/Calamari | source/Calamari.Tests/Fixtures/Integration/Packages/CombinedPackageExtractorFixture.cs | 2,514 | C# |
using System;
namespace FishingBoat
{
internal class Program
{
static void Main(string[] args)
{
int budget = int.Parse(Console.ReadLine());
string season = Console.ReadLine();
int fishermanCount = int.Parse(Console.ReadLine());
int boatRent = 0;
double discount = 0;
double extraDiscount = 0;
switch (season)
{
case "Spring":
boatRent = 3000;
break;
case "Summer":
case "Autumn":
boatRent = 4200;
break;
case "Winter":
boatRent = 2600;
break;
}
if (fishermanCount <= 6)
{
discount = 0.1;
}
else if (fishermanCount >= 7 && fishermanCount <= 11)
{
discount = 0.15;
}
else if (fishermanCount >= 12)
{
discount = 0.25;
}
double currentSum = boatRent - (boatRent * discount);
if (fishermanCount % 2 == 0)
{
switch (season)
{
case "Spring":
case "Summer":
case "Winter":
extraDiscount = 0.05;
break;
}
}
double totalSum = currentSum - (currentSum * extraDiscount);
double totalPrice = budget - totalSum;
if (totalPrice < 0)
{
Console.WriteLine($"Not enough money! You need {Math.Abs(totalPrice):f2} leva.");
}
else
{
Console.WriteLine($"Yes! You have {totalPrice:f2} leva left.");
}
}
}
}
| 26.873239 | 97 | 0.394654 | [
"MIT"
] | Ivanazzz/SoftUni-Software-Engineering | CSharp-Programming-Basics/ConditionalStatementsAdvanced/lab/FishingBoat/Program.cs | 1,910 | C# |
using System;
public class PhotonPlayerProperty
{
public static string beard_texture_id = "beard_texture_id";
public static string body_texture = "body_texture";
public static string cape = "cape";
public static string character = "character";
public static string costumeId = "costumeId";
public static string currentLevel = "currentLevel";
public static string customBool = "customBool";
public static string customFloat = "customFloat";
public static string customInt = "customInt";
public static string customString = "customString";
public static string dead = "dead";
public static string deaths = "deaths";
public static string division = "division";
public static string eye_texture_id = "eye_texture_id";
public static string glass_texture_id = "glass_texture_id";
public static string guildName = "guildName";
public static string hair_color1 = "hair_color1";
public static string hair_color2 = "hair_color2";
public static string hair_color3 = "hair_color3";
public static string hairInfo = "hairInfo";
public static string heroCostumeId = "heroCostumeId";
public static string isTitan = "isTitan";
public static string kills = "kills";
public static string max_dmg = "max_dmg";
public static string name = "name";
public static string part_chest_1_object_mesh = "part_chest_1_object_mesh";
public static string part_chest_1_object_texture = "part_chest_1_object_texture";
public static string part_chest_object_mesh = "part_chest_object_mesh";
public static string part_chest_object_texture = "part_chest_object_texture";
public static string part_chest_skinned_cloth_mesh = "part_chest_skinned_cloth_mesh";
public static string part_chest_skinned_cloth_texture = "part_chest_skinned_cloth_texture";
public static string RCBombA = "RCBombA";
public static string RCBombB = "RCBombB";
public static string RCBombG = "RCBombG";
public static string RCBombR = "RCBombR";
public static string RCBombRadius = "RCBombRadius";
public static string RCteam = "RCteam";
public static string sex = "sex";
public static string skin_color = "skin_color";
public static string statACL = "statACL";
public static string statBLA = "statBLA";
public static string statGAS = "statGAS";
public static string statSKILL = "statSKILL";
public static string statSPD = "statSPD";
public static string team = "team";
public static string total_dmg = "total_dmg";
public static string uniform_type = "uniform_type";
}
| 48.037037 | 95 | 0.741712 | [
"MIT"
] | ITALIA195/RC-Mod | RC Mod/PhotonPlayerProperty.cs | 2,594 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.SqlObjects.Visitors
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Cosmos.SqlObjects;
internal sealed class SqlObjectEqualityVisitor : SqlObjectVisitor<SqlObject, bool>
{
public static readonly SqlObjectEqualityVisitor Singleton = new SqlObjectEqualityVisitor();
private SqlObjectEqualityVisitor()
{
}
public override bool Visit(SqlAliasedCollectionExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlAliasedCollectionExpression second))
{
return false;
}
if (!first.Alias.Accept(this, second.Alias))
{
return false;
}
if (!first.Collection.Accept(this, second.Collection))
{
return false;
}
return true;
}
public override bool Visit(SqlArrayCreateScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlArrayCreateScalarExpression second))
{
return false;
}
if (first.Items.Count != second.Items.Count)
{
return false;
}
if (!SequenceEquals(first.Items, second.Items))
{
return false;
}
return true;
}
public override bool Visit(SqlArrayIteratorCollectionExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlArrayIteratorCollectionExpression second))
{
return false;
}
if (!Equals(first.Identifier, second.Identifier))
{
return false;
}
if (!Equals(first.Collection, second.Collection))
{
return false;
}
return true;
}
public override bool Visit(SqlArrayScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlArrayScalarExpression second))
{
return false;
}
if (!Equals(first.SqlQuery, second.SqlQuery))
{
return false;
}
return true;
}
public override bool Visit(SqlBetweenScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlBetweenScalarExpression second))
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
if (first.Not != second.Not)
{
return false;
}
if (!Equals(first.StartInclusive, second.StartInclusive))
{
return false;
}
if (!Equals(first.EndInclusive, second.EndInclusive))
{
return false;
}
return true;
}
public override bool Visit(SqlBinaryScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlBinaryScalarExpression second))
{
return false;
}
if (first.OperatorKind != second.OperatorKind)
{
return false;
}
if (!Equals(first.LeftExpression, second.LeftExpression))
{
return false;
}
if (!Equals(first.RightExpression, second.RightExpression))
{
return false;
}
return true;
}
public override bool Visit(SqlBooleanLiteral first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlBooleanLiteral second))
{
return false;
}
if (first.Value != second.Value)
{
return false;
}
return true;
}
public override bool Visit(SqlCoalesceScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlCoalesceScalarExpression second))
{
return false;
}
if (!Equals(first.Left, second.Left))
{
return false;
}
if (!Equals(first.Right, second.Right))
{
return false;
}
return true;
}
public override bool Visit(SqlConditionalScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlConditionalScalarExpression second))
{
return false;
}
if (!Equals(first.Condition, second.Condition))
{
return false;
}
if (!Equals(first.Consequent, second.Consequent))
{
return false;
}
if (!Equals(first.Alternative, second.Alternative))
{
return false;
}
return true;
}
public override bool Visit(SqlExistsScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlExistsScalarExpression second))
{
return false;
}
if (!Equals(first.Subquery, second.Subquery))
{
return false;
}
return true;
}
public override bool Visit(SqlFromClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlFromClause second))
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
return true;
}
public override bool Visit(SqlFunctionCallScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlFunctionCallScalarExpression second))
{
return false;
}
if (first.IsUdf != second.IsUdf)
{
return false;
}
if (!Equals(first.Name, second.Name))
{
return false;
}
if (!SequenceEquals(first.Arguments, second.Arguments))
{
return false;
}
return true;
}
public override bool Visit(SqlGroupByClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlGroupByClause second))
{
return false;
}
if (first.Expressions.Count != second.Expressions.Count)
{
return false;
}
if (!SequenceEquals(first.Expressions, second.Expressions))
{
return false;
}
return true;
}
public override bool Visit(SqlIdentifier first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlIdentifier second))
{
return false;
}
if (first.Value != second.Value)
{
return false;
}
return true;
}
public override bool Visit(SqlIdentifierPathExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlIdentifierPathExpression second))
{
return false;
}
if (!first.Value.Accept(this, second.Value))
{
return false;
}
if (!first.ParentPath.Accept(this, second.ParentPath))
{
return false;
}
return true;
}
public override bool Visit(SqlInputPathCollection first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlInputPathCollection second))
{
return false;
}
if (!first.Input.Accept(this, second.Input))
{
return false;
}
if (!first.RelativePath.Accept(this, second.RelativePath))
{
return false;
}
return true;
}
public override bool Visit(SqlInScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlInScalarExpression second))
{
return false;
}
if (!Equals(first.Needle, second.Needle))
{
return false;
}
if (first.Not != second.Not)
{
return false;
}
if (!SequenceEquals(first.Haystack, second.Haystack))
{
return false;
}
return true;
}
public override bool Visit(SqlJoinCollectionExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlJoinCollectionExpression second))
{
return false;
}
if (!Equals(first.Left, second.Left))
{
return false;
}
if (!Equals(first.Right, second.Right))
{
return false;
}
return true;
}
public override bool Visit(SqlLimitSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlLimitSpec second))
{
return false;
}
return Equals(first.LimitExpression, second.LimitExpression);
}
public override bool Visit(SqlLiteralScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlLiteralScalarExpression second))
{
return false;
}
return Equals(first.Literal, second.Literal);
}
public override bool Visit(SqlMemberIndexerScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlMemberIndexerScalarExpression second))
{
return false;
}
if (!Equals(first.Member, second.Member))
{
return false;
}
if (!Equals(first.Indexer, second.Indexer))
{
return false;
}
return true;
}
public override bool Visit(SqlNullLiteral first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlNullLiteral second))
{
return false;
}
return true;
}
public override bool Visit(SqlNumberLiteral first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlNumberLiteral second))
{
return false;
}
return first.Value.Equals(second.Value);
}
public override bool Visit(SqlNumberPathExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlNumberPathExpression second))
{
return false;
}
if (!Equals(first.Value, second.Value))
{
return false;
}
return true;
}
public override bool Visit(SqlObjectCreateScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlObjectCreateScalarExpression second))
{
return false;
}
if (first.Properties.Count() != second.Properties.Count())
{
return false;
}
// order of properties does not matter
foreach (SqlObjectProperty property1 in first.Properties)
{
bool found = false;
foreach (SqlObjectProperty property2 in second.Properties)
{
found |= Equals(property1, property2);
}
if (!found)
{
return false;
}
}
return true;
}
public override bool Visit(SqlObjectProperty first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlObjectProperty second))
{
return false;
}
if (!Equals(first.Name, second.Name))
{
return false;
}
if (!Equals(first.Value, second.Value))
{
return false;
}
return true;
}
public override bool Visit(SqlOffsetLimitClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlOffsetLimitClause second))
{
return false;
}
if (!Equals(first.LimitSpec, second.LimitSpec))
{
return false;
}
if (!Equals(first.OffsetSpec, second.OffsetSpec))
{
return false;
}
return true;
}
public override bool Visit(SqlOffsetSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlOffsetSpec second))
{
return false;
}
if (!Equals(first.OffsetExpression, second.OffsetExpression))
{
return false;
}
return true;
}
public override bool Visit(SqlOrderbyClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlOrderbyClause second))
{
return false;
}
if (!SequenceEquals(first.OrderbyItems, second.OrderbyItems))
{
return false;
}
return true;
}
public override bool Visit(SqlOrderByItem first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlOrderByItem second))
{
return false;
}
if (first.IsDescending != second.IsDescending)
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
return true;
}
public override bool Visit(SqlParameter first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlParameter second))
{
return false;
}
if (first.Name != second.Name)
{
return false;
}
return true;
}
public override bool Visit(SqlParameterRefScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlParameterRefScalarExpression second))
{
return false;
}
if (!Equals(first.Parameter, second.Parameter))
{
return false;
}
return true;
}
public override bool Visit(SqlProgram first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlProgram second))
{
return false;
}
if (!Equals(first.Query, second.Query))
{
return false;
}
return true;
}
public override bool Visit(SqlPropertyName first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlPropertyName second))
{
return false;
}
if (first.Value != second.Value)
{
return false;
}
return true;
}
public override bool Visit(SqlPropertyRefScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlPropertyRefScalarExpression second))
{
return false;
}
if (!Equals(first.Identifier, second.Identifier))
{
return false;
}
return true;
}
public override bool Visit(SqlQuery first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlQuery second))
{
return false;
}
if (!first.SelectClause.Accept(this, second.SelectClause))
{
return false;
}
if (!Equals(first.FromClause, second.FromClause))
{
return false;
}
if (!Equals(first.WhereClause, second.WhereClause))
{
return false;
}
if (!Equals(first.GroupByClause, second.GroupByClause))
{
return false;
}
if (!Equals(first.OrderbyClause, second.OrderbyClause))
{
return false;
}
if (!Equals(first.OffsetLimitClause, second.OffsetLimitClause))
{
return false;
}
return true;
}
public override bool Visit(SqlSelectClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSelectClause second))
{
return false;
}
if (first.HasDistinct != second.HasDistinct)
{
return false;
}
if (!Equals(first.SelectSpec, second.SelectSpec))
{
return false;
}
if (!Equals(first.TopSpec, second.TopSpec))
{
return false;
}
return true;
}
public override bool Visit(SqlSelectItem first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSelectItem second))
{
return false;
}
if (!Equals(first.Alias, second.Alias))
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
return true;
}
public override bool Visit(SqlSelectListSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSelectListSpec second))
{
return false;
}
if (!SequenceEquals(first.Items, second.Items))
{
return false;
}
return true;
}
public override bool Visit(SqlSelectStarSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSelectStarSpec second))
{
return false;
}
return true;
}
public override bool Visit(SqlSelectValueSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSelectValueSpec second))
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
return true;
}
public override bool Visit(SqlStringLiteral first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlStringLiteral second))
{
return false;
}
if (first.Value != second.Value)
{
return false;
}
return true;
}
public override bool Visit(SqlStringPathExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlStringPathExpression second))
{
return false;
}
if (!Equals(first.Value, second.Value))
{
return false;
}
if (!Equals(first.ParentPath, second.ParentPath))
{
return false;
}
return true;
}
public override bool Visit(SqlSubqueryCollection first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSubqueryCollection second))
{
return false;
}
if (!Equals(first.Query, second.Query))
{
return false;
}
return true;
}
public override bool Visit(SqlSubqueryScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlSubqueryScalarExpression second))
{
return false;
}
if (!Equals(first.Query, second.Query))
{
return false;
}
return true;
}
public override bool Visit(SqlTopSpec first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlTopSpec second))
{
return false;
}
if (!Equals(first.TopExpresion, second.TopExpresion))
{
return false;
}
return true;
}
public override bool Visit(SqlUnaryScalarExpression first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlUnaryScalarExpression second))
{
return false;
}
if (!Equals(first.Expression, second.Expression))
{
return false;
}
return true;
}
public override bool Visit(SqlUndefinedLiteral first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlUndefinedLiteral second))
{
return false;
}
return true;
}
public override bool Visit(SqlWhereClause first, SqlObject secondAsObject)
{
if (!(secondAsObject is SqlWhereClause second))
{
return false;
}
if (!Equals(first.FilterExpression, second.FilterExpression))
{
return false;
}
return true;
}
private static bool SequenceEquals(
IReadOnlyList<SqlObject> firstList,
IReadOnlyList<SqlObject> secondList)
{
if (firstList.Count != secondList.Count)
{
return false;
}
IEnumerable<(SqlObject, SqlObject)> itemPairs = firstList
.Zip(secondList, (first, second) => (first, second));
foreach ((SqlObject firstItem, SqlObject secondItem) in itemPairs)
{
if (firstItem.Accept(SqlObjectEqualityVisitor.Singleton, secondItem))
{
return false;
}
}
return true;
}
private static bool BothNull(SqlObject first, SqlObject second)
{
return (first is null) && (second is null);
}
private static bool DifferentNullality(SqlObject first, SqlObject second)
{
return (first is null && !(second is null)) || (!(first is null) && (second is null));
}
private static bool Equals(SqlObject first, SqlObject second)
{
if (BothNull(first, second))
{
return true;
}
else if (DifferentNullality(first, second))
{
return false;
}
else
{
// Both not null
return first.Accept(SqlObjectEqualityVisitor.Singleton, second);
}
}
}
}
| 25.670526 | 104 | 0.47878 | [
"MIT"
] | Sheshagiri/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/SqlObjects/Visitors/SqlObjectEqualityVisitor.cs | 24,389 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Controls
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class ContainerContentChangingEventArgs
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public bool Handled
{
get
{
throw new global::System.NotImplementedException("The member bool ContainerContentChangingEventArgs.Handled is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs", "bool ContainerContentChangingEventArgs.Handled");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public bool InRecycleQueue
{
get
{
throw new global::System.NotImplementedException("The member bool ContainerContentChangingEventArgs.InRecycleQueue is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public object Item
{
get
{
throw new global::System.NotImplementedException("The member object ContainerContentChangingEventArgs.Item is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.UI.Xaml.Controls.Primitives.SelectorItem ItemContainer
{
get
{
throw new global::System.NotImplementedException("The member SelectorItem ContainerContentChangingEventArgs.ItemContainer is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public int ItemIndex
{
get
{
throw new global::System.NotImplementedException("The member int ContainerContentChangingEventArgs.ItemIndex is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public uint Phase
{
get
{
throw new global::System.NotImplementedException("The member uint ContainerContentChangingEventArgs.Phase is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public ContainerContentChangingEventArgs()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs", "ContainerContentChangingEventArgs.ContainerContentChangingEventArgs()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.ContainerContentChangingEventArgs()
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.ItemContainer.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.InRecycleQueue.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.ItemIndex.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.Item.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.Phase.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.Handled.get
// Forced skipping of method Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs.Handled.set
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public void RegisterUpdateCallback( global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Xaml.Controls.ListViewBase, global::Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs> callback)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs", "void ContainerContentChangingEventArgs.RegisterUpdateCallback(TypedEventHandler<ListViewBase, ContainerContentChangingEventArgs> callback)");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public void RegisterUpdateCallback( uint callbackPhase, global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Xaml.Controls.ListViewBase, global::Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs> callback)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.ContainerContentChangingEventArgs", "void ContainerContentChangingEventArgs.RegisterUpdateCallback(uint callbackPhase, TypedEventHandler<ListViewBase, ContainerContentChangingEventArgs> callback)");
}
#endif
}
}
| 57.704762 | 301 | 0.771414 | [
"Apache-2.0"
] | TheRusstler/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/ContainerContentChangingEventArgs.cs | 6,059 | C# |
using Microsoft.IdentityModel.Tokens;
using RestWithASPNETMesaRadionica.Configurations;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
namespace RestWithASPNETMesaRadionica.Services.Implementations
{
public class TokenService : ITokenService
{
private TokenConfiguration _configuration;
public TokenService(TokenConfiguration configuration)
{
_configuration = configuration;
}
public string GenerateAccessToken(IEnumerable<Claim> claims)
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.Secret));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var options = new JwtSecurityToken(
issuer: _configuration.Issuer,
audience: _configuration.Audience,
claims: claims,
expires: DateTime.Now.AddMinutes(_configuration.Minutes),
signingCredentials: signinCredentials
);
string tokenString = new JwtSecurityTokenHandler().WriteToken(options);
return tokenString;
}
public string GenerateRefreshToken()
{
var randomNumber = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
};
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.Secret)),
ValidateLifetime = false
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
if (jwtSecurityToken == null ||
!jwtSecurityToken.Header.Alg.Equals(
SecurityAlgorithms.HmacSha256,
StringComparison.InvariantCulture))
throw new SecurityTokenException("Invalid Token");
return principal;
}
}
}
| 37.013889 | 108 | 0.640525 | [
"Apache-2.0"
] | mcanavez/API-Rest | RestWithASPNET5/RestWithASPNET5/Services/Implementations/TokenService.cs | 2,667 | C# |
using AM.Core.Algorithms.StringManipulation.Converters;
namespace AM.Core.Algorithms.StringManipulation.Tests.Converters
{
public class BruteForceZigZagConverterTests : ZigZagConverterTestsBase<BruteForceZigZagConverter>
{
}
}
| 26.777778 | 101 | 0.817427 | [
"MIT"
] | mkArtak/Algorithms | test/AM.Core.Algorithms.StringManipulation.Tests/Converters/BruteForceZigZagConverterTests.cs | 243 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
namespace DirectX12GameEngine.Serialization
{
public class FileSystemProvider : IFileProvider
{
public FileSystemProvider(IStorageFolder rootFolder, IStorageFolder? readWriteRootFolder = null)
{
RootFolder = rootFolder;
ReadWriteRootFolder = readWriteRootFolder ?? rootFolder;
}
public string RootPath => RootFolder.Path;
public IStorageFolder RootFolder { get; }
public IStorageFolder ReadWriteRootFolder { get; }
public async Task<bool> ExistsAsync(string path)
{
return await ExistsAsync(ReadWriteRootFolder, path)
|| (RootFolder != ReadWriteRootFolder && await ExistsAsync(RootFolder, path));
}
public async Task<Stream> OpenStreamAsync(string path, FileMode mode, FileAccess access)
{
if (access.HasFlag(FileAccess.Write))
{
return await ReadWriteRootFolder.OpenStreamForWriteAsync(path, ToCreationCollisionOption(mode));
}
else
{
if (mode != FileMode.Open) throw new ArgumentException("File mode has to be FileMode.Open when FileAccess.Read is specified.");
if (await ExistsAsync(ReadWriteRootFolder, path))
{
return await ReadWriteRootFolder.OpenStreamForReadAsync(path);
}
if (RootFolder != ReadWriteRootFolder && await ExistsAsync(RootFolder, path))
{
return await RootFolder.OpenStreamForReadAsync(path);
}
throw new FileNotFoundException();
}
}
private async Task<bool> ExistsAsync(IStorageFolder folder, string path)
{
return await ((IStorageFolder2)folder).TryGetItemAsync(path) != null;
}
private CreationCollisionOption ToCreationCollisionOption(FileMode mode) => mode switch
{
FileMode.CreateNew => CreationCollisionOption.FailIfExists,
FileMode.Create => CreationCollisionOption.ReplaceExisting,
FileMode.OpenOrCreate => CreationCollisionOption.OpenIfExists,
_ => throw new NotSupportedException()
};
}
}
| 35.484848 | 143 | 0.625961 | [
"MIT"
] | 5l1v3r1/DirectX12GameEngine | DirectX12GameEngine.Serialization/FileSystemProvider.cs | 2,344 | C# |
#pragma checksum "C:\Users\iamys\OneDrive\Belgeler\GitHub\UserManagementApplication\UserManagementApplication\UserManagementApplication.Web\Areas\Identity\Pages\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "43e0bf0d61f9a553d2f59156ad2cdff9b3bdd158"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages__ViewStart), @"mvc.1.0.view", @"/Areas/Identity/Pages/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\iamys\OneDrive\Belgeler\GitHub\UserManagementApplication\UserManagementApplication\UserManagementApplication.Web\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\iamys\OneDrive\Belgeler\GitHub\UserManagementApplication\UserManagementApplication\UserManagementApplication.Web\Areas\Identity\Pages\_ViewImports.cshtml"
using UserManagementApplication.Web.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\iamys\OneDrive\Belgeler\GitHub\UserManagementApplication\UserManagementApplication\UserManagementApplication.Web\Areas\Identity\Pages\_ViewImports.cshtml"
using UserManagementApplication.Web.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"43e0bf0d61f9a553d2f59156ad2cdff9b3bdd158", @"/Areas/Identity/Pages/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ed1726f3f07dc145dd7a5c3f174f70f80486eea0", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
public class Areas_Identity_Pages__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 2 "C:\Users\iamys\OneDrive\Belgeler\GitHub\UserManagementApplication\UserManagementApplication\UserManagementApplication.Web\Areas\Identity\Pages\_ViewStart.cshtml"
Layout = "/Views/Shared/_Layout.cshtml";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 53.208955 | 263 | 0.794109 | [
"Apache-2.0"
] | iamyasinkaya/User-Management-App | UserManagementApplication/UserManagementApplication.Web/obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/_ViewStart.cshtml.g.cs | 3,565 | C# |
using System;
namespace Shriek.Auth.Domain
{
public class Class1
{
}
}
| 9.444444 | 28 | 0.623529 | [
"MIT"
] | Shriek-Projects/shriek-auth | src/Shriek.Auth.Domain/Class1.cs | 87 | C# |
//using Acr.UserDialogs;
using LibVLCSharp.Forms.Shared;
using System;
using System.Net;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace CloudStreamForms.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null) {
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// ((Style)this.Resources["TabbedPageStyle"]).Setters[2] = ((Style)this.Resources["TabbedPageStyle2"]).Setters[1];
// ======================================= INIT =======================================
FFImageLoading.Forms.Platform.CachedImageRenderer.Init();
// Rg.Plugins.Popup.Popup.Init();
LibVLCSharpFormsRenderer.Init();
// UserDialogs.Init();
Xamarin.Forms.Forms.Init(e);
((Style)this.Resources["TabbedPageStyle"]).Setters[0] = ((Style)this.Resources["TabbedPageStyle2"]).Setters[0];
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) {
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null) {
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
protected override void OnActivated(IActivatedEventArgs args) // INTENTDATA
{
base.OnActivated(args);
if (args.Kind == ActivationKind.Protocol) {
//Main.print("DATA RECIVED");
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
Window.Current.Activate();
/*
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null) {
rootFrame = new Frame();
}
Window.Current.Content = rootFrame;
rootFrame.Navigate(typeof( App));*/
/// Xamarin.Forms.Device.BeginInvokeOnMainThread(() => {
// });
// new Frame().Navigate(typeof(MainPage), args);
var url = eventArgs.Uri.AbsoluteUri;
if (url != null) {
if (url != "") {
CloudStreamForms.MainPage.PushPageFromUrlAndName(url);
}
}
try {
CloudStreamForms.MainPage.intentData = eventArgs.Data.ToString();
}
catch (Exception) {
}
/*
try {
CloudStreamForms.MainPage.intentData = eventArgs.Data.ToString();
}
catch (Exception) {
}*/
}
}
internal static void OnDownloadProgressChanged(object basePath, DownloadProgressChangedEventArgs e)
{
throw new NotImplementedException();
}
}
}
| 37.371795 | 130 | 0.562779 | [
"MIT"
] | LagradOst/CloudSteam-2 | CloudStreamForms/CloudStreamForms.UWP/App.xaml.cs | 5,832 | C# |
// -----------------------------------------------------------------------
// <copyright file="DropletExitedMessage.cs" company="Uhuru Software, Inc.">
// Copyright (c) 2011 Uhuru Software, Inc., All Rights Reserved
// </copyright>
// -----------------------------------------------------------------------
namespace Uhuru.CloudFoundry.DEA.Messages
{
using System;
using Uhuru.Utilities;
using Uhuru.Utilities.Json;
/// <summary>
/// This encapsulates a message that is sent after a droplet instance has exited.
/// </summary>
public class DropletExitedMessage : JsonConvertibleObject
{
/// <summary>
/// Gets or sets the id of the droplet the instance belongs to.
/// </summary>
[JsonName("droplet")]
public int DropletId
{
get;
set;
}
/// <summary>
/// Gets or sets the droplet version.
/// </summary>
[JsonName("version")]
public string Version
{
get;
set;
}
/// <summary>
/// Gets or sets the id of the droplet instance.
/// </summary>
[JsonName("instance")]
public string InstanceId
{
get;
set;
}
/// <summary>
/// Gets or sets the index of the droplet instance.
/// </summary>
[JsonName("index")]
public int Index
{
get;
set;
}
/// <summary>
/// Gets or sets the reason, if known, why the droplet instance has exited.
/// </summary>
[JsonName("reason")]
public DropletExitReason? ExitReason
{
get;
set;
}
/// <summary>
/// Gets or sets the timestamp corresponding to the moment the instance has crashed (if that is what happened), in interchangeable format.
/// </summary>
[JsonName("crash_timestamp")]
public int? StateTimestampInterchangeableFormat
{
get { return this.CrashedTimestamp != null ? (int?)RubyCompatibility.DateTimeToEpochSeconds((DateTime)this.CrashedTimestamp) : null; }
set { this.CrashedTimestamp = value != null ? (DateTime?)RubyCompatibility.DateTimeFromEpochSeconds((int)value) : null; }
}
/// <summary>
/// Gets or sets the timestamp corresponding to the moment the instance has crashed (if that is what happened).
/// </summary>
public DateTime? CrashedTimestamp
{
get;
set;
}
}
}
| 29.681818 | 146 | 0.514548 | [
"Apache-2.0",
"MIT"
] | lspecian/vcap-dotnet | src/Uhuru.CloudFoundry.DEA/Messages/DropletExitedMessage.cs | 2,614 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows.Speech;
using HoloToolkit.Unity;
/// <summary>
/// The SurfaceManager class allows applications to scan the environment for a specified amount of time
/// and then process the Spatial Mapping Mesh (find planes, remove vertices) after that time has expired.
/// </summary>
public class PlaySpaceManager : Singleton<PlaySpaceManager>
{
[Tooltip("When checked, the SurfaceObserver will stop running after a specified amount of time.")]
public bool limitScanningByTime = true;
[Tooltip("How much time (in seconds) that the SurfaceObserver will run after being started; used when 'Limit Scanning By Time' is checked.")]
public float scanTime = 1.0f;
[Tooltip("Material to use when rendering Spatial Mapping meshes while the observer is running.")]
public Material defaultMaterial;
[Tooltip("Optional Material to use when rendering Spatial Mapping meshes after the observer has been stopped.")]
public Material secondaryMaterial;
[Tooltip("Minimum number of floor planes required in order to exit scanning/processing mode.")]
public uint minimumFloors = 1;
[Tooltip("Minimum number of wall planes required in order to exit scanning/processing mode.")]
public uint minimumWalls = 0;
/// <summary>
/// Indicates if processing of the surface meshes is complete.
/// </summary>
private bool meshesProcessed = false;
/// <summary>
/// GameObject initialization.
/// </summary>
private void Start()
{
// Update surfaceObserver and storedMeshes to use the same material during scanning.
SpatialMappingManager.Instance.SetSurfaceMaterial(defaultMaterial);
// Register for the MakePlanesComplete event.
SurfaceMeshesToPlanes.Instance.MakePlanesComplete += SurfaceMeshesToPlanes_MakePlanesComplete;
}
/// <summary>
/// Called once per frame.
/// </summary>
private void Update()
{
// Check to see if the spatial mapping data has been processed
// and if we are limiting how much time the user can spend scanning.
if (!meshesProcessed && limitScanningByTime)
{
// If we have not processed the spatial mapping data
// and scanning time is limited...
// Check to see if enough scanning time has passed
// since starting the observer.
if (limitScanningByTime && ((Time.time - SpatialMappingManager.Instance.StartTime) < scanTime))
{
// If we have a limited scanning time, then we should wait until
// enough time has passed before processing the mesh.
}
else
{
// The user should be done scanning their environment,
// so start processing the spatial mapping data...
/* TODO: 3.a DEVELOPER CODING EXERCISE 3.a */
// 3.a: Check if IsObserverRunning() is true on the
// SpatialMappingManager.Instance.
if(SpatialMappingManager.Instance.IsObserverRunning())
{
// 3.a: If running, Stop the observer by calling
// StopObserver() on the SpatialMappingManager.Instance.
SpatialMappingManager.Instance.StopObserver();
}
// 3.a: Call CreatePlanes() to generate planes.
CreatePlanes();
// 3.a: Set meshesProcessed to true.
meshesProcessed = true;
}
}
}
/// <summary>
/// Handler for the SurfaceMeshesToPlanes MakePlanesComplete event.
/// </summary>
/// <param name="source">Source of the event.</param>
/// <param name="args">Args for the event.</param>
private void SurfaceMeshesToPlanes_MakePlanesComplete(object source, System.EventArgs args)
{
/* TODO: 3.a DEVELOPER CODING EXERCISE 3.a */
// Collection of floor and table planes that we can use to set horizontal items on.
List<GameObject> horizontal = new List<GameObject>();
// Collection of wall planes that we can use to set vertical items on.
List<GameObject> vertical = new List<GameObject>();
// 3.a: Get all floor and table planes by calling
// SurfaceMeshesToPlanes.Instance.GetActivePlanes().
// Assign the result to the 'horizontal' list.
horizontal = SurfaceMeshesToPlanes.Instance.GetActivePlanes(PlaneTypes.Table | PlaneTypes.Floor);
// 3.a: Get all wall planes by calling
// SurfaceMeshesToPlanes.Instance.GetActivePlanes().
// Assign the result to the 'vertical' list.
vertical = SurfaceMeshesToPlanes.Instance.GetActivePlanes(PlaneTypes.Wall);
// Check to see if we have enough horizontal planes (minimumFloors)
// and vertical planes (minimumWalls), to set holograms on in the world.
if (horizontal.Count >= minimumFloors && vertical.Count >= minimumWalls)
{
// We have enough floors and walls to place our holograms on...
// 3.a: Let's reduce our triangle count by removing triangles
// from SpatialMapping meshes that intersect with our active planes.
// Call RemoveVertices().
// Pass in all activePlanes found by SurfaceMeshesToPlanes.Instance.
RemoveVertices(SurfaceMeshesToPlanes.Instance.ActivePlanes);
// 3.a: We can indicate to the user that scanning is over by
// changing the material applied to the Spatial Mapping meshes.
// Call SpatialMappingManager.Instance.SetSurfaceMaterial().
// Pass in the secondaryMaterial.
SpatialMappingManager.Instance.SetSurfaceMaterial(secondaryMaterial);
// 3.a: We are all done processing the mesh, so we can now
// initialize a collection of Placeable holograms in the world
// and use horizontal/vertical planes to set their starting positions.
// Call SpaceCollectionManager.Instance.GenerateItemsInWorld().
// Pass in the lists of horizontal and vertical planes that we found earlier.
SpaceCollectionManager.Instance.GenerateItemsInWorld(horizontal, vertical);
}
else
{
// We do not have enough floors/walls to place our holograms on...
// 3.a: Re-enter scanning mode so the user can find more surfaces by
// calling StartObserver() on the SpatialMappingManager.Instance.
SpatialMappingManager.Instance.StartObserver();
// 3.a: Re-process spatial data after scanning completes by
// re-setting meshesProcessed to false.
meshesProcessed = false;
}
}
/// <summary>
/// Creates planes from the spatial mapping surfaces.
/// </summary>
private void CreatePlanes()
{
// Generate planes based on the spatial map.
SurfaceMeshesToPlanes surfaceToPlanes = SurfaceMeshesToPlanes.Instance;
if (surfaceToPlanes != null && surfaceToPlanes.enabled)
{
surfaceToPlanes.MakePlanes();
}
}
/// <summary>
/// Removes triangles from the spatial mapping surfaces.
/// </summary>
/// <param name="boundingObjects"></param>
private void RemoveVertices(IEnumerable<GameObject> boundingObjects)
{
RemoveSurfaceVertices removeVerts = RemoveSurfaceVertices.Instance;
if (removeVerts != null && removeVerts.enabled)
{
removeVerts.RemoveSurfaceVerticesWithinBounds(boundingObjects);
}
}
/// <summary>
/// Called when the GameObject is unloaded.
/// </summary>
private void OnDestroy()
{
if (SurfaceMeshesToPlanes.Instance != null)
{
SurfaceMeshesToPlanes.Instance.MakePlanesComplete -= SurfaceMeshesToPlanes_MakePlanesComplete;
}
}
} | 36.801047 | 142 | 0.73837 | [
"MIT"
] | kaiomagalhaes/hololens-planetarium | Starting/Planetarium/New Unity Project/Assets/Scripts/PlaySpaceManager.cs | 7,031 | C# |
using System;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
namespace AutoDogTerminalAPI
{
//关于进程的输入输出委托事件
public delegate void ProcessEventHanlder(object sender, ProcessEventArgs args);
public class ProcessInterface
{
//初始化进程
public ProcessInterface()
{
// Configure the output worker.
outputWorker.WorkerReportsProgress = true;
outputWorker.WorkerSupportsCancellation = true;
outputWorker.DoWork += outputWorker_DoWork;
outputWorker.ProgressChanged += outputWorker_ProgressChanged;
// Configure the error worker.
errorWorker.WorkerReportsProgress = true;
errorWorker.WorkerSupportsCancellation = true;
errorWorker.DoWork += errorWorker_DoWork;
errorWorker.ProgressChanged += errorWorker_ProgressChanged;
}
void outputWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState is string)
{
FireProcessOutputEvent(e.UserState as string);
}
}
void outputWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (outputWorker.CancellationPending == false)
{
int count;
var buffer = new char[1024];
do
{
var builder = new StringBuilder();
count = outputReader.Read(buffer, 0, 1024);
builder.Append(buffer, 0, count);
outputWorker.ReportProgress(0, builder.ToString());
} while (count > 0);
System.Threading.Thread.Sleep(200);
}
}
void errorWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState is string)
{
FireProcessErrorEvent(e.UserState as string);
}
}
void errorWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (errorWorker.CancellationPending == false)
{
int count;
var buffer = new char[1024];
do
{
var builder = new StringBuilder();
count = errorReader.Read(buffer, 0, 1024);
builder.Append(buffer, 0, count);
errorWorker.ReportProgress(0, builder.ToString());
} while (count > 0);
System.Threading.Thread.Sleep(200);
}
}
public void StartProcess(string fileName, string arguments)
{
var processStartInfo = new ProcessStartInfo(fileName, arguments);
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo = processStartInfo;
process.Exited += currentProcess_Exited;
try
{
process.Start();
}
catch (Exception e)
{
Trace.WriteLine("Failed to start process " + fileName + " with arguments '" + arguments + "'");
Trace.WriteLine(e.ToString());
return;
}
processFileName = fileName;
processArguments = arguments;
inputWriter = process.StandardInput;
outputReader = TextReader.Synchronized(process.StandardOutput);
errorReader = TextReader.Synchronized(process.StandardError);
outputWorker.RunWorkerAsync();
errorWorker.RunWorkerAsync();
}
public void StopProcess()
{
if (IsProcessRunning == false)
return;
process.Kill();
}
void currentProcess_Exited(object sender, EventArgs e)
{
FireProcessExitEvent(process.ExitCode);
outputWorker.CancelAsync();
errorWorker.CancelAsync();
inputWriter = null;
outputReader = null;
errorReader = null;
process = null;
processFileName = null;
processArguments = null;
}
private void FireProcessOutputEvent(string content)
{
var theEvent = OnProcessOutput;
if (theEvent != null)
theEvent(this, new ProcessEventArgs(content));
}
private void FireProcessErrorEvent(string content)
{
var theEvent = OnProcessError;
if (theEvent != null)
theEvent(this, new ProcessEventArgs(content));
}
private void FireProcessInputEvent(string content)
{
var theEvent = OnProcessInput;
if (theEvent != null)
theEvent(this, new ProcessEventArgs(content));
}
private void FireProcessExitEvent(int code)
{
var theEvent = OnProcessExit;
if (theEvent != null)
theEvent(this, new ProcessEventArgs(code));
}
public void WriteInput(string input)
{
if (IsProcessRunning)
{
inputWriter.WriteLine(input);
inputWriter.Flush();
}
}
/// <summary>
/// The current process.
/// </summary>
private Process process;
/// <summary>
/// The input writer.
/// </summary>
private StreamWriter inputWriter;
/// <summary>
/// The output reader.
/// </summary>
private TextReader outputReader;
/// <summary>
/// The error reader.
/// </summary>
private TextReader errorReader;
/// <summary>
/// The output worker.
/// </summary>
private BackgroundWorker outputWorker = new BackgroundWorker();
/// <summary>
/// The error worker.
/// </summary>
private BackgroundWorker errorWorker = new BackgroundWorker();
/// <summary>
/// Current process file name.
/// </summary>
private string processFileName;
/// <summary>
/// Arguments sent to the current process.
/// </summary>
private string processArguments;
/// <summary>
/// Occurs when process output is produced.
/// </summary>
public event ProcessEventHanlder OnProcessOutput;
/// <summary>
/// Occurs when process error output is produced.
/// </summary>
public event ProcessEventHanlder OnProcessError;
/// <summary>
/// Occurs when process input is produced.
/// </summary>
public event ProcessEventHanlder OnProcessInput;
/// <summary>
/// Occurs when the process ends.
/// </summary>
public event ProcessEventHanlder OnProcessExit;
public bool IsProcessRunning
{
get
{
try
{
return (process != null && process.HasExited == false);
}
catch
{
return false;
}
}
}
public Process Process
{
get { return process; }
}
public string ProcessFileName
{
get { return processFileName; }
}
public string ProcessArguments
{
get { return processArguments; }
}
}
}
| 28.971014 | 111 | 0.528889 | [
"MIT"
] | devdiv/AutoDog | AutoDog/AutoDogTerminalAPI/ProcessInterface.cs | 8,034 | 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.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using Microsoft.HttpRepl.Fakes;
using Microsoft.HttpRepl.FileSystem;
using Microsoft.HttpRepl.OpenApi;
using Microsoft.HttpRepl.Preferences;
using Microsoft.HttpRepl.Suggestions;
using Microsoft.HttpRepl.UserProfile;
using Xunit;
namespace Microsoft.HttpRepl.Tests.Suggestions
{
public class HeaderCompletionTests
{
[Fact]
public void GetCompletions_NullExistingHeaders_ProperResults()
{
IEnumerable<string> result = HeaderCompletion.GetCompletions(null, "U");
Assert.Equal(3, result.Count());
Assert.Contains("Upgrade", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("Upgrade-Insecure-Requests", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("User-Agent", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetCompletions_ExistingHeader_ProperResults()
{
IReadOnlyCollection<string> existingHeaders = new Collection<string>() { "User-Agent" };
IEnumerable<string> result = HeaderCompletion.GetCompletions(existingHeaders, "U");
Assert.Equal(2, result.Count());
Assert.Contains("Upgrade", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("Upgrade-Insecure-Requests", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetCompletions_NotAnExistingHeader_ProperResults()
{
IReadOnlyCollection<string> existingHeaders = new Collection<string>() { "Content-Type" };
IEnumerable<string> result = HeaderCompletion.GetCompletions(existingHeaders, "U");
Assert.Equal(3, result.Count());
Assert.Contains("Upgrade", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("Upgrade-Insecure-Requests", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("User-Agent", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetCompletions_NoResults_ReturnsEmpty()
{
IEnumerable<string> result = HeaderCompletion.GetCompletions(null, "Not-A-Real-Header");
Assert.Empty(result);
}
[Theory]
[InlineData("Accept")]
[InlineData("Content-Length")]
[InlineData("X-Requested-With")]
public void GetValueCompletions_NoHeaderMatch_ReturnsNull(string header)
{
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: null, path: null, header, prefix: null, programState: null);
Assert.Null(result);
}
[Fact]
public void GetValueCompletions_NoMatch_ReturnsNull()
{
HttpState httpState = SetupHttpState();
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "", httpState);
Assert.Null(result);
}
[Fact]
public void GetValueCompletions_OneMatch_ReturnsMatch()
{
DirectoryStructure directoryStructure = new DirectoryStructure(null);
RequestInfo requestInfo = new RequestInfo();
requestInfo.SetRequestBody("GET", "application/json", "");
requestInfo.SetRequestBody("PUT", "application/xml", "");
directoryStructure.RequestInfo = requestInfo;
HttpState httpState = SetupHttpState();
httpState.BaseAddress = new Uri("https://localhost/");
ApiDefinition apiDefinition = new ApiDefinition();
apiDefinition.DirectoryStructure = directoryStructure;
httpState.ApiDefinition = apiDefinition;
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "", httpState);
Assert.Single(result);
Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetValueCompletions_MultipleMatches_ReturnsCorrectMatches()
{
DirectoryStructure directoryStructure = new DirectoryStructure(null);
RequestInfo requestInfo = new RequestInfo();
requestInfo.SetRequestBody("GET", "application/json", "");
requestInfo.SetRequestBody("GET", "text/plain", "");
requestInfo.SetRequestBody("PUT", "application/xml", "");
directoryStructure.RequestInfo = requestInfo;
HttpState httpState = SetupHttpState();
httpState.BaseAddress = new Uri("https://localhost/");
ApiDefinition apiDefinition = new ApiDefinition();
apiDefinition.DirectoryStructure = directoryStructure;
httpState.ApiDefinition = apiDefinition;
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "", httpState);
Assert.Equal(2, result.Count());
Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("text/plain", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetValueCompletions_NoMethod_ReturnsAll()
{
DirectoryStructure directoryStructure = new DirectoryStructure(null);
RequestInfo requestInfo = new RequestInfo();
requestInfo.SetRequestBody("GET", "application/json", "");
requestInfo.SetRequestBody("GET", "text/plain", "");
requestInfo.SetRequestBody("PUT", "application/xml", "");
directoryStructure.RequestInfo = requestInfo;
HttpState httpState = SetupHttpState();
httpState.BaseAddress = new Uri("https://localhost/");
ApiDefinition apiDefinition = new ApiDefinition();
apiDefinition.DirectoryStructure = directoryStructure;
httpState.ApiDefinition = apiDefinition;
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: null, path: "", header: "Content-Type", "", httpState);
Assert.Equal(3, result.Count());
Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("text/plain", result, StringComparer.OrdinalIgnoreCase);
Assert.Contains("application/xml", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetValueCompletions_WithPrefix_ReturnsMatch()
{
DirectoryStructure directoryStructure = new DirectoryStructure(null);
RequestInfo requestInfo = new RequestInfo();
requestInfo.SetRequestBody("GET", "application/json", "");
requestInfo.SetRequestBody("GET", "text/plain", "");
requestInfo.SetRequestBody("PUT", "application/xml", "");
directoryStructure.RequestInfo = requestInfo;
HttpState httpState = SetupHttpState();
httpState.BaseAddress = new Uri("https://localhost/");
ApiDefinition apiDefinition = new ApiDefinition();
apiDefinition.DirectoryStructure = directoryStructure;
httpState.ApiDefinition = apiDefinition;
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "a", httpState);
Assert.Single(result);
Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void GetValueCompletions_EmptyContentType_Skips()
{
DirectoryStructure directoryStructure = new DirectoryStructure(null);
RequestInfo requestInfo = new RequestInfo();
requestInfo.SetRequestBody("GET", "application/json", "");
requestInfo.SetRequestBody("GET", "", "");
directoryStructure.RequestInfo = requestInfo;
HttpState httpState = SetupHttpState();
httpState.BaseAddress = new Uri("https://localhost/");
ApiDefinition apiDefinition = new ApiDefinition();
apiDefinition.DirectoryStructure = directoryStructure;
httpState.ApiDefinition = apiDefinition;
IEnumerable<string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "", httpState);
Assert.Single(result);
Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
}
private static HttpState SetupHttpState()
{
IFileSystem fileSystem = new FileSystemStub();
IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();
IPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null);
HttpClient httpClient = new HttpClient();
return new HttpState(fileSystem, preferences, httpClient);
}
}
}
| 44.557692 | 146 | 0.660984 | [
"Apache-2.0"
] | jhu78/HttpRepl | src/Microsoft.HttpRepl.Tests/Suggestions/HeaderCompletionTests.cs | 9,268 | C# |
using System.Threading.Tasks;
using NUnit.Framework;
using SFA.DAS.EmployerFinance.Application.Commands.ImportPayeSchemeLevyDeclarations;
using SFA.DAS.EmployerFinance.Application.Commands.UpdateLevyDeclarationSagaProgress;
using SFA.DAS.EmployerFinance.MessageHandlers.EventHandlers.EmployerFinance;
using SFA.DAS.EmployerFinance.Messages.Events;
using SFA.DAS.Testing;
namespace SFA.DAS.EmployerFinance.UnitTests.MessageHandlers.EventHandlers.EmployerFinance
{
[TestFixture]
[Parallelizable]
public class StartedProcessingLevyDeclarationsAdHocEventHandlerTests : FluentTest<StartedProcessingLevyDeclarationsAdHocEventHandlerTestsFixture>
{
[Test]
public Task Handle_WhenHandlingEvent_ThenShouldSendImportLevyDeclarationsCommand()
{
return TestAsync(f => f.Handle(), f => f.VerifySend<ImportPayeSchemeLevyDeclarationsCommand>((c, m) =>
c.SagaId == m.SagaId &&
c.PayrollPeriod == m.PayrollPeriod &&
c.AccountPayeSchemeId == m.AccountPayeSchemeId));
}
[Test]
public Task Handle_WhenHandlingEvent_ThenShouldSendUpdateLevyDeclarationSagaProgressCommand()
{
return TestAsync(f => f.Handle(), f => f.AssertSentMessage<UpdateLevyDeclarationSagaProgressCommand>((sm, m) => sm.SagaId == m.SagaId));
}
}
public class StartedProcessingLevyDeclarationsAdHocEventHandlerTestsFixture : EventHandlerTestsFixture<StartedProcessingLevyDeclarationsAdHocEvent, StartedProcessingLevyDeclarationsAdHocEventHandler>
{
}
} | 46.441176 | 203 | 0.756175 | [
"MIT"
] | SkillsFundingAgency/das-employerfinance | src/SFA.DAS.EmployerFinance.UnitTests/MessageHandlers/EventHandlers/EmployerFinance/StartedProcessingLevyDeclarationsAdHocEventHandlerTests.cs | 1,579 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Altairis.Services.LoginApprovals;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace DemoApp.Areas.Identity.Pages.Account.Manage {
public class ApproveLoginModel : PageModel {
private readonly LoginApprovalManager loginApprovalManager;
public ApproveLoginModel(LoginApprovalManager loginApprovalManager) {
this.loginApprovalManager = loginApprovalManager;
}
public string DisplaySessionId { get; set; }
public string RequesterIpAddress { get; set; }
public string RequesterUserAgent { get; set; }
public IActionResult OnGet(string lasid) {
var las = this.loginApprovalManager.GetLoginApprovalInfo(lasid);
if (las == null) return this.NotFound();
this.DisplaySessionId = this.loginApprovalManager.FormatIdForDisplay(las.SessionId);
this.RequesterIpAddress = las.RequesterIpAddress;
this.RequesterUserAgent = las.RequesterUserAgent;
return this.Page();
}
public IActionResult OnPostApprove(string lasid) {
this.loginApprovalManager.ApproveLogin(lasid);
return this.RedirectToPage("ApproveLoginDone");
}
public IActionResult OnPostDecline(string lasid) {
this.loginApprovalManager.DeclineLogin(lasid);
return this.RedirectToPage("ApproveLoginDeclined");
}
}
} | 34.977273 | 96 | 0.697856 | [
"MIT"
] | ridercz/Altairis.Services.LoginApprovals | DemoApp/Areas/Identity/Pages/Account/Manage/ApproveLogin.cshtml.cs | 1,539 | C# |
#region using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Xml.Serialization;
#endregion
namespace ExplorerWpf {
public static class SettingsHandler {
public const string ROOT_FOLDER = CurrentSettings.S_ROOT_FOLDER;
private static CurrentSettings _current;
private static ColorSettings _color;
static SettingsHandler() {
_current = new CurrentSettings( true );
_color = new ColorSettings();
try {
LoadCurrentState();
} catch (Exception ex) {
OnError( ex );
}
UserPowerShell = _current.SUserPowerShell;
}
public static readonly bool UserPowerShell;
public static bool ChangeUserPowerShell { get => _current.SUserPowerShell; set => _current.SUserPowerShell = value; }
public static bool PerformanceMode { get => _current.SPerformanceMode; set => _current.SPerformanceMode = value; }
public static bool ExecuteInNewProcess { get => _current.SExecuteInNewProcess; set => _current.SExecuteInNewProcess = value; }
public static bool ConsoleAutoChangeDisc { get => _current.SConsoleAutoChangeDisc; set => _current.SConsoleAutoChangeDisc = value; }
public static bool ConsoleAutoChangePath { get => _current.SConsoleAutoChangePath; set => _current.SConsoleAutoChangePath = value; }
public static bool ConsolePresent { get => _current.SConsolePresent; set => _current.SConsolePresent = value; }
public static string ParentDirectoryPrefix { get => _current.SParentDirectoryPrefix; set => _current.SParentDirectoryPrefix = value; }
public static List<string> ExtenstionWithSpecialIcons { get => _current.SExtenstionWithSpecialIcons; set => _current.SExtenstionWithSpecialIcons = value; }
public static ColorSettings Color1 {
[DebuggerStepThrough] get => _color;
}
public static byte ConTransSub => 40;
public static void OnError(Exception ex) {
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.BackgroundColor = ConsoleColor.White;
Console.WriteLine( "Module: " + ex.Source );
Console.WriteLine( "Message: " + ex.Message );
Console.WriteLine( "HResult: " + ex.HResult + " HelpLink: " + ex.HelpLink );
//Console.WriteLine( "StackTrace: " + ex.StackTrace );
Console.ResetColor();
}
public static void SaveCurrentState() {
var xr = new XmlSerializer( typeof(CurrentSettings) );
using ( var fs = File.Open( CurrentSettings.S_SETTINGS_FILE, FileMode.Create ) ) {
xr.Serialize( fs, _current );
}
}
public static void LoadCurrentState() {
if ( !File.Exists( CurrentSettings.S_SETTINGS_FILE ) ) return;
try {
var xr = new XmlSerializer( typeof(CurrentSettings) );
using ( var fs = File.Open( CurrentSettings.S_SETTINGS_FILE, FileMode.Open ) ) {
var tmp = (CurrentSettings) xr.Deserialize( fs );
_current = tmp.Equals( new CurrentSettings() ) ? new CurrentSettings( true ) : tmp;
}
} catch (Exception e) {
OnError( e );
_current = new CurrentSettings( true );
SaveCurrentState();
}
}
public static void SaveCurrentColor() {
_color.SyncFromApplication();
var xr = new XmlSerializer( typeof(ColorSettings) );
using ( var fs = File.Open( ColorSettings.S_SETTINGS_FILE, FileMode.Create ) ) {
xr.Serialize( fs, _color );
}
}
public static void LoadCurrentColor() {
if ( !File.Exists( ColorSettings.S_SETTINGS_FILE ) ) return;
try {
var xr = new XmlSerializer( typeof(ColorSettings) );
using ( var fs = File.Open( ColorSettings.S_SETTINGS_FILE, FileMode.Open ) ) {
var tmp = (ColorSettings) xr.Deserialize( fs );
_color = /* TODO: check for null tmp.Equals( new ColorSettings() ) ? new ColorSettings( true ) :*/ tmp;
}
} catch (Exception e) {
OnError( e );
_color = new ColorSettings( true );
SaveCurrentColor();
}
_color.SyncToApplication();
}
[Serializable]
public struct CurrentSettings {
public bool SConsoleAutoChangeDisc;
public bool SConsoleAutoChangePath;
public bool SConsolePresent;
public string SParentDirectoryPrefix;
public bool SExecuteInNewProcess;
public bool SUserPowerShell;
public bool SPerformanceMode;
public List<string> SExtenstionWithSpecialIcons;
public const string S_ROOT_FOLDER = "/";
public const string S_SETTINGS_FILE = "settimgs.xmlx";
public CurrentSettings(bool defaultInit) {
this.SExtenstionWithSpecialIcons = new List<string> { ".exe", ".lnk", ".url" };
this.SConsoleAutoChangeDisc = true;
this.SConsoleAutoChangePath = true;
this.SUserPowerShell = true;
this.SConsolePresent = false;
this.SExecuteInNewProcess = false;
this.SPerformanceMode = false;
this.SParentDirectoryPrefix = "⤴ ";
}
}
[Serializable]
public struct ColorSettings {
public const string S_SETTINGS_FILE = "colors.xmlx";
public XmlColor Background;
public XmlColor Border;
public XmlColor WindowBorder;
public XmlColor ScrollBarBackground;
public XmlColor HeaderOver;
public XmlColor Selected;
public XmlColor Expander;
public XmlColor ForegroundGrad1;
public XmlColor ForegroundGrad2;
public XmlColor BackgroundGrad1;
public XmlColor BackgroundGrad2;
public ColorSettings(bool defaultInit) : this() { SyncFromApplication(); }
public void SyncFromApplication() {
this.Background = ( (SolidColorBrush) Application.Current.Resources["DefBack"] ).Color;
this.Border = ( (SolidColorBrush) Application.Current.Resources["Border"] ).Color;
this.WindowBorder = ( (SolidColorBrush) Application.Current.Resources["WindowBorder"] ).Color;
this.ScrollBarBackground = ( (SolidColorBrush) Application.Current.Resources["ScrollBarBackground"] ).Color;
this.HeaderOver = (Color) Application.Current.Resources["ControlLightColor"];
this.Selected = (Color) Application.Current.Resources["SelectedBackgroundColor"];
this.Expander = (Color) Application.Current.Resources["GlyphColor"];
var backG = (LinearGradientBrush) Application.Current.Resources["Background"];
var foreG = (LinearGradientBrush) Application.Current.Resources["Foreground"];
this.ForegroundGrad1 = foreG.GradientStops[0].Color;
this.ForegroundGrad2 = foreG.GradientStops[1].Color;
this.BackgroundGrad1 = backG.GradientStops[0].Color;
this.BackgroundGrad2 = backG.GradientStops[1].Color;
}
public void SyncToApplication() {
Application.Current.Resources["DefBack"] = new SolidColorBrush( this.Background );
Application.Current.Resources["WindowBorder"] = new SolidColorBrush( this.WindowBorder );
Application.Current.Resources["Border"] = new SolidColorBrush( this.Border );
Application.Current.Resources["Accent"] = new SolidColorBrush( this.Border );
Application.Current.Resources["ScrollBarBackground"] = new SolidColorBrush( this.ScrollBarBackground );
Application.Current.Resources["ControlLightColor"] = (Color) this.HeaderOver;
Application.Current.Resources["ControlMediumColor"] = (Color) this.HeaderOver;
Application.Current.Resources["DynamicResourceControlBrushKey"] = new SolidColorBrush( this.HeaderOver );
Application.Current.Resources["ControlMouseOverColor"] = (Color) this.HeaderOver;
Application.Current.Resources["SelectedBackgroundColor"] = (Color) this.Selected;
Application.Current.Resources["SelectedUnfocusedColor"] = (Color) this.Selected;
Application.Current.Resources["GlyphColor"] = (Color) this.Expander;
Application.Current.Resources["Foreground"] = new LinearGradientBrush( this.ForegroundGrad1, this.ForegroundGrad2, new Point( 0, 0 ), new Point( 1, 0 ) );
Application.Current.Resources["DynamicResourceControlTextBrushKey"] = Application.Current.Resources["Foreground"];
Application.Current.Resources["Background"] = new LinearGradientBrush( this.BackgroundGrad1, this.BackgroundGrad2, new Point( 0, 0 ), new Point( 1, 0 ) );
Application.Current.Resources["BackgroundLight"] = new LinearGradientBrush( Color.Subtract( this.BackgroundGrad1, Color.FromArgb( ConTransSub, 1, 1, 0 ) ), Color.Subtract( this.BackgroundGrad2, Color.FromArgb( ConTransSub, 1, 1, 1 ) ), new Point( 0, 0 ), new Point( 1, 0 ) );
}
[Serializable]
public struct XmlColor {
private Color _colorM;
public XmlColor(Color c) => this._colorM = c;
public Color ToColor() => this._colorM;
public void FromColor(Color c) { this._colorM = c; }
public static implicit operator Color(XmlColor x) => x.ToColor();
public static implicit operator XmlColor(Color c) => new XmlColor( c );
[XmlAttribute]
public string Web { get => this._colorM.ToString(); set => this._colorM = (Color) ColorConverter.ConvertFromString( value ); }
}
}
}
#region NativeMethods
// ReSharper disable InconsistentNaming
public struct NativeMethods {
#region Blur
[DllImport( "user32.dll" )] private static extern int SetWindowCompositionAttribute(IntPtr hWnd, ref WindowCompositionAttributeData data);
[StructLayout( LayoutKind.Sequential )]
private struct WindowCompositionAttributeData {
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
private enum WindowCompositionAttribute {
// ...
WCA_ACCENT_POLICY = 19
// ...
}
private enum AccentState {
// ReSharper disable UnusedMember.Local
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
// ReSharper restore UnusedMember.Local
}
[StructLayout( LayoutKind.Sequential )]
private struct AccentPolicy {
public AccentState AccentState;
private readonly int AccentFlags;
private readonly int GradientColor;
private readonly int AnimationId;
}
public static void EnableBlur(IntPtr handle) { SetAccent( handle, AccentState.ACCENT_ENABLE_BLURBEHIND ); }
public static void DisableBlur(IntPtr handle) { SetAccent( handle, AccentState.ACCENT_DISABLED ); }
private static void SetAccent(IntPtr handle, AccentState state) {
var accent = new AccentPolicy();
var accentStructSize = Marshal.SizeOf( accent );
accent.AccentState = state;
var accentPtr = Marshal.AllocHGlobal( accentStructSize );
Marshal.StructureToPtr( accent, accentPtr, false );
var data = new WindowCompositionAttributeData { Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY, SizeOfData = accentStructSize, Data = accentPtr };
SetWindowCompositionAttribute( handle, ref data );
Marshal.FreeHGlobal( accentPtr );
}
#endregion
#region ContextMenu
// Retrieves the IShellFolder interface for the desktop folder, which is the root of the Shell's namespace.
[DllImport( "shell32.dll" )]
internal static extern int SHGetDesktopFolder(out IntPtr ppshf);
// Takes a STRRET structure returned by IShellFolder::GetDisplayNameOf, converts it to a string, and places the result in a buffer.
[DllImport( "shlwapi.dll", EntryPoint = "StrRetToBuf", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true )]
internal static extern int StrRetToBuf(IntPtr pstr, IntPtr pidl, StringBuilder pszBuf, int cchBuf);
// The CreatePopupMenu function creates a drop-down menu, submenu, or shortcut menu. The menu is initially empty. You can insert or append menu items by using the InsertMenuItem function. You can also use the InsertMenu function to insert menu items and the AppendMenu function to append menu items.
[DllImport( "user32", SetLastError = true, CharSet = CharSet.Auto )]
internal static extern IntPtr CreatePopupMenu();
// The DestroyMenu function destroys the specified menu and frees any memory that the menu occupies.
[DllImport( "user32", SetLastError = true, CharSet = CharSet.Auto )]
internal static extern bool DestroyMenu(IntPtr hMenu);
// Determines the default menu item on the specified menu
[DllImport( "user32", SetLastError = true, CharSet = CharSet.Auto )]
internal static extern int GetMenuDefaultItem(IntPtr hMenu, bool fByPos, uint gmdiFlags);
#endregion
[DllImport( "user32.dll" )] internal static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport( "kernel32" )] internal static extern bool AllocConsole();
[DllImport( "kernel32.dll", SetLastError = true )]
internal static extern bool AttachConsole(uint dwProcessId);
[DllImport( "kernel32.dll" )] internal static extern IntPtr GetConsoleWindow();
[DllImport( "kernel32.dll", SetLastError = true, ExactSpelling = true )]
internal static extern bool FreeConsole();
[DllImport( "user32.dll", EntryPoint = "SetLayeredWindowAttributes" )]
internal static extern int SetLayeredWindowAttributes(IntPtr hwnd, int crKey, byte bAlpha, int dwFlags);
[DllImport( "user32.dll" )] internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport( "user32.dll", SetLastError = true )]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport( "USER32.DLL" )] internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport( "user32.dll" )] internal static extern bool DrawMenuBar(IntPtr hWnd);
[DllImport( "user32.dll", EntryPoint = "SetWindowPos" )]
internal static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport( "user32.dll" )] internal static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport( "user32.dll", SetLastError = true )]
internal static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport( "user32", ExactSpelling = true, SetLastError = true )]
internal static extern int MapWindowPoints(IntPtr hWndFrom, IntPtr hWndTo, [In, Out] ref RECT rect, [MarshalAs( UnmanagedType.U4 )]
int cPoints);
[DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
internal static extern IntPtr GetDesktopWindow();
[StructLayout( LayoutKind.Sequential )]
internal struct RECT {
public int left, top, bottom, right;
}
internal const int GWL_STYLE = -16; //hex constant for style changing
internal const int WS_BORDER = 0x00800000; //window with border
internal const int WS_CAPTION = 0x00C00000; //window with a title bar
internal const int WS_SYSMENU = 0x00080000; //window with no borders etc.
internal const int WS_MINIMIZEBOX = 0x00020000; //window with minimizebox
internal const int WS_MAXIMIZEBOX = 0x00010000; //window with MAXIMIZEBOX
internal const int WS_THICKFRAME = 0x00040000; //The window has a sizing border. Same as the WS_SIZEBOX style.
internal const int SW_HIDE = 0;
internal const int SW_SHOWNORMAL = 1;
internal const int SW_RESTORE = 9;
}
#endregion
}
| 46.954907 | 307 | 0.620495 | [
"MIT"
] | xuri02/Explorer | ExplorerWpf/SettingsHandler.cs | 17,706 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.