content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChartJSCore.Models;
using Mate.DataCore.Data.Context;
using Mate.DataCore.Nominal;
using Microsoft.AspNetCore.Mvc;
namespace Mate.ViewComponents
{
public class StockEvolutionViewComponent : ViewComponent
{
private readonly MateResultDb _context;
public StockEvolutionViewComponent(MateResultDb context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(List<string> paramsList)
{
var generateChartTask = Task.Run(function: () =>
{
if (!_context.SimulationJobs.Any())
{
return null;
}
var simConfig = _context.SimulationConfigurations.Single(predicate: x => x.Id == Convert.ToInt32(paramsList[0]));
var maxX = Convert.ToInt32(value: Math.Floor(d: (decimal)simConfig.SimulationEndTime / 1000) * 1000);
Chart chart = new Chart();
// charttype
chart.Type = Enums.ChartType.Scatter;
// use available hight in Chart
chart.Options = new LineOptions()
{
MaintainAspectRatio = false,
Responsive = true,
Scales = new Scales
{
YAxes = new List<Scale> { new CartesianScale { Id = "first-y-axis", Type = "linear", Display = true,
ScaleLabel = new ScaleLabel{ LabelString = "Value in €", Display = true, FontSize = 12 },
Ticks = new CartesianLinearTick { Min = 0, Display = true } } },
XAxes = new List<Scale> { new CartesianScale { Id = "first-x-axis", Type = "linear", Display = true,
Ticks = new CartesianLinearTick{ Max = maxX, Min = 0 , Display = true },
ScaleLabel = new ScaleLabel { LabelString = "Time in min", Display = true, FontSize = 12 } } },
},
Legend = new Legend { Position = "bottom", Display = true, FullWidth = true },
Title = new Title { Text = "Machine Workloads", Position = "top", FontSize = 24, FontStyle = "bold" }
};
SimulationType simType = (paramsList[index: 1].Equals(value: "Decentral")) ? SimulationType.Decentral : SimulationType.Central;
var kpis = _context.Kpis.Where(predicate: x => x.KpiType == KpiType.StockEvolution
&& x.Count <= maxX
&& x.SimulationConfigurationId == Convert.ToInt32(paramsList[0])
&& x.SimulationNumber == Convert.ToInt32(paramsList[2])
&& x.SimulationType == simType).OrderBy(keySelector: x => x.Name).ToList();
var articles = kpis.Select(selector: x => x.Name).Distinct();
var data = new Data { Datasets = new List<Dataset>() };
foreach (var article in articles)
{
// add zero to start
var articleKpis = new List<LineScatterData> { new LineScatterData { X = "0", Y = "0" } };
articleKpis.AddRange(collection: kpis.Where(predicate: x => x.Name == article).OrderBy(keySelector: x => x.Count)
.Select(selector: x => new LineScatterData { X = x.Count.ToString(), Y = x.ValueMin.ToString() }).ToList());
var lds = new LineScatterDataset()
{
// min Stock
Data = articleKpis,
BorderWidth = 1,
Label = article,
ShowLine = true,
//SteppedLine = true,
LineTension = 0
, Hidden = (article.Equals(value: "Dump-Truck") || article.Equals(value: "Race-Truck")) ? false : true
,YAxisID = "first-y-axis"
};
data.Datasets.Add(item: lds);
}
chart.Data = data;
return chart;
});
// create JS to Render Chart.
ViewData[index: "chart"] = await generateChartTask;
ViewData[index: "Type"] = paramsList[index: 1];
return View(viewName: $"StockEvolution");
}
}
}
| 44.83 | 139 | 0.517511 | [
"Apache-2.0"
] | JulianWolfgangVonRoete/MATE | Mate/ViewComponents/StockEvolutionViewComponent.cs | 4,487 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// ゲームプレイ領域
/// </summary>
public class PlayArea : MonoBehaviour
{
/// <summary>
/// 範囲を決める矩形
/// </summary>
[SerializeField]
private Rect _areaRect = new Rect(-5f, -5f, 10f, 10f);
/// <summary>
/// 壁の厚さ
/// </summary>
[SerializeField]
private float _thickness = 1f;
/// <summary>
/// 壁コライダー
/// </summary>
[SerializeField]
private BoxCollider2D _wallColliderLeft = null;
[SerializeField]
private BoxCollider2D _wallColliderRight = null;
[SerializeField]
private BoxCollider2D _wallColliderTop = null;
[SerializeField]
private BoxCollider2D _wallColliderBottom = null;
/// <summary>
/// 壁表示
/// </summary>
[SerializeField]
private LineRenderer _lineRenderer = null;
private void Reset()
{
_lineRenderer = GetComponent<LineRenderer>();
}
private void OnValidate()
{
if (_wallColliderLeft != null)
{
_wallColliderLeft.offset = new Vector2(_areaRect.xMin - _thickness / 2f, _areaRect.center.y);
_wallColliderLeft.size = new Vector2(_thickness, _areaRect.height + _thickness * 2f);
}
if (_wallColliderRight != null)
{
_wallColliderRight.offset = new Vector2(_areaRect.xMax + _thickness / 2f, _areaRect.center.y);
_wallColliderRight.size = new Vector2(_thickness, _areaRect.height + _thickness * 2f);
}
if (_wallColliderTop != null)
{
_wallColliderTop.offset = new Vector2(_areaRect.center.x, _areaRect.yMax + _thickness / 2f);
_wallColliderTop.size = new Vector2(_areaRect.width + _thickness * 2f, _thickness);
}
if (_wallColliderBottom != null)
{
_wallColliderBottom.offset = new Vector2(_areaRect.center.x, _areaRect.yMin - _thickness / 2f);
_wallColliderBottom.size = new Vector2(_areaRect.width + _thickness * 2f, _thickness);
}
// ラインレンダラで描画
if (_lineRenderer != null)
{
_lineRenderer.useWorldSpace = true;
_lineRenderer.positionCount = 4;
_lineRenderer.loop = true;
_lineRenderer.startWidth = _thickness;
_lineRenderer.endWidth = _thickness;
_lineRenderer.SetPosition(0, new Vector2(_areaRect.xMin - _thickness / 2f, _areaRect.yMin - _thickness / 2f));
_lineRenderer.SetPosition(1, new Vector2(_areaRect.xMax + _thickness / 2f, _areaRect.yMin - _thickness / 2f));
_lineRenderer.SetPosition(2, new Vector2(_areaRect.xMax + _thickness / 2f, _areaRect.yMax + _thickness / 2f));
_lineRenderer.SetPosition(3, new Vector2(_areaRect.xMin - _thickness / 2f, _areaRect.yMax + _thickness / 2f));
}
}
/// <summary>
/// 矩形を設定
/// </summary>
/// <param name="rect"></param>
public void SetRect(Rect rect)
{
_areaRect = rect;
OnValidate();
}
/// <summary>
/// 領域内のランダムな点を取得する
/// </summary>
/// <param name="margin">壁からのマージン</param>
/// <returns></returns>
public Vector2 GetRandomPositionInRect(float margin)
{
var x = Random.Range(_areaRect.xMin + margin, _areaRect.xMax - margin);
var y = Random.Range(_areaRect.yMin + margin, _areaRect.yMax - margin);
return new Vector2(x, y);
}
}
| 30.830357 | 122 | 0.618303 | [
"MIT"
] | neuneu9/Unity1week_20200810_Scripts | Scripts/Play/PlayArea.cs | 3,589 | C# |
// Note: this script has to be on an always-active UI parent, so that we can
// always find it from other code. (GameObject.Find doesn't find inactive ones)
using UnityEngine;
using UnityEngine.UI;
public partial class UIRespawn : MonoBehaviour {
public GameObject panel;
public Button button;
void Update() {
var player = Utils.ClientLocalPlayer();
if (!player) return;
// visible while player is dead
panel.SetActive(player.health == 0);
button.onClick.SetListener(() => { player.CmdRespawn(); });
// addon system hooks
Utils.InvokeMany(typeof(UIRespawn), this, "Update_");
}
}
| 29.863636 | 79 | 0.659056 | [
"MIT"
] | TUmedu/moonwaker | Assets/uMMORPG/Scripts/_UI/UIRespawn.cs | 659 | C# |
namespace CSharpBasics
{
public class Collection
{
public static void Arrays_1D(){
int[] scores;//declare an array
scores = new int[5];//initializing of an array -> this will assign a 20 bytes memory block
// insert elements
scores[0] = 50;
scores[3] = 78;
//read an element of anarray
// Console.WriteLine(scores[1]); //reading 1 value at a time
Console.WriteLine($"Size of an array = {scores.Length}");
Console.WriteLine($"Dimension of the array = {scores.Rank}");
//read whole array
foreach (var score in scores)
{
Console.WriteLine(scores + " ");
}
}
public static void Arrays_MultiDimensional(){
int[,] twoDArray = new int[2,3]; // 2D array with 2 rows and 3 columns
int[,,] threeDArray = new int[3,3,3];
Console.WriteLine($"Size = {twoDArray.Length}");
Console.WriteLine($"Rank = {twoDArray.Rank}");
twoDArray[0,0]=1;
twoDArray[1,0]=2;
//read an element
//Console.WriteLine(twoDArray[1,2]);
/*for (int i = 0; i < 2; i++) //rows
{
for (int j = 0; j < 3; j++) //columns
{
Console.Write(twoDArray[i,j]+ " ");
}
Console.WriteLine();
}*/
foreach (var element in twoDArray)
{
Console.WriteLine(element+ " ");
}
}
public static int[] Reverse(int[] x){
int[] reversed = new int[x.Length];
for (int i = x.Length-1; i >= 0; i--)
{
reversed[x.Length-1-i]=x[i];
}
return reversed;
}
public static void JaggedArrays()
{
int[][] jaggedArray = new int[2][]; // only initialize rows
jaggedArray[0] = new int[3]; // initializing columns for 1st row; 1st row has 3 columns
jaggedArray[1] = new int[5]; // initializing columns for 2nd row; 2nd row has 5 columns
//1st row
jaggedArray[0][0]=89;
jaggedArray[0][1]=55;
jaggedArray[0][2]=90;
//2nd row
jaggedArray[1][0]=55;
jaggedArray[1][1]=65;
jaggedArray[1][2]=67;
jaggedArray[1][3]=88;
jaggedArray[1][4]=100;
//read
Console.WriteLine($"Lenght - {jaggedArray.Length}");
Console.WriteLine($"Rank - {jaggedArray.Rank}");
for (int i = 0; i < jaggedArray.Length; i++) //rows
{
for (int j = 0; j < jaggedArray[i].Length; j++) // columns
{
Console.Write(jaggedArray[i][j]+" ");
}
Console.WriteLine();
}
}
public static void ReadArray(int[] anyArray){
foreach (var a in anyArray)
{
Console.Write(a+ " ");
}
}
public static void MoveZeroes(int[] y){
ReadArray(y);
Console.WriteLine();
for (int i = 0; i < y.Length; i++)
{
if (y[i] == 0)
{
for (int j = i; j < y.Length-1; j++)
{
int temp = y[j];
y[j] = y[j+1];
y[j+1]=temp;
}
}
}
ReadArray(y);
}
}
} | 31.965217 | 102 | 0.428183 | [
"MIT"
] | 220328-uta-sh-net-ext/Vladimir-Shnyakin | Materials/B/CSharpBasics/CSharpArrays.cs | 3,676 | C# |
// Copyright (c) Microsoft Corporation.
// All rights reserved.
// Licensed under the MIT license.
// See license in the project root for license information.
namespace Microsoft.Graph.ODataTemplateWriter.CodeHelpers.Cpp.Entities
{
using Microsoft.Graph.ODataTemplateWriter.CodeHelpers.Cpp.Helpers;
using System.Collections.Generic;
using Vipr.Core.CodeModel;
/// <summary>
/// A request entity.
/// </summary>
public sealed class RequestEntity : BaseRequestEntity
{
/// <summary>
/// Instantiates a new instance of <see cref="RequestEntity"/> class
/// based on passed ODCM class.
/// </summary>
/// <param name="odcmClass">The ODCM class.</param>
public RequestEntity(OdcmClass odcmClass)
: base(odcmClass, isAbstract: false)
{
}
/// <inheritdoc/>
public override string GenerateIncludeStatements()
{
string entityName = GetEntityName();
string requestInterfaceEntityName = GetRequestInterfaceEntityName();
IncludeBlock includesBlock = new IncludeBlock();
includesBlock.AppendFile(IncludeFile.CppRestSdkHttpMsg, isSystem: true);
includesBlock.AppendFile(IncludeFile.PplxCancellationToken, isSystem: true);
includesBlock.AppendFile(IncludeFile.StdFuture, isSystem: true);
includesBlock.AppendFile(IncludeFile.StdString, isSystem: true);
includesBlock.AppendLine();
includesBlock.AppendFile($"{requestInterfaceEntityName}.h", isSystem: false);
includesBlock.AppendFile($"{entityName}.h", isSystem: false);
includesBlock.AppendLine();
includesBlock.AppendFile(IncludeFile.GraphSdkBaseClientInterface, isSystem: false);
includesBlock.AppendFile(IncludeFile.GraphSdkBaseRequest, isSystem: false);
includesBlock.AppendLine();
return includesBlock.ToString();
}
/// <inheritdoc/>
protected override string GetFullEntityName() => $"{GetEntityName()}Request";
/// <inheritdoc/>
protected override string GetBasePrimaryEntityName() => "BaseRequest";
/// <inheritdoc/>
protected override string GetBaseInterfaceEntityName() => $"I{GetFullEntityName()}";
/// <inheritdoc/>
protected override string GetEntityHeaderComment() => $"A request for {GetEntityName()} entity";
/// <summary>
/// Generates the get method.
/// </summary>
/// <returns>The string contains method definition.</returns>
public string GenerateGetMethod()
{
string entityName = GetEntityName();
using (CodeBlock methodCodeBlock = new CodeBlock(2))
{
methodCodeBlock.AppendLine($"std::future<{entityName}> GetAsync(const pplx::cancellation_token& token) noexcept override");
using (CodeBlock bodyCodeBlock = new CodeBlock(methodCodeBlock))
{
bodyCodeBlock.AppendLine("constexpr auto method{ web::http::methods::GET };");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine($"const {entityName} responseEntity{{ co_await SendAsync<{entityName}>(method, token) }};");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine("co_return responseEntity;");
}
return methodCodeBlock.ToString();
}
}
/// <summary>
/// Generates the create method.
/// </summary>
/// <returns>The string contains method definition.</returns>
public string GenerateCreateMethod()
{
string entityName = GetEntityName();
using (CodeBlock methodCodeBlock = new CodeBlock(2))
{
methodCodeBlock.AppendLine($"std::future<{entityName}> CreateAsync(const {entityName}& entity, const pplx::cancellation_token& token) noexcept override");
using (CodeBlock bodyCodeBlock = new CodeBlock(methodCodeBlock))
{
bodyCodeBlock.AppendLine("constexpr auto method{ web::http::methods::POST };");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine($"const {entityName} responseEntity{{ co_await SendAsync<{entityName}>(entity, method, token) }};");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine("co_return responseEntity;");
}
return methodCodeBlock.ToString();
}
}
/// <summary>
/// Generates the update method.
/// </summary>
/// <returns>The string contains method definition.</returns>
public string GenerateUpdateMethod()
{
string entityName = GetEntityName();
using (CodeBlock methodCodeBlock = new CodeBlock(2))
{
methodCodeBlock.AppendLine($"std::future<{entityName}> UpdateAsync(const {entityName}& entity, const pplx::cancellation_token& token) noexcept override");
using (CodeBlock bodyCodeBlock = new CodeBlock(methodCodeBlock))
{
bodyCodeBlock.AppendLine("constexpr auto method{ web::http::methods::PATCH };");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine($"const {entityName} responseEntity{{ co_await SendAsync<{entityName}>(entity, method, token) }};");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine("co_return responseEntity;");
}
return methodCodeBlock.ToString();
}
}
/// <summary>
/// Generates the delete method.
/// </summary>
/// <returns>The string contains method definition.</returns>
public string GenerateDeleteMethod()
{
string entityName = GetEntityName();
using (CodeBlock methodCodeBlock = new CodeBlock(2))
{
methodCodeBlock.AppendLine($"std::future<void> DeleteAsync(const {entityName}& entity, const pplx::cancellation_token& token) noexcept override");
using (CodeBlock bodyCodeBlock = new CodeBlock(methodCodeBlock))
{
bodyCodeBlock.AppendLine("constexpr auto method{ web::http::methods::DELETE };");
bodyCodeBlock.AppendLine();
bodyCodeBlock.AppendLine($"co_await SendAsync<{entityName}>(entity, method, token);");
}
return methodCodeBlock.ToString();
}
}
}
}
| 41.374233 | 170 | 0.602165 | [
"MIT"
] | cpp11nullptr/MSGraph-SDK-Code-Generator | src/GraphODataTemplateWriter/CodeHelpers/Cpp/Entities/RequestEntity.cs | 6,746 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Response
{
/// <summary>
/// MybankCreditSceneprodLprQueryResponse.
/// </summary>
public class MybankCreditSceneprodLprQueryResponse : AlipayResponse
{
/// <summary>
/// 贷款利率基于LPR基准利率数据。 贷款利率为年利率为16.2%,LPR基准利率为3.85%,则为浮动利率上浮12.35%
/// </summary>
[JsonPropertyName("float_rate")]
public string FloatRate { get; set; }
/// <summary>
/// 贷款利率给予LPR基准利率浮动情况。 1为上浮,0为持平,-1为下降
/// </summary>
[JsonPropertyName("loan_dir")]
public string LoanDir { get; set; }
/// <summary>
/// 期数。 1年或者5年
/// </summary>
[JsonPropertyName("loan_tenor")]
public string LoanTenor { get; set; }
/// <summary>
/// LPR基准利率。转换为百分比即为3.85%
/// </summary>
[JsonPropertyName("lpr_basic_rate")]
public string LprBasicRate { get; set; }
/// <summary>
/// LPR基准利率时间。时间格式为:yyyyMMdd。
/// </summary>
[JsonPropertyName("lpr_date_str")]
public string LprDateStr { get; set; }
/// <summary>
/// 是否可重试
/// </summary>
[JsonPropertyName("retry")]
public string Retry { get; set; }
/// <summary>
/// 网商traceId,便于查询日志内容
/// </summary>
[JsonPropertyName("trace_id")]
public string TraceId { get; set; }
}
}
| 27.433962 | 72 | 0.553645 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Response/MybankCreditSceneprodLprQueryResponse.cs | 1,682 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Goal : MonoBehaviour
{
public Transform startPos;
public int score;
public ChangeScene sceneManager;
private void Awake()
{
sceneManager = GameObject.FindObjectOfType<ChangeScene>();
}
void Start()
{
score = 0;
}
private void Update()
{
if (score >= 10)
{
sceneManager.MainMenuReturn();
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Player")
{
collision.gameObject.transform.position = startPos.position;
score++;
gameObject.transform.position = new Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
Debug.Log("Score: " + score);
}
}
}
| 19.886364 | 105 | 0.585143 | [
"MIT"
] | Jhar226/AGGP-231c-Labs | Lab01/AGGP 231c - Lab01/Assets/Scripts/Goal.cs | 877 | C# |
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Components.DictionaryAdapter
{
using System;
using System.ComponentModel;
/// <summary>
/// Contract for editing the Dictionary adapter.
/// </summary>
public interface IDictionaryEdit : IEditableObject, IRevertibleChangeTracking
{
bool CanEdit { get; }
bool IsEditing { get; }
bool SupportsMultiLevelEdit { get; set; }
IDisposable SuppressEditingBlock();
void SuppressEditing();
void ResumeEditing();
}
}
| 29.815789 | 81 | 0.704325 | [
"Apache-2.0"
] | belav/Core | src/Castle.Core/Components.DictionaryAdapter/IDictionaryEdit.cs | 1,135 | C# |
using System.IO;
namespace AudioMog.Core.Audio.ExtraData
{
public class OggVorbisExtraData : ACodecExtraData
{
public byte Version;
public uint LoopStart;
public uint LoopEnd;
public uint NumberOfSamples;
public uint HeaderSize;
public uint SeekTableSize;
public ushort UnknownAt18;
public OggVorbisExtraData(MaterialSection.MaterialEntry entry, BinaryReader reader)
{
var extraDataOffset = entry.ExtraDataOffset;
/* extradata: */
/* 0x00: version */
/* 0x01: reserved */
/* 0x02: size */
/* 0x04: loop start offset */
/* 0x08: loop end offset */
/* 0x0c: num samples */
/* 0x10: header size */
/* 0x14: seek table size */
/* 0x18: reserved x2 */
/* 0x20: seek table */
Version = reader.ReadByteAt(extraDataOffset);
var unknownAt1 = reader.ReadByteAt(extraDataOffset + 0x01);
var badSize = reader.ReadUInt16At(extraDataOffset + 0x02);
LoopStart = reader.ReadUInt32At(extraDataOffset + 0x04);
LoopEnd = reader.ReadUInt32At(extraDataOffset + 0x08);
NumberOfSamples = reader.ReadUInt32At(extraDataOffset + 0x0c);
HeaderSize = reader.ReadUInt32At(extraDataOffset + 0x10);
SeekTableSize = reader.ReadUInt32At(extraDataOffset + 0x14);
UnknownAt18 = reader.ReadUInt16At(extraDataOffset + 0x18);
//seek table at 20
}
}
} | 30.44186 | 85 | 0.710466 | [
"MIT"
] | Yoraiz0r/AudioMog | AudioMog/Audio/ExtraData/OggVorbisExtraData.cs | 1,311 | C# |
using System;
public static class Test {
public static void Main() {
RunTest(() => Console.WriteLine ($"Initializing the map took {1}ms"));
}
static void RunTest (Action callback)
{
callback();
}
} | 17.416667 | 72 | 0.665072 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/tests/test-interpolation-03.cs | 209 | C# |
using Microsoft.Boogie;
using System;
using ProgTransformation;
using System.Diagnostics;
using System.Linq;
using System.IO;
using SymDiffUtils;
namespace SymdiffPreprocess
{
/// <summary>
/// Put any transformations that need to be done to prepare a BPL file for SymDiff
/// (e.g. specific to some front end perhaps guarded by flags)
/// </summary>
class Preprocess
{
private static int PrintUsage()
{
Console.WriteLine("SmackProcessor.exe a.bpl [-break]");
return -1;
}
private static string relativeDir = "";
static int Main(string[] args)
{
if (args.Length < 1)
{
return PrintUsage();
}
if (args.ToList().Any(x => x == "-break")) Debugger.Launch();
args.Where(x => x.StartsWith("-relativeSourceDir:"))
.Iter(s => relativeDir = s.Split(':')[1]);
CommandLineOptions.Install(new CommandLineOptions());
string programFileName = args[0];
Debug.Assert(programFileName.Contains(".bpl"), string.Format("File name is expected to have the .bpl extension: {0}.", programFileName));
string outFileName = programFileName.Substring(0, programFileName.LastIndexOf(".bpl")) + "_unsmacked.bpl";
PersistentProgram persistentProgram;
try
{
persistentProgram = ParseAndTypeCheckProgram(programFileName);
File.Copy(programFileName, outFileName, true);
}
catch
{
//Sort of a hack.
using (Stream prelude = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\resources", "prelude.bpl")))
{
using (Stream bpl = File.OpenRead(programFileName))
{
using (Stream outBpl = new FileStream(outFileName, FileMode.Create))
{
bpl.CopyTo(outBpl);
prelude.CopyTo(outBpl);
}
}
}
}
finally
{
persistentProgram = ParseAndTypeCheckProgram(outFileName);
}
var pass = new SmackPreprocessorTransform(relativeDir);
SmackPreprocessorTransform.writeAllFiles = true;
persistentProgram = pass.run(persistentProgram);
persistentProgram.writeToFile(outFileName);
return 0;
}
private static PersistentProgram ParseAndTypeCheckProgram(string programFileName)
{
Program program;
program = BoogieUtils.ParseProgram(programFileName);
int errors = program.Resolve();
if (errors > 0)
throw new ArgumentException("Unable to resolve " + programFileName);
ModSetCollector c = new ModSetCollector();
c.DoModSetAnalysis(program);
errors = program.Typecheck();
if (errors > 0)
throw new ArgumentException("Unable to typecheck " + programFileName);
PersistentProgram persistentProgram = new PersistentProgram(program);
return persistentProgram;
}
}
}
| 33.643564 | 149 | 0.546792 | [
"MIT"
] | aheroine/SIR-use | Sources/SymDiffPreProcess/source/PreProcess.cs | 3,398 | C# |
/*************************************************************************************
Toolkit for WPF
Copyright (C) 2007-2019 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at https://github.com/xceedsoftware/wpftoolkit/blob/master/license.md
For more features, controls, and fast professional support,
pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
namespace Xceed.Wpf.Toolkit
{
internal class DateTimeInfo
{
public string Content
{
get;
set;
}
public string Format
{
get;
set;
}
public bool IsReadOnly
{
get;
set;
}
public int Length
{
get;
set;
}
public int StartPosition
{
get;
set;
}
public DateTimePart Type
{
get;
set;
}
}
}
| 20.45283 | 101 | 0.51476 | [
"MIT"
] | O-Debegnach/Supervisor-de-Comercio | wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit/DateTimeUpDown/Implementation/DateTimeInfo.cs | 1,086 | C# |
using System;
using System.Linq;
using System.Reflection;
using FluentAssertions;
namespace TicTacToeTests.Validators {
public class ValidationInfo
{
private readonly string _name;
private readonly Type _type;
public ValidationInfo(string name, Type type)
{
_name = name;
_type = type;
}
public bool NameMatches(string name) => name == _name;
public void AssertType(object obj)
{
obj.Should().NotBeNull($"[name = {_name}] [type = {_type.Name}]");
obj.Should().BeOfType(_type);
}
public FieldInfo FieldInfo(object obj)
{
FieldInfo fieldInfo = obj.GetType()
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(t => NameMatches(t.Name));
fieldInfo.Should().NotBeNull($"[name = {_name}] for [type = {_type.Name}]");
return fieldInfo;
}
public FieldInfo FieldInfo<T>()
{
FieldInfo fieldInfo = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(t => NameMatches(t.Name));
fieldInfo.Should().NotBeNull($"[name = {_name}] for [type = {_type.Name}]");
return fieldInfo;
}
}
} | 30.906977 | 101 | 0.574868 | [
"MIT"
] | Fyzxs/MicroObjectTicTacToe | TicTacToeTests/Validators/ValidationInfo.cs | 1,331 | C# |
namespace Qa.UseExistDbContext.MultiTenancy
{
public static class MultiTenancyConsts
{
/* Enable/disable multi-tenancy easily in a single point.
* If you will never need to multi-tenancy, you can remove
* related modules and code parts, including this file.
*/
public const bool IsEnabled = true;
}
}
| 29.75 | 66 | 0.658263 | [
"MIT"
] | liangshiw/AbpDataProectionSamles | samples/Qa.UseExistDbContext/aspnet-core/src/Qa.UseExistDbContext.Domain.Shared/MultiTenancy/MultiTenancyConsts.cs | 359 | C# |
namespace Sitecore.Foundation.Search.Repositories
{
using Sitecore.Foundation.Search.Models;
public interface IMallSearchRepository : ISearchRepository
{
SearchItems GetAllMalls();
}
} | 23.333333 | 62 | 0.738095 | [
"Apache-2.0"
] | jaydipkotadiya1605/Code | src/Foundation/Search/code/Repositories/IMallSearchRepository.cs | 212 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Graphics.UserInterface
{
public abstract class LoadingButton : OsuHoverContainer
{
private bool isLoading;
public bool IsLoading
{
get => isLoading;
set
{
isLoading = value;
Enabled.Value = !isLoading;
if (value)
{
loading.Show();
OnLoadStarted();
}
else
{
loading.Hide();
OnLoadFinished();
}
}
}
public Vector2 LoadingAnimationSize
{
get => loading.Size;
set => loading.Size = value;
}
private readonly LoadingAnimation loading;
protected LoadingButton()
{
AddRange(new[]
{
CreateContent(),
loading = new LoadingAnimation
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(12)
}
});
}
protected override bool OnClick(ClickEvent e)
{
if (!Enabled.Value)
return false;
try
{
return base.OnClick(e);
}
finally
{
// run afterwards as this will disable this button.
IsLoading = true;
}
}
protected virtual void OnLoadStarted()
{
}
protected virtual void OnLoadFinished()
{
}
protected abstract Drawable CreateContent();
}
}
| 24.255814 | 80 | 0.439597 | [
"MIT"
] | Altenhh/osu | osu.Game/Graphics/UserInterface/LoadingButton.cs | 2,003 | C# |
namespace Pitstop.Infrastructure.Messaging;
public interface IMessageHandlerCallback
{
Task<bool> HandleMessageAsync(string messageType, string message);
} | 26.833333 | 70 | 0.826087 | [
"Apache-2.0"
] | NileshGule/pitstop | src/Infrastructure.Messaging/IMessageHandlerCallback.cs | 163 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
// 날짜 : 2021-09-26 PM 9:47:41
// 작성자 : Rito
// https://www.youtube.com/watch?v=PGk0rnyTa1U
namespace Rito.MillionDust
{
using SF = UnityEngine.SerializeField;
/*======================================================================*/
/* */
/* Fields & Unitey Events */
/* */
/*======================================================================*/
[DisallowMultipleComponent]
public partial class DustManager : MonoBehaviour
{
// Singleton
public static DustManager Instance => _instance;
private static DustManager _instance;
private struct Dust
{
public Vector3 position;
public int isAlive;
}
[Header("Compute Shader")]
[SF] private ComputeShader dustCompute;
[Header("Dust")]
[SF] private Mesh dustMesh;
[SF] private Material dustMaterial;
[Space(4f)]
[SF] private int dustCount = 100000; // 생성할 먼지 개수
[Range(0.01f, 2f)]
[SF] private float dustScale = 1f;
[Range(0.01f, 1f)]
[SF] private float dustRadius = 1f;
[Space(4f)]
[SF] private Color dustColorA = Color.black;
[SF] private Color dustColorB = Color.gray;
[Header("Spawn")]
[SF] private Vector3 spawnBottomCenter = new Vector3(0, 0, 0); // 분포 중심 하단 위치(피벗)
[SF] private Vector3 spawnSize = new Vector3(100, 25, 100); // 분포 너비(XYZ)
// 월드 큐브 콜라이더
[Header("World")]
[SF] private Vector3 worldBottomCenter = new Vector3(0, 0, 0);
[SF] private Vector3 worldSize = new Vector3(100, 25, 100);
[SF] private Material worldMaterial;
[Header("Player")]
[SF] private PlayerController controller;
[SF] private VacuumCleaner cleaner;
[SF] private Cone blower;
[SF] private DustEmitter emitter;
[SF] private Cannon cannon;
[Header("Physics")]
[Range(-20f, 20f)]
[SF] private float gravityX = 0;
[Range(-20f, 20f)]
[SF] private float gravityY = -9.8f;
[Range(-20f, 20f)]
[SF] private float gravityZ = 0;
[Space]
[Range(0.01f, 20f)]
[SF] private float mass = 1f; // 먼지 질량
[Range(0f, 10f)]
[SF] private float drag = 1f; // (공기) 저항력
[Range(0f, 1f)]
[SF] private float bounciness = 0.6f; // 충돌 탄성력
[Header("Game")]
[Range(0, 1f)]
[SF] private float timescale = 1f;
private ComputeBuffer dustBuffer; // 먼지 데이터 버퍼(위치, ...)
private ComputeBuffer dustVelocityBuffer; // 먼지 현재 속도 버퍼
private ComputeBuffer argsBuffer; // 먼지 렌더링 데이터 버퍼
private ComputeBuffer aliveNumberBuffer; // 생존 먼지 개수 버퍼
private ComputeBuffer dustColorBuffer; // 먼지 색상 버퍼
private ComputeBuffer collisionFlagBuffer;// 충돌 처리 완료 여부 버퍼
// Private Variables
private uint[] aliveNumberArray;
private int aliveNumber;
private float deltaTime;
private Bounds worldBounds;
private GameObject worldGO;
private MeshFilter worldMF;
private MeshRenderer worldMR;
// Inputs & Mode
private KeyCode cleanerKey = KeyCode.Alpha1;
private KeyCode blowerKey = KeyCode.Alpha2;
private KeyCode emitterKey = KeyCode.Alpha3;
private KeyCode cannonKey = KeyCode.Alpha4;
private KeyCode operationKey = KeyCode.Mouse0;
private KeyCode showCursorKey = KeyCode.Mouse1;
private Cone currentCone;
// Compute Shader Data
private int kernelPopulate;
private int kernelSetDustColors;
private int kernelUpdate;
private int kernelVacuumUp;
private int kernelEmit;
private int kernelBlow;
private int kernelExplode;
private int kernelGroupSizeX;
// 게임 시작 시 초기화 작업 완료 후 처리
private Queue<Action> afterInitJobQueue = new Queue<Action>();
private ColliderSet sphereColliderSet;
private ColliderSet boxColliderSet;
/***********************************************************************
* Unity Events
***********************************************************************/
#region .
private void Awake()
{
_instance = this;
}
private void Start()
{
ClampDustCount();
InitCones();
InitKernels();
InitComputeShader();
InitComputeBuffers();
SetBuffersToShaders();
PopulateDusts();
SetDustColors();
InitWorldBounds();
InitColliders();
ProcessInitialJobs();
StartCoroutine(DetectDataChangesRoutine());
}
/// <summary> 초기화 이전에 쌓인 작업들 처리 </summary>
private void ProcessInitialJobs()
{
while (afterInitJobQueue.Count > 0)
afterInitJobQueue.Dequeue()?.Invoke();
afterInitJobQueue = null;
}
private void Update()
{
Time.timeScale = timescale;
deltaTime = Time.deltaTime;
HandlePlayerInputs();
UpdateCommonVariables();
UpdateVacuumCleaner();
UpdateEmitter();
UpdateBlower();
UpdatePhysics();
dustMaterial.SetFloat("_Scale", dustScale);
Graphics.DrawMeshInstancedIndirect(dustMesh, 0, dustMaterial, worldBounds, argsBuffer);
}
private void OnDestroy()
{
if (dustBuffer != null) dustBuffer.Release();
if (argsBuffer != null) argsBuffer.Release();
if (aliveNumberBuffer != null) aliveNumberBuffer.Release();
if (dustVelocityBuffer != null) dustVelocityBuffer.Release();
if (dustColorBuffer != null) dustColorBuffer.Release();
if (collisionFlagBuffer != null) collisionFlagBuffer.Release();
}
private GUIStyle boxStyle;
private void OnGUI()
{
if (boxStyle == null)
{
boxStyle = new GUIStyle(GUI.skin.box);
boxStyle.fontSize =
#if UNITY_EDITOR
48;
#else
24;
#endif
}
float scWidth = Screen.width;
float scHeight = Screen.height;
Rect r = new Rect(scWidth * 0.04f, scHeight * 0.04f, scWidth * 0.25f, scHeight * 0.05f);
GUI.Box(r, $"{aliveNumber:#,###,##0} / {dustCount:#,###,##0}", boxStyle);
}
private void OnDrawGizmos()
{
if (Application.isPlaying) return;
CalculateWorldBounds(ref worldBounds);
Gizmos.color = Color.cyan;
Gizmos.DrawWireCube(worldBounds.center, worldBounds.size);
}
#endregion
}
} | 31.308696 | 100 | 0.52701 | [
"MIT"
] | rito15/Unity-Million-Dust | Million Dust/Scripts/DustManager.cs | 7,455 | C# |
using System;
using System.Collections.Generic;
namespace csharp
{
public class Program
{
public static void Main(string[] args)
{
//Console.WriteLine("OMGHAI!");
IList<Item> Items = new List<Item>{
new Item {Name = "+5 Dexterity Vest", SellIn = 10, Quality = 20},
new Item {Name = "Aged Brie", SellIn = 2, Quality = 0},
new Item {Name = "Elixir of the Mongoose", SellIn = 5, Quality = 7},
new Item {Name = "Sulfuras, Hand of Ragnaros", SellIn = 0, Quality = 80},
new Item {Name = "Sulfuras, Hand of Ragnaros", SellIn = -1, Quality = 80},
new Item
{
Name = "Backstage passes to a TAFKAL80ETC concert",
SellIn = 15,
Quality = 20
},
new Item
{
Name = "Backstage passes to a TAFKAL80ETC concert",
SellIn = 10,
Quality = 49
},
new Item
{
Name = "Backstage passes to a TAFKAL80ETC concert",
SellIn = 5,
Quality = 49
},
// this conjured item does not work properly yet
new Item {Name = "Conjured Mana Cake", SellIn = 3, Quality = 6}
};
var app = new GildedRose(Items);
for (var i = 0; i < 31; i++)
{
Console.WriteLine("-------- day " + i + " --------");
Console.WriteLine("name, sellIn, quality");
for (var j = 0; j < Items.Count; j++)
{
System.Console.WriteLine(Items[j]);
}
Console.WriteLine("");
app.UpdateQuality();
}
Console.Read();
}
}
}
| 33.103448 | 90 | 0.427083 | [
"MIT"
] | mw509/GildedRose-Refactoring-Kata | csharp/Program.cs | 1,922 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using VarietyHiggstGushed.Model;
using Windows.ApplicationModel.Core;
using Windows.Storage;
using Windows.UI.Core;
namespace VarietyHiggstGushed.ViewModel
{
public class AccountGoverment
{
public AccountGoverment()
{
JwAccountGoverment = this;
}
private static AccountGoverment _accountGoverment;
public Account Account { set; get; }
public JwStorage JwStorage { get; set; } = new JwStorage();
public static AccountGoverment JwAccountGoverment
{
set => _accountGoverment = value;
get => _accountGoverment ?? (_accountGoverment = new AccountGoverment());
}
///// <summary>
///// 第一次使用
///// </summary>
//public bool TtjeqbikiFbr { get; set; } = true;
public async Task Read()
{
//如果重新开始
JwStorage = new JwStorage
{
TranStoragePrice = 100,
TransitStorage = 100
};
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(
"ms-appx:///PropertyStorage.txt"));
var str = (await FileIO.ReadTextAsync(file)).Split('\n');
var propertyStorage = new List<Property>();
for (var i = 0; i < str.Length; i++)
{
try
{
propertyStorage.Add(new Property(str[i], str[i + 1]));
i++;
}
catch (FormatException e)
{
e.Data.Add("1", str[i]);
e.Data.Add("num", str[i + 1]);
throw e;
}
}
propertyStorage.Sort((a, b) => a.Value.CompareTo(b.Value));
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
JwStorage.PropertyStorage.Clear();
foreach (var temp in propertyStorage)
{
JwStorage.PropertyStorage.Add(new WqmnygDcxwptivk(temp));
}
});
Account = new Account();
}
public async Task<bool> ReadJwStorage()
{
await RrhkpWjwyAccount();
//读取存档
var str = "JwStorage";
var folder = ApplicationData.Current.RoamingFolder;
try
{
var file = await folder.GetFileAsync(str);
str = await FileIO.ReadTextAsync(file);
JwStorage = JsonConvert.DeserializeObject<JwStorage>(str);
}
catch (FileNotFoundException)
{
return false;
}
return JwStorage != null;
}
public async Task HscurqtacabfgzAccount()
{
var str = nameof(Account);
var folder = ApplicationData.Current.RoamingFolder;
var file = await folder.CreateFileAsync(str, CreationCollisionOption.ReplaceExisting);
str = JsonConvert.SerializeObject(Account);
await FileIO.WriteTextAsync(file, str);
}
public async Task Storage()
{
await HscurqtacabfgzAccount();
var str = "JwStorage";
var folder = ApplicationData.Current.RoamingFolder;
var file = await folder.CreateFileAsync(str, CreationCollisionOption.ReplaceExisting);
str = JsonConvert.SerializeObject(JwStorage);
await FileIO.WriteTextAsync(file, str);
}
private async Task RrhkpWjwyAccount()
{
var str = nameof(Account);
var folder = ApplicationData.Current.RoamingFolder;
try
{
var file = await folder.GetFileAsync(str);
str = await FileIO.ReadTextAsync(file);
Account = JsonConvert.DeserializeObject<Account>(str);
}
catch (FileNotFoundException)
{
Account = new Account();
}
if (Account == null)
{
Account = new Account();
}
}
}
}
| 30.739437 | 104 | 0.518213 | [
"MIT"
] | lindexi/UWP | uwp/src/VarietyHiggstGushed/VarietyHiggstGushed/ViewModel/AccountGoverment.cs | 4,397 | 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 iotdeviceadvisor-2020-09-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.IoTDeviceAdvisor.Model;
using Amazon.IoTDeviceAdvisor.Model.Internal.MarshallTransformations;
using Amazon.IoTDeviceAdvisor.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.IoTDeviceAdvisor
{
/// <summary>
/// Implementation for accessing IoTDeviceAdvisor
///
/// AWS IoT Core Device Advisor is a cloud-based, fully managed test capability for validating
/// IoT devices during device software development. Device Advisor provides pre-built
/// tests that you can use to validate IoT devices for reliable and secure connectivity
/// with AWS IoT Core before deploying devices to production. By using Device Advisor,
/// you can confirm that your devices can connect to AWS IoT Core, follow security best
/// practices and, if applicable, receive software updates from IoT Device Management.
/// You can also download signed qualification reports to submit to the AWS Partner Network
/// to get your device qualified for the AWS Partner Device Catalog without the need to
/// send your device in and wait for it to be tested.
/// </summary>
public partial class AmazonIoTDeviceAdvisorClient : AmazonServiceClient, IAmazonIoTDeviceAdvisor
{
private static IServiceMetadata serviceMetadata = new AmazonIoTDeviceAdvisorMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonIoTDeviceAdvisorClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTDeviceAdvisorConfig()) { }
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonIoTDeviceAdvisorClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTDeviceAdvisorConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonIoTDeviceAdvisorClient Configuration Object</param>
public AmazonIoTDeviceAdvisorClient(AmazonIoTDeviceAdvisorConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonIoTDeviceAdvisorClient(AWSCredentials credentials)
: this(credentials, new AmazonIoTDeviceAdvisorConfig())
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonIoTDeviceAdvisorClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonIoTDeviceAdvisorConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Credentials and an
/// AmazonIoTDeviceAdvisorClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonIoTDeviceAdvisorClient Configuration Object</param>
public AmazonIoTDeviceAdvisorClient(AWSCredentials credentials, AmazonIoTDeviceAdvisorConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTDeviceAdvisorConfig())
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTDeviceAdvisorConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonIoTDeviceAdvisorClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonIoTDeviceAdvisorClient Configuration Object</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonIoTDeviceAdvisorConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTDeviceAdvisorConfig())
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTDeviceAdvisorConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonIoTDeviceAdvisorClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonIoTDeviceAdvisorClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonIoTDeviceAdvisorClient Configuration Object</param>
public AmazonIoTDeviceAdvisorClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonIoTDeviceAdvisorConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateSuiteDefinition
/// <summary>
/// Creates a Device Advisor test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateSuiteDefinition service method.</param>
///
/// <returns>The response from the CreateSuiteDefinition service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/CreateSuiteDefinition">REST API Reference for CreateSuiteDefinition Operation</seealso>
public virtual CreateSuiteDefinitionResponse CreateSuiteDefinition(CreateSuiteDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateSuiteDefinitionResponseUnmarshaller.Instance;
return Invoke<CreateSuiteDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateSuiteDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateSuiteDefinition operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateSuiteDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/CreateSuiteDefinition">REST API Reference for CreateSuiteDefinition Operation</seealso>
public virtual IAsyncResult BeginCreateSuiteDefinition(CreateSuiteDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateSuiteDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateSuiteDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateSuiteDefinition.</param>
///
/// <returns>Returns a CreateSuiteDefinitionResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/CreateSuiteDefinition">REST API Reference for CreateSuiteDefinition Operation</seealso>
public virtual CreateSuiteDefinitionResponse EndCreateSuiteDefinition(IAsyncResult asyncResult)
{
return EndInvoke<CreateSuiteDefinitionResponse>(asyncResult);
}
#endregion
#region DeleteSuiteDefinition
/// <summary>
/// Deletes a Device Advisor test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSuiteDefinition service method.</param>
///
/// <returns>The response from the DeleteSuiteDefinition service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/DeleteSuiteDefinition">REST API Reference for DeleteSuiteDefinition Operation</seealso>
public virtual DeleteSuiteDefinitionResponse DeleteSuiteDefinition(DeleteSuiteDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteSuiteDefinitionResponseUnmarshaller.Instance;
return Invoke<DeleteSuiteDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteSuiteDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteSuiteDefinition operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteSuiteDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/DeleteSuiteDefinition">REST API Reference for DeleteSuiteDefinition Operation</seealso>
public virtual IAsyncResult BeginDeleteSuiteDefinition(DeleteSuiteDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteSuiteDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteSuiteDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteSuiteDefinition.</param>
///
/// <returns>Returns a DeleteSuiteDefinitionResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/DeleteSuiteDefinition">REST API Reference for DeleteSuiteDefinition Operation</seealso>
public virtual DeleteSuiteDefinitionResponse EndDeleteSuiteDefinition(IAsyncResult asyncResult)
{
return EndInvoke<DeleteSuiteDefinitionResponse>(asyncResult);
}
#endregion
#region GetSuiteDefinition
/// <summary>
/// Gets information about a Device Advisor test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSuiteDefinition service method.</param>
///
/// <returns>The response from the GetSuiteDefinition service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteDefinition">REST API Reference for GetSuiteDefinition Operation</seealso>
public virtual GetSuiteDefinitionResponse GetSuiteDefinition(GetSuiteDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteDefinitionResponseUnmarshaller.Instance;
return Invoke<GetSuiteDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetSuiteDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSuiteDefinition operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSuiteDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteDefinition">REST API Reference for GetSuiteDefinition Operation</seealso>
public virtual IAsyncResult BeginGetSuiteDefinition(GetSuiteDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetSuiteDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSuiteDefinition.</param>
///
/// <returns>Returns a GetSuiteDefinitionResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteDefinition">REST API Reference for GetSuiteDefinition Operation</seealso>
public virtual GetSuiteDefinitionResponse EndGetSuiteDefinition(IAsyncResult asyncResult)
{
return EndInvoke<GetSuiteDefinitionResponse>(asyncResult);
}
#endregion
#region GetSuiteRun
/// <summary>
/// Gets information about a Device Advisor test suite run.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSuiteRun service method.</param>
///
/// <returns>The response from the GetSuiteRun service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRun">REST API Reference for GetSuiteRun Operation</seealso>
public virtual GetSuiteRunResponse GetSuiteRun(GetSuiteRunRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteRunRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteRunResponseUnmarshaller.Instance;
return Invoke<GetSuiteRunResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetSuiteRun operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSuiteRun operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSuiteRun
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRun">REST API Reference for GetSuiteRun Operation</seealso>
public virtual IAsyncResult BeginGetSuiteRun(GetSuiteRunRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteRunRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteRunResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetSuiteRun operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSuiteRun.</param>
///
/// <returns>Returns a GetSuiteRunResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRun">REST API Reference for GetSuiteRun Operation</seealso>
public virtual GetSuiteRunResponse EndGetSuiteRun(IAsyncResult asyncResult)
{
return EndInvoke<GetSuiteRunResponse>(asyncResult);
}
#endregion
#region GetSuiteRunReport
/// <summary>
/// Gets a report download link for a successful Device Advisor qualifying test suite
/// run.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSuiteRunReport service method.</param>
///
/// <returns>The response from the GetSuiteRunReport service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRunReport">REST API Reference for GetSuiteRunReport Operation</seealso>
public virtual GetSuiteRunReportResponse GetSuiteRunReport(GetSuiteRunReportRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteRunReportRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteRunReportResponseUnmarshaller.Instance;
return Invoke<GetSuiteRunReportResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetSuiteRunReport operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSuiteRunReport operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSuiteRunReport
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRunReport">REST API Reference for GetSuiteRunReport Operation</seealso>
public virtual IAsyncResult BeginGetSuiteRunReport(GetSuiteRunReportRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetSuiteRunReportRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetSuiteRunReportResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetSuiteRunReport operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSuiteRunReport.</param>
///
/// <returns>Returns a GetSuiteRunReportResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/GetSuiteRunReport">REST API Reference for GetSuiteRunReport Operation</seealso>
public virtual GetSuiteRunReportResponse EndGetSuiteRunReport(IAsyncResult asyncResult)
{
return EndInvoke<GetSuiteRunReportResponse>(asyncResult);
}
#endregion
#region ListSuiteDefinitions
/// <summary>
/// Lists the Device Advisor test suites you have created.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSuiteDefinitions service method.</param>
///
/// <returns>The response from the ListSuiteDefinitions service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteDefinitions">REST API Reference for ListSuiteDefinitions Operation</seealso>
public virtual ListSuiteDefinitionsResponse ListSuiteDefinitions(ListSuiteDefinitionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSuiteDefinitionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSuiteDefinitionsResponseUnmarshaller.Instance;
return Invoke<ListSuiteDefinitionsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListSuiteDefinitions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListSuiteDefinitions operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListSuiteDefinitions
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteDefinitions">REST API Reference for ListSuiteDefinitions Operation</seealso>
public virtual IAsyncResult BeginListSuiteDefinitions(ListSuiteDefinitionsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSuiteDefinitionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSuiteDefinitionsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListSuiteDefinitions operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListSuiteDefinitions.</param>
///
/// <returns>Returns a ListSuiteDefinitionsResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteDefinitions">REST API Reference for ListSuiteDefinitions Operation</seealso>
public virtual ListSuiteDefinitionsResponse EndListSuiteDefinitions(IAsyncResult asyncResult)
{
return EndInvoke<ListSuiteDefinitionsResponse>(asyncResult);
}
#endregion
#region ListSuiteRuns
/// <summary>
/// Lists the runs of the specified Device Advisor test suite. You can list all runs of
/// the test suite, or the runs of a specific version of the test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListSuiteRuns service method.</param>
///
/// <returns>The response from the ListSuiteRuns service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteRuns">REST API Reference for ListSuiteRuns Operation</seealso>
public virtual ListSuiteRunsResponse ListSuiteRuns(ListSuiteRunsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSuiteRunsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSuiteRunsResponseUnmarshaller.Instance;
return Invoke<ListSuiteRunsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListSuiteRuns operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListSuiteRuns operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListSuiteRuns
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteRuns">REST API Reference for ListSuiteRuns Operation</seealso>
public virtual IAsyncResult BeginListSuiteRuns(ListSuiteRunsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListSuiteRunsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListSuiteRunsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListSuiteRuns operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListSuiteRuns.</param>
///
/// <returns>Returns a ListSuiteRunsResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListSuiteRuns">REST API Reference for ListSuiteRuns Operation</seealso>
public virtual ListSuiteRunsResponse EndListSuiteRuns(IAsyncResult asyncResult)
{
return EndInvoke<ListSuiteRunsResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Lists the tags attached to an IoT Device Advisor resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region ListTestCases
/// <summary>
/// Lists all the test cases in the test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTestCases service method.</param>
///
/// <returns>The response from the ListTestCases service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTestCases">REST API Reference for ListTestCases Operation</seealso>
public virtual ListTestCasesResponse ListTestCases(ListTestCasesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTestCasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTestCasesResponseUnmarshaller.Instance;
return Invoke<ListTestCasesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTestCases operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTestCases operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTestCases
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTestCases">REST API Reference for ListTestCases Operation</seealso>
public virtual IAsyncResult BeginListTestCases(ListTestCasesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTestCasesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTestCasesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTestCases operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTestCases.</param>
///
/// <returns>Returns a ListTestCasesResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/ListTestCases">REST API Reference for ListTestCases Operation</seealso>
public virtual ListTestCasesResponse EndListTestCases(IAsyncResult asyncResult)
{
return EndInvoke<ListTestCasesResponse>(asyncResult);
}
#endregion
#region StartSuiteRun
/// <summary>
/// Starts a Device Advisor test suite run.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartSuiteRun service method.</param>
///
/// <returns>The response from the StartSuiteRun service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ConflictException">
/// Sends Conflict Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/StartSuiteRun">REST API Reference for StartSuiteRun Operation</seealso>
public virtual StartSuiteRunResponse StartSuiteRun(StartSuiteRunRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartSuiteRunRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartSuiteRunResponseUnmarshaller.Instance;
return Invoke<StartSuiteRunResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the StartSuiteRun operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartSuiteRun operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartSuiteRun
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/StartSuiteRun">REST API Reference for StartSuiteRun Operation</seealso>
public virtual IAsyncResult BeginStartSuiteRun(StartSuiteRunRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartSuiteRunRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartSuiteRunResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartSuiteRun operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartSuiteRun.</param>
///
/// <returns>Returns a StartSuiteRunResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/StartSuiteRun">REST API Reference for StartSuiteRun Operation</seealso>
public virtual StartSuiteRunResponse EndStartSuiteRun(IAsyncResult asyncResult)
{
return EndInvoke<StartSuiteRunResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Adds to and modifies existing tags of an IoT Device Advisor resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Removes tags from an IoT Device Advisor resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ResourceNotFoundException">
/// Sends Resource Not Found Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
#region UpdateSuiteDefinition
/// <summary>
/// Updates a Device Advisor test suite.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateSuiteDefinition service method.</param>
///
/// <returns>The response from the UpdateSuiteDefinition service method, as returned by IoTDeviceAdvisor.</returns>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.InternalServerException">
/// Sends Internal Failure Exception.
/// </exception>
/// <exception cref="Amazon.IoTDeviceAdvisor.Model.ValidationException">
/// Sends invalid request exception.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UpdateSuiteDefinition">REST API Reference for UpdateSuiteDefinition Operation</seealso>
public virtual UpdateSuiteDefinitionResponse UpdateSuiteDefinition(UpdateSuiteDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateSuiteDefinitionResponseUnmarshaller.Instance;
return Invoke<UpdateSuiteDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateSuiteDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateSuiteDefinition operation on AmazonIoTDeviceAdvisorClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateSuiteDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UpdateSuiteDefinition">REST API Reference for UpdateSuiteDefinition Operation</seealso>
public virtual IAsyncResult BeginUpdateSuiteDefinition(UpdateSuiteDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateSuiteDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateSuiteDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateSuiteDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateSuiteDefinition.</param>
///
/// <returns>Returns a UpdateSuiteDefinitionResult from IoTDeviceAdvisor.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotdeviceadvisor-2020-09-18/UpdateSuiteDefinition">REST API Reference for UpdateSuiteDefinition Operation</seealso>
public virtual UpdateSuiteDefinitionResponse EndUpdateSuiteDefinition(IAsyncResult asyncResult)
{
return EndInvoke<UpdateSuiteDefinitionResponse>(asyncResult);
}
#endregion
}
} | 54.539561 | 181 | 0.679211 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/IoTDeviceAdvisor/Generated/_bcl35/AmazonIoTDeviceAdvisorClient.cs | 57,212 | C# |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:03:57 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
#pragma warning disable 1591
namespace DotSpatial.Projections.GeographicCategories
{
/// <summary>
/// Antarctica
/// </summary>
public class Antarctica : CoordinateSystemCategory
{
#region Fields
public readonly ProjectionInfo AustralianAntarctic1998;
public readonly ProjectionInfo CampAreaAstro;
public readonly ProjectionInfo DeceptionIsland;
public readonly ProjectionInfo Petrels1972;
public readonly ProjectionInfo PointeGeologiePerroud1950;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Antarctica
/// </summary>
public Antarctica()
{
AustralianAntarctic1998 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs ");
CampAreaAstro = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
DeceptionIsland = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs ");
Petrels1972 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
PointeGeologiePerroud1950 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs ");
AustralianAntarctic1998.Name = "GCS_Australian_Antarctic_1998";
AustralianAntarctic1998.GeographicInfo.Name = "GCS_Australian_Antarctic_1998";
CampAreaAstro.Name = "GCS_Camp_Area";
CampAreaAstro.GeographicInfo.Name = "GCS_Camp_Area";
DeceptionIsland.Name = "GCS_Deception_Island";
DeceptionIsland.GeographicInfo.Name = "GCS_Deception_Island";
Petrels1972.Name = "GCS_Petrels_1972";
Petrels1972.GeographicInfo.Name = "GCS_Petrels_1972";
PointeGeologiePerroud1950.Name = "GCS_Pointe_Geologie_Perroud_1950";
PointeGeologiePerroud1950.GeographicInfo.Name = "GCS_Pointe_Geologie_Perroud_1950";
AustralianAntarctic1998.GeographicInfo.Datum.Name = "D_Australian_Antarctic_1998";
CampAreaAstro.GeographicInfo.Datum.Name = "D_Camp_Area";
DeceptionIsland.GeographicInfo.Datum.Name = "D_Deception_Island";
Petrels1972.GeographicInfo.Datum.Name = "D_Petrels_1972";
PointeGeologiePerroud1950.GeographicInfo.Datum.Name = "D_Pointe_Geologie_Perroud_1950";
}
#endregion
}
}
#pragma warning restore 1591 | 48.742857 | 111 | 0.595545 | [
"MIT"
] | AlexanderSemenyak/DotSpatial | Source/DotSpatial.Projections/GeographicCategories/Antarctica.cs | 3,412 | C# |
namespace DNTScanner.Core
{
/// <summary>
/// WiaImage Format
/// </summary>
public sealed class WiaImageFormat
{
private WiaImageFormat(string value) { Value = value; }
/// <summary>
/// Gets or sets a WiaImage Format
/// </summary>
public string Value { get; }
/// <summary>
/// BMP format
/// </summary>
public static WiaImageFormat Bmp => new WiaImageFormat("{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}");
/// <summary>
/// PNG format
/// </summary>
public static WiaImageFormat Png => new WiaImageFormat("{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}");
/// <summary>
/// GIF format
/// </summary>
public static WiaImageFormat Gif => new WiaImageFormat("{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}");
/// <summary>
/// JPG format
/// </summary>
public static WiaImageFormat Jpeg => new WiaImageFormat("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}");
/// <summary>
/// TIFF format
/// </summary>
public static WiaImageFormat Tiff => new WiaImageFormat("{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}");
}
} | 30.25 | 106 | 0.571074 | [
"Apache-2.0"
] | VahidN/DNTScanner.Core | DNTScanner.Core/WiaImageFormat.cs | 1,212 | C# |
using Trowel.Common.Transport;
using System.Collections.Generic;
using System.Linq;
namespace Trowel.BspEditor.Editing.Components.Compile.Specification
{
public class CompileTool
{
public string Name { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public bool Enabled { get; set; }
public List<CompileParameter> Parameters { get; private set; }
public CompileTool()
{
Parameters = new List<CompileParameter>();
}
public static CompileTool Parse(SerialisedObject gs)
{
var tool = new CompileTool
{
Name = gs.Get("Name", ""),
Description = gs.Get("Description", ""),
Order = gs.Get("Order", 0),
Enabled = gs.Get("Enabled", true)
};
var parameters = gs.Children.Where(x => x.Name == "Parameter");
tool.Parameters.AddRange(parameters.Select(CompileParameter.Parse));
return tool;
}
}
} | 31.470588 | 80 | 0.564486 | [
"BSD-3-Clause"
] | mattiascibien/trowel | Trowel.BspEditor.Editing/Components/Compile/Specification/CompileTool.cs | 1,072 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace New.Models
{
public class Product1
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
public int OrderId { get; set; }
//public int? CustomerId { get; set; }
/* public virtual Order Order { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<Customer> Customers { get; set; }*/
}
} | 28.789474 | 71 | 0.616088 | [
"MIT"
] | DikshaGunnewar/AllAssignmentsSDNBackUp | 09Aug2017AssigmnetToBeCompleted - Copy/New/New/Models/Product1.cs | 549 | C# |
using Git.Storage.Web.Lib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Git.Framework.Controller;
using Git.Framework.DataTypes.ExtensionMethods;
using Git.Storage.Entity.Store;
using Git.Storage.Provider.Client;
using Git.Storage.Web.Lib.Filter;
using Git.Framework.DataTypes;
using Git.Storage.Common;
namespace Git.Storage.Web.Areas.Client.Controllers
{
public class SupplierController : MasterPage
{
[LoginFilter]
public ActionResult Index()
{
return View();
}
/// <summary>
/// 添加供应商
/// </summary>
/// <returns></returns>
[LoginFilter]
public ActionResult AddSupplier()
{
string SupNum = WebUtil.GetQueryStringValue<string>("SupNum");
if (SupNum.IsEmpty())
{
ViewBag.Supplier = new SupplierEntity();
ViewBag.SupType = EnumHelper.GetOptions<ESupType>((int)ESupType.Invented, "请选择供应商类型");
return View();
}
else
{
SupplierProvider provider = new SupplierProvider();
SupplierEntity entity = provider.GetSupplier(SupNum);
entity = entity == null ? new SupplierEntity() : entity;
ViewBag.SupType = EnumHelper.GetOptions<ESupType>(entity.SupType,"请选择供应商类型");
ViewBag.Supplier = entity;
return View();
}
}
/// <summary>
/// 选择供应商
/// </summary>
/// <returns></returns>
[LoginFilter]
public ActionResult Dialog()
{
return View();
}
}
}
| 27.903226 | 102 | 0.568786 | [
"MIT"
] | KittenCN/WMS | Git.Storage.Web/Areas/Client/Controllers/SupplierController.cs | 1,784 | C# |
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using Sast.AbstractSTree.Interfaces;
using Sast.AbstractSTree.Models.Nodes;
namespace Sast.AbstractSTree.Cores.Visitors
{
public class BaseNodeVisitor : AbstractParseTreeVisitor<BaseNode>
{
#region Override methods
public override BaseNode VisitChildren([NotNull] IRuleNode node)
{
if (node.ChildCount > 1)
{
ITreeNode[] newChildren = new ITreeNode[node.ChildCount];
for (int i = 0; i < node.ChildCount; i++)
{
newChildren[i] = new BaseNodeVisitor().Visit(node.GetChild(i));
}
BaseNode newNode = new BaseNode()
{
Name = node.GetType().Name,
Children = newChildren
};
return newNode;
}
else
{
return base.VisitChildren(node);
}
}
public override BaseNode VisitTerminal([NotNull] ITerminalNode node)
{
return new BaseNode() { Name = node.GetText() };
}
#endregion
}
}
| 20.863636 | 70 | 0.680828 | [
"MIT"
] | wiseants/Sast | Sast.AbstractSTree/Cores/Visitors/BaseNodeVisitor.cs | 920 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.AspNet.Http;
namespace Microsoft.AspNet.Routing.Constraints
{
public class RegexRouteConstraint : IRouteConstraint
{
public RegexRouteConstraint([NotNull] Regex regex)
{
Constraint = regex;
}
public RegexRouteConstraint([NotNull] string regexPattern)
{
Constraint = new Regex(regexPattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
public Regex Constraint { get; private set; }
public bool Match([NotNull] HttpContext httpContext,
[NotNull] IRouter route,
[NotNull] string routeKey,
[NotNull] IDictionary<string, object> routeValues,
RouteDirection routeDirection)
{
object routeValue;
if (routeValues.TryGetValue(routeKey, out routeValue)
&& routeValue != null)
{
var parameterValueString = Convert.ToString(routeValue, CultureInfo.InvariantCulture);
return Constraint.IsMatch(parameterValueString);
}
return false;
}
}
}
| 32.413043 | 111 | 0.625755 | [
"Apache-2.0"
] | icyjiang/Microsoft.AspNet.Routing | src/Microsoft.AspNet.Routing/Constraints/RegexRouteConstraint.cs | 1,491 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using System.Text;
using System.Text.Json;
using Azure.Core;
namespace Azure.Media.Analytics.Edge.Models
{
public partial class MediaGraphInstance
{
/// <summary>
/// Deserialize MediaGraphInstance.
/// </summary>
/// <param name="json"></param>
/// <returns>
/// Deserialized Graph Instance.
/// </returns>
public static MediaGraphInstance Deserialize(string json)
{
JsonElement element = JsonDocument.Parse(json).RootElement;
return DeserializeMediaGraphInstance(element);
}
}
}
| 26.444444 | 71 | 0.631653 | [
"MIT"
] | ChenglongLiu/azure-sdk-for-net | sdk/mediaservices/Azure.Media.Analytics.Edge/src/Customization/MediaGraphInstance.cs | 716 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(805)]
[Attributes(9)]
public class DcsTxFreqComp
{
[ElementsCount(16)]
[ElementType("int8")]
[Description("")]
public sbyte[] Value { get; set; }
}
}
| 19.333333 | 43 | 0.593596 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/DcsTxFreqCompI.cs | 406 | C# |
namespace CompanyDirectory.Web.Models
{
public class Settings
{
public string Api { get; set; }
}
}
| 15.125 | 39 | 0.61157 | [
"MIT"
] | jacobladams/creating-cloud-infrastructure-with-c-sharp-and-pulumi | CompanyDirectory.Web/Models/Settings.cs | 123 | 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("06 Control Num")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06 Control Num")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2dd9a5f4-e102-4e5d-9526-1d343aecefb5")]
// 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.864865 | 84 | 0.743041 | [
"MIT"
] | Bullsized/Assignments-Basics | 02 Exams/12 Programming Basics Exam - 19 March 2017 - Evening/06 Control Num/Properties/AssemblyInfo.cs | 1,404 | C# |
// ==========================================================================
// Notifo.io
// ==========================================================================
// Copyright (c) Sebastian Stehle
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Notifo.Domain.Channels;
using Notifo.Domain.Channels.Email;
using Notifo.Domain.Integrations.Resources;
namespace Notifo.Domain.Integrations.Smtp
{
public sealed class SmtpIntegration : IIntegration
{
private readonly SmtpEmailServerPool serverPool;
private static readonly IntegrationProperty HostProperty = new IntegrationProperty("host", IntegrationPropertyType.Text)
{
EditorLabel = Texts.SMTP_HostLabel,
EditorDescription = null,
IsRequired = true,
Summary = true
};
private static readonly IntegrationProperty HostPortProperty = new IntegrationProperty("port", IntegrationPropertyType.Number)
{
EditorLabel = Texts.SMTP_PortLabel,
EditorDescription = null,
DefaultValue = "587"
};
private static readonly IntegrationProperty UsernameProperty = new IntegrationProperty("username", IntegrationPropertyType.Text)
{
EditorLabel = Texts.SMTP_UsernameLabel,
EditorDescription = Texts.SMTP_UsernameHints
};
private static readonly IntegrationProperty PasswordProperty = new IntegrationProperty("password", IntegrationPropertyType.Password)
{
EditorLabel = Texts.SMTP_PasswordLabel,
EditorDescription = Texts.SMTP_PasswordHints
};
private static readonly IntegrationProperty FromEmailProperty = new IntegrationProperty("fromEmail", IntegrationPropertyType.Text)
{
Pattern = Patterns.Email,
EditorLabel = Texts.Email_FromEmailLabel,
EditorDescription = Texts.Email_FromEmailDescription,
IsRequired = true,
Summary = true
};
private static readonly IntegrationProperty FromNameProperty = new IntegrationProperty("fromName", IntegrationPropertyType.Text)
{
EditorLabel = Texts.Email_FromNameLabel,
EditorDescription = Texts.Email_FromNameDescription,
IsRequired = true
};
public IntegrationDefinition Definition { get; } =
new IntegrationDefinition(
"SMTP",
Texts.SMTP_Name,
"./integrations/email.svg",
new List<IntegrationProperty>
{
HostProperty,
HostPortProperty,
UsernameProperty,
PasswordProperty,
FromEmailProperty,
FromNameProperty
},
new List<UserProperty>(),
new HashSet<string>
{
Providers.Email
})
{
Description = Texts.SMTP_Description
};
public SmtpIntegration(SmtpEmailServerPool serverPool)
{
this.serverPool = serverPool;
}
public bool CanCreate(Type serviceType, string id, ConfiguredIntegration configured)
{
return serviceType == typeof(IEmailSender);
}
public object? Create(Type serviceType, string id, ConfiguredIntegration configured, IServiceProvider serviceProvider)
{
if (CanCreate(serviceType, id, configured))
{
var host = HostProperty.GetString(configured);
if (string.IsNullOrWhiteSpace(host))
{
return null;
}
var port = HostPortProperty.GetNumber(configured);
if (port == 0)
{
return null;
}
var fromEmail = FromEmailProperty.GetString(configured);
if (string.IsNullOrWhiteSpace(fromEmail))
{
return null;
}
var fromName = FromNameProperty.GetString(configured);
if (string.IsNullOrWhiteSpace(fromName))
{
return null;
}
var options = new SmtpOptions
{
Username = UsernameProperty.GetString(configured),
Host = host,
HostPort = (int)port,
Password = PasswordProperty.GetString(configured)
};
return new SmtpEmailSender(
() => serverPool.GetServer(options),
fromEmail,
fromName);
}
return null;
}
}
}
| 34.25 | 140 | 0.534063 | [
"MIT"
] | idist-hn/notifo | backend/src/Notifo.Domain.Integrations/Smtp/SmtpIntegration.cs | 4,934 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentContextApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameContext {
public GameEntity mapConfigEntity { get { return GetGroup(GameMatcher.MapConfig).GetSingleEntity(); } }
public MapConfigComponent mapConfig { get { return mapConfigEntity.mapConfig; } }
public bool hasMapConfig { get { return mapConfigEntity != null; } }
public GameEntity SetMapConfig(System.Collections.Generic.Dictionary<string, MapConfig> newList) {
if (hasMapConfig) {
throw new Entitas.EntitasException("Could not set MapConfig!\n" + this + " already has an entity with MapConfigComponent!",
"You should check if the context already has a mapConfigEntity before setting it or use context.ReplaceMapConfig().");
}
var entity = CreateEntity();
entity.AddMapConfig(newList);
return entity;
}
public void ReplaceMapConfig(System.Collections.Generic.Dictionary<string, MapConfig> newList) {
var entity = mapConfigEntity;
if (entity == null) {
entity = SetMapConfig(newList);
} else {
entity.ReplaceMapConfig(newList);
}
}
public void RemoveMapConfig() {
mapConfigEntity.Destroy();
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public MapConfigComponent mapConfig { get { return (MapConfigComponent)GetComponent(GameComponentsLookup.MapConfig); } }
public bool hasMapConfig { get { return HasComponent(GameComponentsLookup.MapConfig); } }
public void AddMapConfig(System.Collections.Generic.Dictionary<string, MapConfig> newList) {
var index = GameComponentsLookup.MapConfig;
var component = (MapConfigComponent)CreateComponent(index, typeof(MapConfigComponent));
component.list = newList;
AddComponent(index, component);
}
public void ReplaceMapConfig(System.Collections.Generic.Dictionary<string, MapConfig> newList) {
var index = GameComponentsLookup.MapConfig;
var component = (MapConfigComponent)CreateComponent(index, typeof(MapConfigComponent));
component.list = newList;
ReplaceComponent(index, component);
}
public void RemoveMapConfig() {
RemoveComponent(GameComponentsLookup.MapConfig);
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherMapConfig;
public static Entitas.IMatcher<GameEntity> MapConfig {
get {
if (_matcherMapConfig == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.MapConfig);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherMapConfig = matcher;
}
return _matcherMapConfig;
}
}
}
| 41.905263 | 135 | 0.612158 | [
"MIT"
] | et9930/ECS-Game | Assets/Script/Generated/Game/Components/GameMapConfigComponent.cs | 3,981 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/dwrite.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("DA20D8EF-812A-4C43-9802-62EC4ABD7ADD")]
[NativeTypeName("struct IDWriteFontFamily : IDWriteFontList")]
public unsafe partial struct IDWriteFontFamily
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IDWriteFontFamily*, Guid*, void**, int>)(lpVtbl[0]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IDWriteFontFamily*, uint>)(lpVtbl[1]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IDWriteFontFamily*, uint>)(lpVtbl[2]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetFontCollection(IDWriteFontCollection** fontCollection)
{
return ((delegate* unmanaged<IDWriteFontFamily*, IDWriteFontCollection**, int>)(lpVtbl[3]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), fontCollection);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("UINT32")]
public uint GetFontCount()
{
return ((delegate* unmanaged<IDWriteFontFamily*, uint>)(lpVtbl[4]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetFont([NativeTypeName("UINT32")] uint index, IDWriteFont** font)
{
return ((delegate* unmanaged<IDWriteFontFamily*, uint, IDWriteFont**, int>)(lpVtbl[5]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), index, font);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetFamilyNames(IDWriteLocalizedStrings** names)
{
return ((delegate* unmanaged<IDWriteFontFamily*, IDWriteLocalizedStrings**, int>)(lpVtbl[6]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), names);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetFirstMatchingFont(DWRITE_FONT_WEIGHT weight, DWRITE_FONT_STRETCH stretch, DWRITE_FONT_STYLE style, IDWriteFont** matchingFont)
{
return ((delegate* unmanaged<IDWriteFontFamily*, DWRITE_FONT_WEIGHT, DWRITE_FONT_STRETCH, DWRITE_FONT_STYLE, IDWriteFont**, int>)(lpVtbl[7]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), weight, stretch, style, matchingFont);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetMatchingFonts(DWRITE_FONT_WEIGHT weight, DWRITE_FONT_STRETCH stretch, DWRITE_FONT_STYLE style, IDWriteFontList** matchingFonts)
{
return ((delegate* unmanaged<IDWriteFontFamily*, DWRITE_FONT_WEIGHT, DWRITE_FONT_STRETCH, DWRITE_FONT_STYLE, IDWriteFontList**, int>)(lpVtbl[8]))((IDWriteFontFamily*)Unsafe.AsPointer(ref this), weight, stretch, style, matchingFonts);
}
}
}
| 48.47561 | 245 | 0.693836 | [
"MIT"
] | manju-summoner/terrafx.interop.windows | sources/Interop/Windows/um/dwrite/IDWriteFontFamily.cs | 3,977 | C# |
using ModusTempus.GUI.Activity;
namespace ModusTempus.GUI.Group
{
public class GroupController
{
private GroupModel _groupModel;
private ActivityModel _activityModel;
public GroupController(GroupModel groupModel, ActivityModel activityModel)
{
_groupModel = groupModel;
_activityModel = activityModel;
}
public void JoinGroup(string name)
{
_groupModel.JoinGroup(name);
_activityModel.LoadActivities();
}
public void LeaveGroup(string name)
{
_groupModel.LeaveGroup(name);
_activityModel.LoadActivities();
}
public void SelectGroup(string name)
{
_groupModel.SelectGroup(name);
_activityModel.LoadActivities();
}
public void SearchGroups()
{
_groupModel.LoadGroups();
}
public void CreateGroup(string name)
{
_groupModel.CreateGroup(name);
}
public void DeleteGroup()
{
_groupModel.DeleteSelectedGroup();
_activityModel.LoadActivities();
}
}
}
| 18.392157 | 76 | 0.731343 | [
"MIT"
] | vbidin/modus-tempus | ModusTempus.GUI/Group/GroupController.cs | 940 | C# |
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
using System.Text;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers
{
internal static class ERationalCharArrayString {
private const int MaxSafeInt = EDecimal.MaxSafeInt;
public static ERational FromString(
char[] chars,
int offset,
int length,
bool throwException) {
int tmpoffset = offset;
if (chars == null) {
if (!throwException) {
return null;
} else {
throw new ArgumentNullException(nameof(chars));
}
}
if (tmpoffset < 0) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + tmpoffset + ") is" +
"\u0020less" + "\u0020than " + "0");
}
}
if (tmpoffset > chars.Length) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + tmpoffset + ") is" +
"\u0020more" + "\u0020than " + chars.Length);
}
}
if (length < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("length(" + length + ") is less than " + "0");
}
}
if (length > chars.Length) {
if (!throwException) {
return null;
} else {
throw new FormatException("length(" + length + ") is more than " +
chars.Length);
}
}
if (chars.Length - tmpoffset < length) {
if (!throwException) {
return null;
} else { throw new FormatException("chars's length minus " +
tmpoffset + "(" + (chars.Length - tmpoffset) + ") is less than " + length);
}
}
if (length == 0) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
var negative = false;
int endStr = tmpoffset + length;
if (chars[tmpoffset] == '+' || chars[tmpoffset] == '-') {
negative = chars[tmpoffset] == '-';
++tmpoffset;
}
var numerInt = 0;
EInteger numer = null;
var haveDigits = false;
var haveDenominator = false;
var ndenomInt = 0;
EInteger ndenom = null;
int i = tmpoffset;
if (i + 8 == endStr) {
if ((chars[i] == 'I' || chars[i] == 'i') &&
(chars[i + 1] == 'N' || chars[i + 1] == 'n') &&
(chars[i + 2] == 'F' || chars[i + 2] == 'f') &&
(chars[i + 3] == 'I' || chars[i + 3] == 'i') && (chars[i + 4] ==
'N' ||
chars[i + 4] == 'n') && (chars[i + 5] == 'I' || chars[i + 5] ==
'i') &&
(chars[i + 6] == 'T' || chars[i + 6] == 't') && (chars[i + 7] ==
'Y' || chars[i + 7] == 'y')) {
return negative ? ERational.NegativeInfinity :
ERational.PositiveInfinity;
}
}
if (i + 3 == endStr) {
if ((chars[i] == 'I' || chars[i] == 'i') &&
(chars[i + 1] == 'N' || chars[i + 1] == 'n') && (chars[i + 2] ==
'F' || chars[i + 2] == 'f')) {
return negative ? ERational.NegativeInfinity :
ERational.PositiveInfinity;
}
}
var numerStart = 0;
if (i + 3 <= endStr) {
// Quiet NaN
if ((chars[i] == 'N' || chars[i] == 'n') && (chars[i + 1] == 'A' ||
chars[i +
1] == 'a') && (chars[i + 2] == 'N' || chars[i + 2] == 'n')) {
if (i + 3 == endStr) {
return (!negative) ? ERational.NaN : ERational.NaN.Negate();
}
i += 3;
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, endStr);
return ERational.CreateNaN(numer, false, negative);
} else {
return ERational.CreateNaN(
EInteger.FromInt32(numerInt),
false,
negative);
}
}
}
if (i + 4 <= endStr) {
// Signaling NaN
if ((chars[i] == 'S' || chars[i] == 's') && (chars[i + 1] == 'N' ||
chars[i +
1] == 'n') && (chars[i + 2] == 'A' || chars[i + 2] == 'a') &&
(chars[i + 3] == 'N' || chars[i + 3] == 'n')) {
if (i + 4 == endStr) {
return (!negative) ? ERational.SignalingNaN :
ERational.SignalingNaN.Negate();
}
i += 4;
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
haveDigits = haveDigits || thisdigit != 0;
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
int flags3 = (negative ? BigNumberFlags.FlagNegative : 0) |
BigNumberFlags.FlagSignalingNaN;
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, endStr);
return ERational.CreateNaN(numer, true, negative);
} else {
return ERational.CreateNaN(
EInteger.FromInt32(numerInt),
true,
negative);
}
}
}
// Ordinary number
numerStart = i;
int numerEnd = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
numerEnd = i + 1;
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
haveDigits = true;
} else if (chars[i] == '/') {
haveDenominator = true;
++i;
break;
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, numerEnd);
}
if (haveDenominator) {
EInteger denom = null;
var denomInt = 0;
tmpoffset = 1;
haveDigits = false;
if (i == endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
haveDigits = true;
var thisdigit = (int)(chars[i] - '0');
numerEnd = i + 1;
if (denomInt <= MaxSafeInt) {
denomInt *= 10;
denomInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (denomInt > MaxSafeInt) {
denom = EInteger.FromSubstring(chars, numerStart, numerEnd);
}
if (denom == null) {
ndenomInt = denomInt;
} else {
ndenom = denom;
}
} else {
ndenomInt = 1;
}
if (i != endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (ndenom == null ? (ndenomInt == 0) : ndenom.IsZero) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
ERational erat = ERational.Create(
numer == null ? (EInteger)numerInt : numer,
ndenom == null ? (EInteger)ndenomInt : ndenom);
return negative ? erat.Negate() : erat;
}
}
}
| 35.444828 | 190 | 0.38136 | [
"MIT"
] | neos-sdi/adfsmfa | Neos.IdentityServer 3.1/Neos.IdentityServer.MultiFactor.WebAuthN.Common/Library/CBor/Numbers/ERationalCharArrayString.cs | 10,279 | C# |
// Copyright (c) 2018 Aurigma Inc. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
namespace Aurigma.GraphicsMill.AjaxControls
{
[System.Drawing.ToolboxBitmap(typeof(RectangleRubberband), "Resources.RectangleRubberband.bmp")]
[DefaultEvent("RectangleChanged")]
[NonVisualControl]
public class RectangleRubberband : RectangleController, IRubberband, IPostBackEventHandler
{
/// <summary>
/// Private structure for control state deserialization
/// </summary>
private struct RectangleRubberbandState
{
public bool AutoPostBack;
public bool Erasable;
public int GripSize;
public bool GripsVisible;
public bool MaskVisible;
public int MaskOpacity;
public byte MaskColorRed;
public byte MaskColorGreen;
public byte MaskColorBlue;
public bool Movable;
public float Ratio;
public System.Drawing.Rectangle Rectangle;
public int ResizeMode;
public bool RectangleChanged;
public static RectangleRubberbandState Empty
{
get
{
RectangleRubberbandState instance;
instance.AutoPostBack = false;
instance.Erasable = true;
instance.GripSize = 9;
instance.GripsVisible = false;
instance.MaskVisible = false;
instance.MaskOpacity = 50;
instance.MaskColorRed = 0;
instance.MaskColorGreen = 0;
instance.MaskColorBlue = 0;
instance.Movable = true;
instance.Ratio = 1;
instance.Rectangle = Rectangle.Empty;
instance.ResizeMode = Convert.ToInt32(AjaxControls.ResizeMode.Arbitrary, Common.GetNumberFormat());
instance.RectangleChanged = false;
return instance;
}
}
}
private bool _autoPostBack;
private RectangleRubberbandState _postedState;
public RectangleRubberband() : base()
{
_erasable = true;
_gripSize = 8;
_gripsVisible = false;
_maskVisible = false;
_movable = true;
_outlineWidth = 1;
_ratio = 1;
_rectangle = System.Drawing.Rectangle.Empty;
_resizeMode = ResizeMode.Arbitrary;
_postedState = RectangleRubberbandState.Empty;
ScriptClassName = "Aurigma.GraphicsMill.RectangleRubberband";
}
#region Public members
[Browsable(true)]
[ResDescription("RectangleRubberband_AutoPostBack")]
[DefaultValue(false)]
public bool AutoPostBack
{
get
{
return _autoPostBack;
}
set
{
_autoPostBack = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_Erasable")]
[DefaultValue(true)]
public bool Erasable
{
get
{
return _erasable;
}
set
{
_erasable = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_GripSize")]
[DefaultValue(8)]
public int GripSize
{
get
{
return _gripSize;
}
set
{
_gripSize = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_GripsVisible")]
[DefaultValue(false)]
public bool GripsVisible
{
get
{
return _gripsVisible;
}
set
{
_gripsVisible = value;
}
}
[Browsable(false)]
public bool IsEmpty
{
get
{
return !(_rectangle.Width > 0 && _rectangle.Height > 0);
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_MaskVisible")]
[DefaultValue(false)]
public bool MaskVisible
{
get
{
return _maskVisible;
}
set
{
_maskVisible = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_MaskOpacity")]
[DefaultValue(50)]
public int MaskOpacity
{
get
{
return _maskOpacity;
}
set
{
if ((_maskOpacity < 0) || (_maskOpacity > 100))
throw new ArgumentOutOfRangeException("value",
Resources.Messages.MaskOpacityIsOutOfRange);
_maskOpacity = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_MaskColor")]
[DefaultValue("#000000")]
public System.Drawing.Color MaskColor
{
get
{
return System.Drawing.Color.FromArgb(this._maskOpacity, this._maskColorRedComponent, this._maskColorGreenComponent,
this._maskColorBlueComponent);
}
set
{
this._maskColorBlueComponent = value.B;
this._maskColorGreenComponent = value.G;
this._maskColorRedComponent = value.R;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_Movable")]
[DefaultValue(false)]
public bool Movable
{
get
{
return _movable;
}
set
{
_movable = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_Ratio")]
[DefaultValue(1f)]
public float Ratio
{
get
{
return _ratio;
}
set
{
_ratio = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_Rectangle")]
[DefaultValue("0; 0; 0; 0")]
public System.Drawing.Rectangle Rectangle
{
get
{
return _rectangle;
}
set
{
_rectangle = value;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_ResizeMode")]
[DefaultValue(ResizeMode.Arbitrary)]
public ResizeMode ResizeMode
{
get
{
return _resizeMode;
}
set
{
_resizeMode = value;
}
}
public void Erase()
{
if (_erasable)
{
_rectangle = System.Drawing.Rectangle.Empty;
}
}
[Browsable(true)]
[ResDescription("RectangleRubberband_RectangleChanged")]
public event EventHandler<RectangleEventArgs> RectangleChanged;
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
RaisePostBackEvent(eventArgument);
}
#endregion Public members
#region Protected members
protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
bool baseLoadPostData = base.LoadPostData(postDataKey, postCollection);
string state = postCollection[GetStateFieldId()];
if (String.IsNullOrEmpty(state))
{
return false;
}
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
_postedState = jss.Deserialize<RectangleRubberbandState>(state);
_autoPostBack = _postedState.AutoPostBack;
_erasable = _postedState.Erasable;
_gripSize = _postedState.GripSize;
_gripsVisible = _postedState.GripsVisible;
_maskVisible = _postedState.MaskVisible;
_maskOpacity = _postedState.MaskOpacity;
_maskColorRedComponent = _postedState.MaskColorRed;
_maskColorGreenComponent = _postedState.MaskColorGreen;
_maskColorBlueComponent = _postedState.MaskColorBlue;
_movable = _postedState.Movable;
_ratio = _postedState.Ratio;
if (_postedState.Rectangle.Width < 0 || _postedState.Rectangle.Height < 0)
{
_rectangle = Rectangle.Empty;
}
else
{
_rectangle = _postedState.Rectangle;
}
_resizeMode = (ResizeMode)(_postedState.ResizeMode);
if (_postedState.RectangleChanged)
{
return true;
}
return baseLoadPostData;
}
protected override void RaisePostDataChangedEvent()
{
OnRectangleChanged();
}
protected virtual void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == "RectangleChanged")
{
OnRectangleChanged();
}
}
protected void OnRectangleChanged()
{
if (RectangleChanged != null)
{
RectangleChanged(this, new RectangleEventArgs(this.Rectangle));
}
}
protected override void InitScriptDescriptor(ScriptControlDescriptor descriptor)
{
System.Globalization.NumberFormatInfo format = Common.GetNumberFormat();
descriptor.AddProperty("_autoPostBack", _autoPostBack);
descriptor.AddProperty("_erasable", _erasable);
descriptor.AddProperty("_gripsVisible", _gripsVisible);
descriptor.AddProperty("_gripSize", _gripSize);
descriptor.AddProperty("_maskVisible", _maskVisible);
descriptor.AddProperty("_maskOpacity", _maskOpacity);
descriptor.AddProperty("_maskColorRed", _maskColorRedComponent);
descriptor.AddProperty("_maskColorGreen", _maskColorGreenComponent);
descriptor.AddProperty("_maskColorBlue", _maskColorBlueComponent);
descriptor.AddProperty("_movable", _movable);
descriptor.AddProperty("_ratio", _ratio);
descriptor.AddProperty("_resizeMode", _resizeMode);
if (_rectangle.IsEmpty)
{
descriptor.AddScriptProperty("_rectangle", "{x:0,y:0,width:-1,height:-1}");
}
else
{
descriptor.AddScriptProperty("_rectangle", String.Format(format, "{{x:{0},y:{1},width:{2},height:{3}}}",
_rectangle.Left, _rectangle.Top, _rectangle.Width, _rectangle.Height));
}
descriptor.AddScriptProperty("_rectangleChangedPostBack", "function(){"
+ Page.ClientScript.GetPostBackEventReference(this, "RectangleChanged") + "}");
base.InitScriptDescriptor(descriptor);
}
#endregion Protected members
}
} | 29.258794 | 131 | 0.529841 | [
"MIT"
] | aurigma/WebControls | AjaxControls/Controllers/RectangleRubberband.cs | 11,645 | 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("Shared")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shared")]
[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("a8fb0bfc-98b1-40bf-b61a-517e2220af46")]
// 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.432432 | 84 | 0.74296 | [
"MIT"
] | iluxonchik/distributed-applications-development-course | lab_3/Chat/Shared/Properties/AssemblyInfo.cs | 1,388 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AbpApi.Localization;
using Volo.Abp.Account.Localization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.UI.Navigation;
using Volo.Abp.Users;
using AbpApi.Permissions;
namespace AbpApi.Blazor.Menus
{
public class AbpApiMenuContributor : IMenuContributor
{
private readonly IConfiguration _configuration;
public AbpApiMenuContributor(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task ConfigureMenuAsync(MenuConfigurationContext context)
{
if (context.Menu.Name == StandardMenus.Main)
{
await ConfigureMainMenuAsync(context);
}
else if (context.Menu.Name == StandardMenus.User)
{
await ConfigureUserMenuAsync(context);
}
}
private async Task ConfigureMainMenuAsync(MenuConfigurationContext context)
{
var l = context.GetLocalizer<AbpApiResource>();
context.Menu.Items.Insert(
0,
new ApplicationMenuItem(
AbpApiMenus.Home,
l["Menu:Home"],
"/",
icon: "fas fa-home"
)
);
var bookStoreMenu = new ApplicationMenuItem("BookStore", l["Menu:BookStore"], icon: "fa fa-book");
context.Menu.AddItem(bookStoreMenu);
if (await context.IsGrantedAsync(AbpApiPermissions.Books.Default))
{
var booksMenu = new ApplicationMenuItem("BookStore.Books", l["Menu:Books"], url: "/books");
bookStoreMenu.AddItem(booksMenu);
}
}
private Task ConfigureUserMenuAsync(MenuConfigurationContext context)
{
var accountStringLocalizer = context.GetLocalizer<AccountResource>();
var identityServerUrl = _configuration["AuthServer:Authority"] ?? "";
context.Menu.AddItem(new ApplicationMenuItem(
"Account.Manage",
accountStringLocalizer["MyAccount"],
$"{identityServerUrl.EnsureEndsWith('/')}Account/Manage?returnUrl={_configuration["App:SelfUrl"]}",
icon: "fa fa-cog",
order: 1000,
null).RequireAuthenticated());
return Task.CompletedTask;
}
}
}
| 32.961039 | 115 | 0.598503 | [
"MIT"
] | bartvanhoey/AbpApiConsumedByXamarin | XamarinForms/AbpApi/src/AbpApi.Blazor/Menus/AbpApiMenuContributor.cs | 2,540 | C# |
using System;
using AppKit;
using CoreGraphics;
using Foundation;
using HotUI.Mac.Controls;
using HotUI.Mac.Extensions;
namespace HotUI.Mac.Handlers
{
public class ListViewHandler : AbstractHandler<ListView, HUITableView>
{
public static readonly PropertyMapper<ListView> Mapper = new PropertyMapper<ListView>(ViewHandler.Mapper)
{
["ListView"] = MapListViewProperty,
[nameof(ListView.ReloadData)] = MapReloadData
};
public ListViewHandler() : base(Mapper)
{
}
protected override HUITableView CreateView()
{
return new HUITableView();
}
public override void Remove(View view)
{
TypedNativeView.ListView = null;
base.Remove(view);
}
public static void MapListViewProperty(IViewHandler viewHandler, ListView virtualView)
{
var nativeView = (HUITableView)viewHandler.NativeView;
nativeView.ListView = virtualView;
}
public static void MapReloadData(IViewHandler viewHandler, ListView virtualView)
{
var nativeView = (HUITableView)viewHandler.NativeView;
nativeView?.ReloadData();
}
}
}
| 26.659574 | 113 | 0.631285 | [
"MIT"
] | codemonkeh-dave/HotUI | src/HotUI.Mac/Handlers/ListViewHandler.cs | 1,255 | C# |
using System;
using System.ComponentModel.Design;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.Design;
namespace BBX.Control
{
public class TabControlDesigner : ControlDesigner
{
private DesignerVerbCollection _verbs;
public override DesignerVerbCollection Verbs
{
get
{
if (this._verbs == null)
{
this._verbs = new DesignerVerbCollection(new DesignerVerb[]
{
new DesignerVerb("创建新的属性页...", new EventHandler(this.OnBuildTabStrip))
});
}
return this._verbs;
}
}
protected override string GetEmptyDesignTimeHtml()
{
return base.CreatePlaceHolderDesignTimeHtml("右击选择创建新的属性页");
}
private void OnBuildTabStrip(object sender, EventArgs e)
{
TabEditor tabEditor = new TabEditor();
tabEditor.EditComponent(base.Component);
}
public override string GetDesignTimeHtml()
{
string result;
try
{
TabControl tabControl = (TabControl)base.Component;
if (tabControl.Items == null || tabControl.Items.Count == 0)
{
result = this.GetEmptyDesignTimeHtml();
}
else
{
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
tabControl.RenderDownLevelContent(htmlTextWriter);
htmlTextWriter.Flush();
stringWriter.Flush();
result = stringBuilder.ToString();
}
}
catch (Exception ex)
{
result = base.CreatePlaceHolderDesignTimeHtml("生成设计时代码错误:\n\n" + ex.ToString());
}
return result;
}
}
}
| 25 | 84 | 0.700625 | [
"MIT"
] | NewLifeX/BBX | BBX.Control/TabControlDesigner.cs | 1,654 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.296
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebLab.Informes {
using System;
using System.ComponentModel;
using CrystalDecisions.Shared;
using CrystalDecisions.ReportSource;
using CrystalDecisions.CrystalReports.Engine;
public class ResultadoSinOrdenA5 : ReportClass {
public ResultadoSinOrdenA5() {
}
public override string ResourceName {
get {
return "ResultadoSinOrdenA5.rpt";
}
set {
// Do nothing
}
}
public override bool NewGenerator {
get {
return true;
}
set {
// Do nothing
}
}
public override string FullResourceName {
get {
return "WebLab.Informes.ResultadoSinOrdenA5.rpt";
}
set {
// Do nothing
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section Section1 {
get {
return this.ReportDefinition.Sections[0];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section Section2 {
get {
return this.ReportDefinition.Sections[1];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section PageHeaderSection1 {
get {
return this.ReportDefinition.Sections[2];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection1 {
get {
return this.ReportDefinition.Sections[3];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection6 {
get {
return this.ReportDefinition.Sections[4];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection4 {
get {
return this.ReportDefinition.Sections[5];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection5 {
get {
return this.ReportDefinition.Sections[6];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection2 {
get {
return this.ReportDefinition.Sections[7];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section Section3 {
get {
return this.ReportDefinition.Sections[8];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section DetailSection2 {
get {
return this.ReportDefinition.Sections[9];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section DetailSection3 {
get {
return this.ReportDefinition.Sections[10];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection2 {
get {
return this.ReportDefinition.Sections[11];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection1 {
get {
return this.ReportDefinition.Sections[12];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection4 {
get {
return this.ReportDefinition.Sections[13];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section Section4 {
get {
return this.ReportDefinition.Sections[14];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.CrystalReports.Engine.Section Section5 {
get {
return this.ReportDefinition.Sections[15];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_encabezado1 {
get {
return this.DataDefinition.ParameterFields[0];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_encabezado2 {
get {
return this.DataDefinition.ParameterFields[1];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_encabezado3 {
get {
return this.DataDefinition.ParameterFields[2];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_conLogo {
get {
return this.DataDefinition.ParameterFields[3];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_datosPaciente {
get {
return this.DataDefinition.ParameterFields[4];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_ImprimirHojasSeparadas {
get {
return this.DataDefinition.ParameterFields[5];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_tipoNumeracion {
get {
return this.DataDefinition.ParameterFields[6];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_firmaElectronica {
get {
return this.DataDefinition.ParameterFields[7];
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public CrystalDecisions.Shared.IParameterField Parameter_datosProtocolo {
get {
return this.DataDefinition.ParameterFields[8];
}
}
}
[System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")]
public class CachedResultadoSinOrdenA5 : Component, ICachedReport {
public CachedResultadoSinOrdenA5() {
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public virtual bool IsCacheable {
get {
return true;
}
set {
//
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public virtual bool ShareDBLogonInfo {
get {
return false;
}
set {
//
}
}
[Browsable(false)]
[DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public virtual System.TimeSpan CacheTimeOut {
get {
return CachedReportConstants.DEFAULT_TIMEOUT;
}
set {
//
}
}
public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() {
ResultadoSinOrdenA5 rpt = new ResultadoSinOrdenA5();
rpt.Site = this.Site;
return rpt;
}
public virtual string GetCustomizedCacheKey(RequestContext request) {
String key = null;
// // The following is the code used to generate the default
// // cache key for caching report jobs in the ASP.NET Cache.
// // Feel free to modify this code to suit your needs.
// // Returning key == null causes the default cache key to
// // be generated.
//
// key = RequestContext.BuildCompleteCacheKey(
// request,
// null, // sReportFilename
// this.GetType(),
// this.ShareDBLogonInfo );
return key;
}
}
}
| 38.649682 | 113 | 0.592205 | [
"MIT"
] | saludnqn/laboratorio | WebLab/Informes/ResultadoSinOrdenA5.cs | 12,138 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agent.Sdk;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Content.Common.Tracing;
namespace Agent.Plugins.PipelineArtifact
{
public abstract class PipelineArtifactTaskPluginBaseV2 : IAgentTaskPlugin
{
public abstract Guid Id { get; }
protected virtual string DownloadPath => "path";
protected virtual string pipelineRunId => "runId";
protected CallbackAppTraceSource tracer;
public string Stage => "main";
public Task RunAsync(AgentTaskPluginExecutionContext context, CancellationToken token)
{
this.tracer = new CallbackAppTraceSource(str => context.Output(str), System.Diagnostics.SourceLevels.Information);
return this.ProcessCommandInternalAsync(context, token);
}
protected abstract Task ProcessCommandInternalAsync(
AgentTaskPluginExecutionContext context,
CancellationToken token);
// Properties set by tasks
protected static class ArtifactEventProperties
{
public static readonly string SourceRun = "source";
public static readonly string Project = "project";
public static readonly string PipelineDefinition = "pipeline";
public static readonly string PipelineTriggering = "preferTriggeringPipeline";
public static readonly string PipelineVersionToDownload = "runVersion";
public static readonly string BranchName = "runBranch";
public static readonly string Tags = "tags";
public static readonly string ArtifactName = "artifact";
public static readonly string ItemPattern = "patterns";
}
}
// Can be invoked from a build run or a release run should a build be set as the artifact.
public class DownloadPipelineArtifactTaskV2_0_0 : PipelineArtifactTaskPluginBaseV2
{
// Same as https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DownloadPipelineArtifactV1/task.json
public override Guid Id => PipelineArtifactPluginConstants.DownloadPipelineArtifactTaskId;
static readonly string sourceRunCurrent = "current";
static readonly string sourceRunSpecific = "specific";
static readonly string pipelineVersionToDownloadLatest = "latest";
static readonly string pipelineVersionToDownloadSpecific = "specific";
static readonly string pipelineVersionToDownloadLatestFromBranch = "latestFromBranch";
protected override async Task ProcessCommandInternalAsync(
AgentTaskPluginExecutionContext context,
CancellationToken token)
{
ArgUtil.NotNull(context, nameof(context));
string artifactName = context.GetInput(ArtifactEventProperties.ArtifactName, required: false);
string branchName = context.GetInput(ArtifactEventProperties.BranchName, required: false);
string pipelineDefinition = context.GetInput(ArtifactEventProperties.PipelineDefinition, required: false);
string sourceRun = context.GetInput(ArtifactEventProperties.SourceRun, required: true);
string pipelineTriggering = context.GetInput(ArtifactEventProperties.PipelineTriggering, required: false);
string pipelineVersionToDownload = context.GetInput(ArtifactEventProperties.PipelineVersionToDownload, required: false);
string targetPath = context.GetInput(DownloadPath, required: true);
string environmentBuildId = context.Variables.GetValueOrDefault(BuildVariables.BuildId)?.Value ?? string.Empty; // BuildID provided by environment.
string itemPattern = context.GetInput(ArtifactEventProperties.ItemPattern, required: false);
string projectName = context.GetInput(ArtifactEventProperties.Project, required: false);
string tags = context.GetInput(ArtifactEventProperties.Tags, required: false);
string userSpecifiedpipelineId = context.GetInput(pipelineRunId, required: false);
string defaultWorkingDirectory = context.Variables.GetValueOrDefault("system.defaultworkingdirectory").Value;
targetPath = Path.IsPathFullyQualified(targetPath) ? targetPath : Path.GetFullPath(Path.Combine(defaultWorkingDirectory, targetPath));
bool onPrem = !String.Equals(context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.ServerType)?.Value, "Hosted", StringComparison.OrdinalIgnoreCase);
if (onPrem)
{
throw new InvalidOperationException(StringUtil.Loc("OnPremIsNotSupported"));
}
if (!PipelineArtifactPathHelper.IsValidArtifactName(artifactName))
{
throw new ArgumentException(StringUtil.Loc("ArtifactNameIsNotValid", artifactName));
}
string[] minimatchPatterns = itemPattern.Split(
new[] { "\n" },
StringSplitOptions.RemoveEmptyEntries
);
string[] tagsInput = tags.Split(
new[] { "," },
StringSplitOptions.None
);
PipelineArtifactServer server = new PipelineArtifactServer(tracer);
PipelineArtifactDownloadParameters downloadParameters;
if (sourceRun == sourceRunCurrent)
{
// TODO: use a constant for project id, which is currently defined in Microsoft.VisualStudio.Services.Agent.Constants.Variables.System.TeamProjectId (Ting)
string projectIdStr = context.Variables.GetValueOrDefault("system.teamProjectId")?.Value;
if (String.IsNullOrEmpty(projectIdStr))
{
throw new ArgumentNullException("Project ID cannot be null.");
}
Guid projectId = Guid.Parse(projectIdStr);
ArgUtil.NotEmpty(projectId, nameof(projectId));
int pipelineId = 0;
if (int.TryParse(environmentBuildId, out pipelineId) && pipelineId != 0)
{
context.Output(StringUtil.Loc("DownloadingFromBuild", pipelineId));
}
else
{
string hostType = context.Variables.GetValueOrDefault("system.hosttype")?.Value;
if (string.Equals(hostType, "Release", StringComparison.OrdinalIgnoreCase) ||
string.Equals(hostType, "DeploymentGroup", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(StringUtil.Loc("BuildIdIsNotAvailable", hostType ?? string.Empty, hostType ?? string.Empty));
}
else if (!string.Equals(hostType, "Build", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(StringUtil.Loc("CannotDownloadFromCurrentEnvironment", hostType ?? string.Empty));
}
else
{
// This should not happen since the build id comes from build environment. But a user may override that so we must be careful.
throw new ArgumentException(StringUtil.Loc("BuildIdIsNotValid", environmentBuildId));
}
}
downloadParameters = new PipelineArtifactDownloadParameters
{
ProjectRetrievalOptions = BuildArtifactRetrievalOptions.RetrieveByProjectId,
ProjectId = projectId,
PipelineId = pipelineId,
ArtifactName = artifactName,
TargetDirectory = targetPath,
MinimatchFilters = minimatchPatterns,
MinimatchFilterWithArtifactName = true
};
}
else if (sourceRun == sourceRunSpecific)
{
if (String.IsNullOrEmpty(projectName))
{
throw new ArgumentNullException("Project Name cannot be null.");
}
Guid projectId = Guid.Parse(projectName);
int? pipelineId = null;
bool pipelineTriggeringBool = false;
if (bool.TryParse(pipelineTriggering, out pipelineTriggeringBool) && pipelineTriggeringBool)
{
string triggeringPipeline = context.Variables.GetValueOrDefault("build.triggeredBy.buildId")?.Value;
if (!string.IsNullOrEmpty(triggeringPipeline))
{
pipelineId = int.Parse(triggeringPipeline);
}
}
if (!pipelineId.HasValue)
{
if (pipelineVersionToDownload == pipelineVersionToDownloadLatest)
{
pipelineId = await this.GetPipelineIdAsync(context, pipelineDefinition, pipelineVersionToDownload, projectName, tagsInput);
}
else if (pipelineVersionToDownload == pipelineVersionToDownloadSpecific)
{
pipelineId = Int32.Parse(userSpecifiedpipelineId);
}
else if (pipelineVersionToDownload == pipelineVersionToDownloadLatestFromBranch)
{
pipelineId = await this.GetPipelineIdAsync(context, pipelineDefinition, pipelineVersionToDownload, projectName, tagsInput, branchName);
}
else
{
throw new InvalidOperationException("Unreachable code!");
}
}
context.Output(StringUtil.Loc("DownloadingFromBuild", pipelineId));
downloadParameters = new PipelineArtifactDownloadParameters
{
ProjectRetrievalOptions = BuildArtifactRetrievalOptions.RetrieveByProjectName,
ProjectName = projectName,
ProjectId = projectId,
PipelineId = pipelineId.Value,
ArtifactName = artifactName,
TargetDirectory = targetPath,
MinimatchFilters = minimatchPatterns,
MinimatchFilterWithArtifactName = true
};
}
else
{
throw new InvalidOperationException($"Build type '{sourceRun}' is not recognized.");
}
string fullPath = this.CreateDirectoryIfDoesntExist(targetPath);
DownloadOptions downloadOptions;
if (string.IsNullOrEmpty(downloadParameters.ArtifactName))
{
downloadOptions = DownloadOptions.MultiDownload;
}
else
{
downloadOptions = DownloadOptions.SingleDownload;
}
context.Output(StringUtil.Loc("DownloadArtifactTo", targetPath));
await server.DownloadAsyncV2(context, downloadParameters, downloadOptions, token);
context.Output(StringUtil.Loc("DownloadArtifactFinished"));
}
protected virtual string GetArtifactName(AgentTaskPluginExecutionContext context)
{
return context.GetInput(ArtifactEventProperties.ArtifactName, required: true);
}
private string CreateDirectoryIfDoesntExist(string targetPath)
{
string fullPath = Path.GetFullPath(targetPath);
bool dirExists = Directory.Exists(fullPath);
if (!dirExists)
{
Directory.CreateDirectory(fullPath);
}
return fullPath;
}
private async Task<int> GetPipelineIdAsync(AgentTaskPluginExecutionContext context, string pipelineDefinition, string pipelineVersionToDownload, string project, string[] tagFilters, string branchName = null)
{
var definitions = new List<int>() { Int32.Parse(pipelineDefinition) };
VssConnection connection = context.VssConnection;
BuildHttpClient buildHttpClient = connection.GetClient<BuildHttpClient>();
List<Build> list;
if (pipelineVersionToDownload == "latest")
{
list = await buildHttpClient.GetBuildsAsync(project, definitions, tagFilters: tagFilters, queryOrder: BuildQueryOrder.FinishTimeDescending, resultFilter: BuildResult.Succeeded);
}
else if (pipelineVersionToDownload == "latestFromBranch")
{
list = await buildHttpClient.GetBuildsAsync(project, definitions, branchName: branchName, tagFilters: tagFilters, queryOrder: BuildQueryOrder.FinishTimeDescending, resultFilter: BuildResult.Succeeded);
}
else
{
throw new InvalidOperationException("Unreachable code!");
}
if (list.Count > 0)
{
return list.First().Id;
}
else
{
throw new ArgumentException("No builds currently exist in the build definition supplied.");
}
}
}
} | 49.492701 | 217 | 0.626945 | [
"MIT"
] | Loovax/azure-pipelines-agent | src/Agent.Plugins/PipelineArtifact/PipelineArtifactPluginV2.cs | 13,563 | C# |
using System;
using System.Threading;
namespace Pat.Subscriber.IntegrationTests.Helpers
{
public class MessageWaiter<T>
{
private readonly EventWaitHandle _messageReceivedWaiter;
private CapturedMessage<T> _message;
public MessageWaiter(MessageReceivedNotifier<T> messageNotifier, Func<CapturedMessage<T>, bool> predicate)
{
_messageReceivedWaiter = new EventWaitHandle(false, EventResetMode.AutoReset);
messageNotifier.MessageReceived += (sender, args) =>
{
if (predicate(args.CapturedMessage))
{
_message = args.CapturedMessage;
_messageReceivedWaiter.Set();
}
};
}
public CapturedMessage<T> WaitOne(int millisecondsTimeout = 60000)
{
_messageReceivedWaiter.WaitOne(millisecondsTimeout);
return _message;
}
}
} | 30.741935 | 114 | 0.611752 | [
"Apache-2.0"
] | Bigtalljosh/Pat.Subscriber | Pat.Subscriber.IntegrationTests/Helpers/MessageWaiter.cs | 955 | C# |
namespace ASLHelper.UnityHelper;
public class MonoImage
{
public string Name { get; internal set; }
public nint Address { get; internal set; }
public int ClassCount { get; internal set; }
public nint ClassCache { get; internal set; }
}
| 25.4 | 49 | 0.69685 | [
"MIT"
] | just-ero/asl-help | LiveSplit.ASLHelper/UnityHelper/MonoHelpers/MonoObjects/MonoImage.cs | 256 | 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 mq-2017-11-27.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.MQ.Model;
using Amazon.MQ.Model.Internal.MarshallTransformations;
using Amazon.MQ.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.MQ
{
/// <summary>
/// Implementation for accessing MQ
///
/// Amazon MQ is a managed message broker service for Apache ActiveMQ that makes it easy
/// to set up and operate message brokers in the cloud. A message broker allows software
/// applications and components to communicate using various programming languages, operating
/// systems, and formal messaging protocols.
/// </summary>
public partial class AmazonMQClient : AmazonServiceClient, IAmazonMQ
{
private static IServiceMetadata serviceMetadata = new AmazonMQMetadata();
private IMQPaginatorFactory _paginators;
/// <summary>
/// Paginators for the service
/// </summary>
public IMQPaginatorFactory Paginators
{
get
{
if (this._paginators == null)
{
this._paginators = new MQPaginatorFactory(this);
}
return this._paginators;
}
}
#region Constructors
/// <summary>
/// Constructs AmazonMQClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonMQClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMQConfig()) { }
/// <summary>
/// Constructs AmazonMQClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonMQClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMQConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonMQClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonMQClient Configuration Object</param>
public AmazonMQClient(AmazonMQConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonMQClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonMQClient(AWSCredentials credentials)
: this(credentials, new AmazonMQConfig())
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonMQClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonMQConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Credentials and an
/// AmazonMQClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonMQClient Configuration Object</param>
public AmazonMQClient(AWSCredentials credentials, AmazonMQConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMQConfig())
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMQConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMQClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonMQClient Configuration Object</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonMQConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMQConfig())
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMQConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMQClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMQClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonMQClient Configuration Object</param>
public AmazonMQClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonMQConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateBroker
/// <summary>
/// Creates a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateBroker service method.</param>
///
/// <returns>The response from the CreateBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.UnauthorizedException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateBroker">REST API Reference for CreateBroker Operation</seealso>
public virtual CreateBrokerResponse CreateBroker(CreateBrokerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateBrokerResponseUnmarshaller.Instance;
return Invoke<CreateBrokerResponse>(request, options);
}
/// <summary>
/// Creates a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateBroker service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.UnauthorizedException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateBroker">REST API Reference for CreateBroker Operation</seealso>
public virtual Task<CreateBrokerResponse> CreateBrokerAsync(CreateBrokerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateBrokerResponseUnmarshaller.Instance;
return InvokeAsync<CreateBrokerResponse>(request, options, cancellationToken);
}
#endregion
#region CreateConfiguration
/// <summary>
/// Creates a new configuration for the specified configuration name. Amazon MQ uses the
/// default configuration (the engine type and version).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateConfiguration service method.</param>
///
/// <returns>The response from the CreateConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateConfiguration">REST API Reference for CreateConfiguration Operation</seealso>
public virtual CreateConfigurationResponse CreateConfiguration(CreateConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConfigurationResponseUnmarshaller.Instance;
return Invoke<CreateConfigurationResponse>(request, options);
}
/// <summary>
/// Creates a new configuration for the specified configuration name. Amazon MQ uses the
/// default configuration (the engine type and version).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateConfiguration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateConfiguration">REST API Reference for CreateConfiguration Operation</seealso>
public virtual Task<CreateConfigurationResponse> CreateConfigurationAsync(CreateConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConfigurationResponseUnmarshaller.Instance;
return InvokeAsync<CreateConfigurationResponse>(request, options, cancellationToken);
}
#endregion
#region CreateTags
/// <summary>
/// Add a tag to a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTags service method.</param>
///
/// <returns>The response from the CreateTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateTags">REST API Reference for CreateTags Operation</seealso>
public virtual CreateTagsResponse CreateTags(CreateTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTagsResponseUnmarshaller.Instance;
return Invoke<CreateTagsResponse>(request, options);
}
/// <summary>
/// Add a tag to a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateTags">REST API Reference for CreateTags Operation</seealso>
public virtual Task<CreateTagsResponse> CreateTagsAsync(CreateTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTagsResponseUnmarshaller.Instance;
return InvokeAsync<CreateTagsResponse>(request, options, cancellationToken);
}
#endregion
#region CreateUser
/// <summary>
/// Creates an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateUser service method.</param>
///
/// <returns>The response from the CreateUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateUser">REST API Reference for CreateUser Operation</seealso>
public virtual CreateUserResponse CreateUser(CreateUserRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateUserResponseUnmarshaller.Instance;
return Invoke<CreateUserResponse>(request, options);
}
/// <summary>
/// Creates an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateUser service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateUser">REST API Reference for CreateUser Operation</seealso>
public virtual Task<CreateUserResponse> CreateUserAsync(CreateUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateUserResponseUnmarshaller.Instance;
return InvokeAsync<CreateUserResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteBroker
/// <summary>
/// Deletes a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBroker service method.</param>
///
/// <returns>The response from the DeleteBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteBroker">REST API Reference for DeleteBroker Operation</seealso>
public virtual DeleteBrokerResponse DeleteBroker(DeleteBrokerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBrokerResponseUnmarshaller.Instance;
return Invoke<DeleteBrokerResponse>(request, options);
}
/// <summary>
/// Deletes a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteBroker service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteBroker">REST API Reference for DeleteBroker Operation</seealso>
public virtual Task<DeleteBrokerResponse> DeleteBrokerAsync(DeleteBrokerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteBrokerResponseUnmarshaller.Instance;
return InvokeAsync<DeleteBrokerResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteTags
/// <summary>
/// Removes a tag from a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteTags service method.</param>
///
/// <returns>The response from the DeleteTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteTags">REST API Reference for DeleteTags Operation</seealso>
public virtual DeleteTagsResponse DeleteTags(DeleteTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteTagsResponseUnmarshaller.Instance;
return Invoke<DeleteTagsResponse>(request, options);
}
/// <summary>
/// Removes a tag from a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteTags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteTags">REST API Reference for DeleteTags Operation</seealso>
public virtual Task<DeleteTagsResponse> DeleteTagsAsync(DeleteTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteTagsResponseUnmarshaller.Instance;
return InvokeAsync<DeleteTagsResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteUser
/// <summary>
/// Deletes an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteUser service method.</param>
///
/// <returns>The response from the DeleteUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteUser">REST API Reference for DeleteUser Operation</seealso>
public virtual DeleteUserResponse DeleteUser(DeleteUserRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteUserResponseUnmarshaller.Instance;
return Invoke<DeleteUserResponse>(request, options);
}
/// <summary>
/// Deletes an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteUser service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteUser">REST API Reference for DeleteUser Operation</seealso>
public virtual Task<DeleteUserResponse> DeleteUserAsync(DeleteUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteUserResponseUnmarshaller.Instance;
return InvokeAsync<DeleteUserResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeBroker
/// <summary>
/// Returns information about the specified broker.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBroker service method.</param>
///
/// <returns>The response from the DescribeBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBroker">REST API Reference for DescribeBroker Operation</seealso>
public virtual DescribeBrokerResponse DescribeBroker(DescribeBrokerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerResponseUnmarshaller.Instance;
return Invoke<DescribeBrokerResponse>(request, options);
}
/// <summary>
/// Returns information about the specified broker.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBroker service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBroker">REST API Reference for DescribeBroker Operation</seealso>
public virtual Task<DescribeBrokerResponse> DescribeBrokerAsync(DescribeBrokerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerResponseUnmarshaller.Instance;
return InvokeAsync<DescribeBrokerResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeBrokerEngineTypes
/// <summary>
/// Describe available engine types and versions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBrokerEngineTypes service method.</param>
///
/// <returns>The response from the DescribeBrokerEngineTypes service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBrokerEngineTypes">REST API Reference for DescribeBrokerEngineTypes Operation</seealso>
public virtual DescribeBrokerEngineTypesResponse DescribeBrokerEngineTypes(DescribeBrokerEngineTypesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerEngineTypesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerEngineTypesResponseUnmarshaller.Instance;
return Invoke<DescribeBrokerEngineTypesResponse>(request, options);
}
/// <summary>
/// Describe available engine types and versions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBrokerEngineTypes service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeBrokerEngineTypes service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBrokerEngineTypes">REST API Reference for DescribeBrokerEngineTypes Operation</seealso>
public virtual Task<DescribeBrokerEngineTypesResponse> DescribeBrokerEngineTypesAsync(DescribeBrokerEngineTypesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerEngineTypesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerEngineTypesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeBrokerEngineTypesResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeBrokerInstanceOptions
/// <summary>
/// Describe available broker instance options.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBrokerInstanceOptions service method.</param>
///
/// <returns>The response from the DescribeBrokerInstanceOptions service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBrokerInstanceOptions">REST API Reference for DescribeBrokerInstanceOptions Operation</seealso>
public virtual DescribeBrokerInstanceOptionsResponse DescribeBrokerInstanceOptions(DescribeBrokerInstanceOptionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerInstanceOptionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerInstanceOptionsResponseUnmarshaller.Instance;
return Invoke<DescribeBrokerInstanceOptionsResponse>(request, options);
}
/// <summary>
/// Describe available broker instance options.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeBrokerInstanceOptions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeBrokerInstanceOptions service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBrokerInstanceOptions">REST API Reference for DescribeBrokerInstanceOptions Operation</seealso>
public virtual Task<DescribeBrokerInstanceOptionsResponse> DescribeBrokerInstanceOptionsAsync(DescribeBrokerInstanceOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeBrokerInstanceOptionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeBrokerInstanceOptionsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeBrokerInstanceOptionsResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeConfiguration
/// <summary>
/// Returns information about the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConfiguration service method.</param>
///
/// <returns>The response from the DescribeConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfiguration">REST API Reference for DescribeConfiguration Operation</seealso>
public virtual DescribeConfigurationResponse DescribeConfiguration(DescribeConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConfigurationResponseUnmarshaller.Instance;
return Invoke<DescribeConfigurationResponse>(request, options);
}
/// <summary>
/// Returns information about the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConfiguration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfiguration">REST API Reference for DescribeConfiguration Operation</seealso>
public virtual Task<DescribeConfigurationResponse> DescribeConfigurationAsync(DescribeConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConfigurationResponseUnmarshaller.Instance;
return InvokeAsync<DescribeConfigurationResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeConfigurationRevision
/// <summary>
/// Returns the specified configuration revision for the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRevision service method.</param>
///
/// <returns>The response from the DescribeConfigurationRevision service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfigurationRevision">REST API Reference for DescribeConfigurationRevision Operation</seealso>
public virtual DescribeConfigurationRevisionResponse DescribeConfigurationRevision(DescribeConfigurationRevisionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConfigurationRevisionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConfigurationRevisionResponseUnmarshaller.Instance;
return Invoke<DescribeConfigurationRevisionResponse>(request, options);
}
/// <summary>
/// Returns the specified configuration revision for the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRevision service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeConfigurationRevision service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfigurationRevision">REST API Reference for DescribeConfigurationRevision Operation</seealso>
public virtual Task<DescribeConfigurationRevisionResponse> DescribeConfigurationRevisionAsync(DescribeConfigurationRevisionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeConfigurationRevisionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeConfigurationRevisionResponseUnmarshaller.Instance;
return InvokeAsync<DescribeConfigurationRevisionResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeUser
/// <summary>
/// Returns information about an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeUser service method.</param>
///
/// <returns>The response from the DescribeUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
public virtual DescribeUserResponse DescribeUser(DescribeUserRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeUserResponseUnmarshaller.Instance;
return Invoke<DescribeUserResponse>(request, options);
}
/// <summary>
/// Returns information about an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeUser service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
public virtual Task<DescribeUserResponse> DescribeUserAsync(DescribeUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeUserResponseUnmarshaller.Instance;
return InvokeAsync<DescribeUserResponse>(request, options, cancellationToken);
}
#endregion
#region ListBrokers
/// <summary>
/// Returns a list of all brokers.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBrokers service method.</param>
///
/// <returns>The response from the ListBrokers service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListBrokers">REST API Reference for ListBrokers Operation</seealso>
public virtual ListBrokersResponse ListBrokers(ListBrokersRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBrokersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBrokersResponseUnmarshaller.Instance;
return Invoke<ListBrokersResponse>(request, options);
}
/// <summary>
/// Returns a list of all brokers.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListBrokers service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListBrokers service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListBrokers">REST API Reference for ListBrokers Operation</seealso>
public virtual Task<ListBrokersResponse> ListBrokersAsync(ListBrokersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListBrokersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListBrokersResponseUnmarshaller.Instance;
return InvokeAsync<ListBrokersResponse>(request, options, cancellationToken);
}
#endregion
#region ListConfigurationRevisions
/// <summary>
/// Returns a list of all revisions for the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListConfigurationRevisions service method.</param>
///
/// <returns>The response from the ListConfigurationRevisions service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurationRevisions">REST API Reference for ListConfigurationRevisions Operation</seealso>
public virtual ListConfigurationRevisionsResponse ListConfigurationRevisions(ListConfigurationRevisionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConfigurationRevisionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConfigurationRevisionsResponseUnmarshaller.Instance;
return Invoke<ListConfigurationRevisionsResponse>(request, options);
}
/// <summary>
/// Returns a list of all revisions for the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListConfigurationRevisions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListConfigurationRevisions service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurationRevisions">REST API Reference for ListConfigurationRevisions Operation</seealso>
public virtual Task<ListConfigurationRevisionsResponse> ListConfigurationRevisionsAsync(ListConfigurationRevisionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConfigurationRevisionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConfigurationRevisionsResponseUnmarshaller.Instance;
return InvokeAsync<ListConfigurationRevisionsResponse>(request, options, cancellationToken);
}
#endregion
#region ListConfigurations
/// <summary>
/// Returns a list of all configurations.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListConfigurations service method.</param>
///
/// <returns>The response from the ListConfigurations service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurations">REST API Reference for ListConfigurations Operation</seealso>
public virtual ListConfigurationsResponse ListConfigurations(ListConfigurationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConfigurationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConfigurationsResponseUnmarshaller.Instance;
return Invoke<ListConfigurationsResponse>(request, options);
}
/// <summary>
/// Returns a list of all configurations.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListConfigurations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListConfigurations service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurations">REST API Reference for ListConfigurations Operation</seealso>
public virtual Task<ListConfigurationsResponse> ListConfigurationsAsync(ListConfigurationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConfigurationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConfigurationsResponseUnmarshaller.Instance;
return InvokeAsync<ListConfigurationsResponse>(request, options, cancellationToken);
}
#endregion
#region ListTags
/// <summary>
/// Lists tags for a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTags service method.</param>
///
/// <returns>The response from the ListTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListTags">REST API Reference for ListTags Operation</seealso>
public virtual ListTagsResponse ListTags(ListTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsResponseUnmarshaller.Instance;
return Invoke<ListTagsResponse>(request, options);
}
/// <summary>
/// Lists tags for a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTags service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListTags service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListTags">REST API Reference for ListTags Operation</seealso>
public virtual Task<ListTagsResponse> ListTagsAsync(ListTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsResponseUnmarshaller.Instance;
return InvokeAsync<ListTagsResponse>(request, options, cancellationToken);
}
#endregion
#region ListUsers
/// <summary>
/// Returns a list of all ActiveMQ users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListUsers service method.</param>
///
/// <returns>The response from the ListUsers service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListUsers">REST API Reference for ListUsers Operation</seealso>
public virtual ListUsersResponse ListUsers(ListUsersRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsersResponseUnmarshaller.Instance;
return Invoke<ListUsersResponse>(request, options);
}
/// <summary>
/// Returns a list of all ActiveMQ users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListUsers service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListUsers service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListUsers">REST API Reference for ListUsers Operation</seealso>
public virtual Task<ListUsersResponse> ListUsersAsync(ListUsersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsersResponseUnmarshaller.Instance;
return InvokeAsync<ListUsersResponse>(request, options, cancellationToken);
}
#endregion
#region RebootBroker
/// <summary>
/// Reboots a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RebootBroker service method.</param>
///
/// <returns>The response from the RebootBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/RebootBroker">REST API Reference for RebootBroker Operation</seealso>
public virtual RebootBrokerResponse RebootBroker(RebootBrokerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RebootBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = RebootBrokerResponseUnmarshaller.Instance;
return Invoke<RebootBrokerResponse>(request, options);
}
/// <summary>
/// Reboots a broker. Note: This API is asynchronous.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RebootBroker service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RebootBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/RebootBroker">REST API Reference for RebootBroker Operation</seealso>
public virtual Task<RebootBrokerResponse> RebootBrokerAsync(RebootBrokerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RebootBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = RebootBrokerResponseUnmarshaller.Instance;
return InvokeAsync<RebootBrokerResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateBroker
/// <summary>
/// Adds a pending configuration change to a broker.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateBroker service method.</param>
///
/// <returns>The response from the UpdateBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateBroker">REST API Reference for UpdateBroker Operation</seealso>
public virtual UpdateBrokerResponse UpdateBroker(UpdateBrokerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateBrokerResponseUnmarshaller.Instance;
return Invoke<UpdateBrokerResponse>(request, options);
}
/// <summary>
/// Adds a pending configuration change to a broker.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateBroker service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateBroker service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateBroker">REST API Reference for UpdateBroker Operation</seealso>
public virtual Task<UpdateBrokerResponse> UpdateBrokerAsync(UpdateBrokerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateBrokerRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateBrokerResponseUnmarshaller.Instance;
return InvokeAsync<UpdateBrokerResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateConfiguration
/// <summary>
/// Updates the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateConfiguration service method.</param>
///
/// <returns>The response from the UpdateConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateConfiguration">REST API Reference for UpdateConfiguration Operation</seealso>
public virtual UpdateConfigurationResponse UpdateConfiguration(UpdateConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateConfigurationResponseUnmarshaller.Instance;
return Invoke<UpdateConfigurationResponse>(request, options);
}
/// <summary>
/// Updates the specified configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateConfiguration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateConfiguration service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateConfiguration">REST API Reference for UpdateConfiguration Operation</seealso>
public virtual Task<UpdateConfigurationResponse> UpdateConfigurationAsync(UpdateConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateConfigurationResponseUnmarshaller.Instance;
return InvokeAsync<UpdateConfigurationResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateUser
/// <summary>
/// Updates the information for an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateUser service method.</param>
///
/// <returns>The response from the UpdateUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateUser">REST API Reference for UpdateUser Operation</seealso>
public virtual UpdateUserResponse UpdateUser(UpdateUserRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateUserResponseUnmarshaller.Instance;
return Invoke<UpdateUserResponse>(request, options);
}
/// <summary>
/// Updates the information for an ActiveMQ user.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateUser service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateUser service method, as returned by MQ.</returns>
/// <exception cref="Amazon.MQ.Model.BadRequestException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ConflictException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.ForbiddenException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.InternalServerErrorException">
/// Returns information about an error.
/// </exception>
/// <exception cref="Amazon.MQ.Model.NotFoundException">
/// Returns information about an error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateUser">REST API Reference for UpdateUser Operation</seealso>
public virtual Task<UpdateUserResponse> UpdateUserAsync(UpdateUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateUserResponseUnmarshaller.Instance;
return InvokeAsync<UpdateUserResponse>(request, options, cancellationToken);
}
#endregion
}
} | 49.39023 | 230 | 0.651917 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/MQ/Generated/_bcl45/AmazonMQClient.cs | 83,914 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeCommit.Model
{
/// <summary>
/// Either the enum is not in a valid format, or the specified file version enum is not
/// valid in respect to the current file version.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InvalidRelativeFileVersionEnumException : AmazonCodeCommitException
{
/// <summary>
/// Constructs a new InvalidRelativeFileVersionEnumException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidRelativeFileVersionEnumException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidRelativeFileVersionEnumException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidRelativeFileVersionEnumException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidRelativeFileVersionEnumException
/// </summary>
/// <param name="innerException"></param>
public InvalidRelativeFileVersionEnumException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidRelativeFileVersionEnumException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRelativeFileVersionEnumException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidRelativeFileVersionEnumException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRelativeFileVersionEnumException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidRelativeFileVersionEnumException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidRelativeFileVersionEnumException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 49.912 | 182 | 0.676871 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/InvalidRelativeFileVersionEnumException.cs | 6,239 | C# |
#nullable enable
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Elffy.UI
{
/// <summary>Root panel of UI tree</summary>
public sealed class RootPanel : Panel
{
private readonly UILayer _uiLayer;
private Control? _relayoutRoot;
private LayoutExecutionType _layoutExecutionType;
private bool _relayoutRequested;
internal UILayer UILayer => _uiLayer;
/// <summary>Get or set layout execution type.</summary>
public LayoutExecutionType LayoutExecutionType
{
get => _layoutExecutionType;
set => _layoutExecutionType = value;
}
/// <summary><see cref="RootPanel"/> doesn't support it. It throws <see cref="InvalidOperationException"/>.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("RootPanel does not support 'Margin'.", true)]
public new ref LayoutThickness Margin => throw new InvalidOperationException($"{nameof(RootPanel)} does not support '{nameof(Margin)}'.");
internal RootPanel(UILayer uiLayer)
{
Debug.Assert(uiLayer is not null);
_uiLayer = uiLayer;
_relayoutRequested = true;
}
internal void Initialize()
{
SetAsRootControl();
Renderable.ActivateOnUILayer(UILayer);
Renderable.BeforeRendering += ExecuteRelayout;
}
private void ExecuteRelayout(Renderable sender, in Matrix4 model, in Matrix4 view, in Matrix4 projection)
{
var type = _layoutExecutionType;
if(type == LayoutExecutionType.Adaptive) {
Relayout(false);
}
else if(type == LayoutExecutionType.EveryFrame) {
Relayout(true);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Relayout(bool forceToRelayout = false)
{
if(_relayoutRequested || forceToRelayout) {
_relayoutRequested = false;
ControlLayoutHelper.LayoutChildrenRecursively(this);
}
}
public void RequestRelayout()
{
_relayoutRequested = true;
}
}
}
| 32.352113 | 146 | 0.615586 | [
"MIT"
] | ikorin24/Elffy | src/Elffy.Engine/UI/RootPanel.cs | 2,299 | 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Microsoft.AspNet.WebHooks.Filters;
using Microsoft.AspNet.WebHooks.Properties;
using Microsoft.AspNet.WebHooks.Routes;
namespace Microsoft.AspNet.WebHooks.Controllers
{
/// <summary>
/// The <see cref="WebHookRegistrationsController"/> allows the caller to create, modify, and manage WebHooks
/// through a REST-style interface.
/// </summary>
[Authorize]
[RoutePrefix("api/webhooks/registrations")]
public class WebHookRegistrationsController : ApiController
{
private IWebHookRegistrationsManager _registrationsManager;
/// <summary>
/// Gets all registered WebHooks for a given user.
/// </summary>
/// <returns>A collection containing the registered <see cref="WebHook"/> instances for a given user.</returns>
[Route("")]
public async Task<IEnumerable<WebHook>> Get()
{
try
{
var webHooks = await _registrationsManager.GetWebHooksAsync(User, RemovePrivateFilters);
return webHooks;
}
catch (Exception ex)
{
Configuration.DependencyResolver.GetLogger().Error(ex.Message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ex);
throw new HttpResponseException(error);
}
}
/// <summary>
/// Looks up a registered WebHook with the given <paramref name="id"/> for a given user.
/// </summary>
/// <returns>The registered <see cref="WebHook"/> instance for a given user.</returns>
[Route("{id}", Name = WebHookRouteNames.RegistrationLookupAction)]
[HttpGet]
[ResponseType(typeof(WebHook))]
public async Task<IHttpActionResult> Lookup(string id)
{
try
{
var webHook = await _registrationsManager.LookupWebHookAsync(User, id, RemovePrivateFilters);
if (webHook != null)
{
return Ok(webHook);
}
return NotFound();
}
catch (Exception ex)
{
Configuration.DependencyResolver.GetLogger().Error(ex.Message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ex);
throw new HttpResponseException(error);
}
}
/// <summary>
/// Registers a new WebHook for a given user.
/// </summary>
/// <param name="webHook">The <see cref="WebHook"/> to create.</param>
[Route("")]
[ValidateModel]
[ResponseType(typeof(WebHook))]
public async Task<IHttpActionResult> Post(WebHook webHook)
{
if (webHook == null)
{
return BadRequest();
}
try
{
// Validate the provided WebHook ID (or force one to be created on server side)
var idValidator = Configuration.DependencyResolver.GetIdValidator();
await idValidator.ValidateIdAsync(Request, webHook);
// Validate other parts of WebHook
await _registrationsManager.VerifySecretAsync(webHook);
await _registrationsManager.VerifyFiltersAsync(webHook);
await _registrationsManager.VerifyAddressAsync(webHook);
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrationFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Info(message);
var error = Request.CreateErrorResponse(HttpStatusCode.BadRequest, message, ex);
return ResponseMessage(error);
}
try
{
// Add WebHook for this user.
var result = await _registrationsManager.AddWebHookAsync(User, webHook, AddPrivateFilters);
if (result == StoreResult.Success)
{
return CreatedAtRoute(WebHookRouteNames.RegistrationLookupAction, new { id = webHook.Id }, webHook);
}
return CreateHttpResult(result);
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrationFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Error(message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message, ex);
return ResponseMessage(error);
}
}
/// <summary>
/// Updates an existing WebHook registration.
/// </summary>
/// <param name="id">The WebHook ID.</param>
/// <param name="webHook">The new <see cref="WebHook"/> to use.</param>
[Route("{id}")]
[ValidateModel]
public async Task<IHttpActionResult> Put(string id, WebHook webHook)
{
if (webHook == null)
{
return BadRequest();
}
if (!string.Equals(id, webHook.Id, StringComparison.OrdinalIgnoreCase))
{
return BadRequest();
}
try
{
// Validate parts of WebHook
await _registrationsManager.VerifySecretAsync(webHook);
await _registrationsManager.VerifyFiltersAsync(webHook);
await _registrationsManager.VerifyAddressAsync(webHook);
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrationFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Info(message);
var error = Request.CreateErrorResponse(HttpStatusCode.BadRequest, message, ex);
return ResponseMessage(error);
}
try
{
// Update WebHook for this user
var result = await _registrationsManager.UpdateWebHookAsync(User, webHook, AddPrivateFilters);
return CreateHttpResult(result);
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_UpdateFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Error(message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message, ex);
return ResponseMessage(error);
}
}
/// <summary>
/// Deletes an existing WebHook registration.
/// </summary>
/// <param name="id">The WebHook ID.</param>
[Route("{id}")]
public async Task<IHttpActionResult> Delete(string id)
{
try
{
var result = await _registrationsManager.DeleteWebHookAsync(User, id);
return CreateHttpResult(result);
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_DeleteFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Error(message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message, ex);
return ResponseMessage(error);
}
}
/// <summary>
/// Deletes all existing WebHook registrations.
/// </summary>
[Route("")]
public async Task<IHttpActionResult> DeleteAll()
{
try
{
await _registrationsManager.DeleteAllWebHooksAsync(User);
return Ok();
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_DeleteAllFailure, ex.Message);
Configuration.DependencyResolver.GetLogger().Error(message, ex);
var error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message, ex);
return ResponseMessage(error);
}
}
/// <inheritdoc />
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
_registrationsManager = Configuration.DependencyResolver.GetRegistrationsManager();
}
/// <summary>
/// Removes all private (server side) filters from the given <paramref name="webHook"/>.
/// </summary>
protected virtual Task RemovePrivateFilters(string user, WebHook webHook)
{
if (webHook == null)
{
throw new ArgumentNullException(nameof(webHook));
}
var filters = webHook.Filters.Where(f => f.StartsWith(WebHookRegistrar.PrivateFilterPrefix, StringComparison.OrdinalIgnoreCase)).ToArray();
foreach (var filter in filters)
{
webHook.Filters.Remove(filter);
}
return Task.FromResult(true);
}
/// <summary>
/// Executes all <see cref="IWebHookRegistrar"/> instances for server side manipulation, inspection, or
/// rejection of registrations. This can for example be used to add server side only filters that
/// are not governed by <see cref="IWebHookFilterManager"/>.
/// </summary>
protected virtual async Task AddPrivateFilters(string user, WebHook webHook)
{
var registrars = Configuration.DependencyResolver.GetRegistrars();
foreach (var registrar in registrars)
{
try
{
await registrar.RegisterAsync(Request, webHook);
}
catch (HttpResponseException rex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrarStatusCode, registrar.GetType().Name, typeof(IWebHookRegistrar).Name, rex.Response.StatusCode);
Configuration.DependencyResolver.GetLogger().Info(message);
throw;
}
catch (Exception ex)
{
var message = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrarException, registrar.GetType().Name, typeof(IWebHookRegistrar).Name, ex.Message);
Configuration.DependencyResolver.GetLogger().Error(message, ex);
var response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
throw new HttpResponseException(response);
}
}
}
/// <summary>
/// Creates an <see cref="IHttpActionResult"/> based on the provided <paramref name="result"/>.
/// </summary>
/// <param name="result">The result to use when creating the <see cref="IHttpActionResult"/>.</param>
/// <returns>An initialized <see cref="IHttpActionResult"/>.</returns>
private IHttpActionResult CreateHttpResult(StoreResult result)
{
switch (result)
{
case StoreResult.Success:
return Ok();
case StoreResult.Conflict:
return Conflict();
case StoreResult.NotFound:
return NotFound();
case StoreResult.OperationError:
return BadRequest();
default:
return InternalServerError();
}
}
}
}
| 41.54 | 222 | 0.588509 | [
"Apache-2.0"
] | Mythz123/AspNetWebHooks | src/Microsoft.AspNet.WebHooks.Custom.Api/Controllers/WebHookRegistrationsController.cs | 12,464 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntegrationTesting.Components.Database
{
public class AnimalStore : IAnimalStore
{
private readonly IDatabase _database;
public AnimalStore(IDatabase database)
{
_database = database;
}
public async Task<IList<Animal>> GetAnimals()
{
var results = new List<Animal>();
await using var queryReader = await _database.Query("select * from animals");
while (await queryReader.ReadAsync())
{
results.Add(new(
queryReader.GetInt32(0),
queryReader.GetString(1),
queryReader.GetString(2)
));
}
return results;
}
public async Task<Animal> GetAnimal(int id)
{
var query = "select * from animals where id = (@id) limit 1";
await using var queryReader = await _database.Query(query, new() { ["id"] = id });
if (await queryReader.ReadAsync())
{
return new(
queryReader.GetInt32(0),
queryReader.GetString(1),
queryReader.GetString(2)
);
}
return null;
}
public Task SaveAnimal(Animal animal)
{
return _database.Insert(
"insert into animals (name, type) values (@name, @type)",
new() { ["name"] = animal.Name, ["type"] = animal.Type }
);
}
}
}
| 28.372881 | 94 | 0.51135 | [
"MIT"
] | mirusser/Learning-dontNet | src/Testing/IntegrationTesting/Components/Database/AnimalStore.cs | 1,676 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Microsoft.Protocols.TestTools.StackSdk.Asn1;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr.Mcs
{
/*
Segmentation ::= BIT STRING
{
begin (0),
end (1)
} (SIZE (2))
*/
public class Segmentation : Asn1Object
{
public static readonly int begin = 0;
public static readonly int end = 1;
public bool[] Value;
public Segmentation()
{
Value = new bool[0];
}
public Segmentation(bool[] data)
{
Value = data;
}
protected override bool VerifyConstraints()
{
return Value.Length == 2;
}
public override void PerEncode(IAsn1PerEncodingBuffer buffer)
{
buffer.WriteBit(Value[0]);
buffer.WriteBit(Value[1]);
}
public override void PerDecode(IAsn1DecodingBuffer buffer, bool aligned = true)
{
Value = buffer.ReadBits(2);
}
public override bool Equals(object obj)
{
// If parameter is null or cannot be cast to Asn1Integer return false.
Segmentation p = obj as Segmentation;
if (p == null)
{
return false;
}
// Return true if the fields match.
return this.Value.SequenceEqual(p.Value);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| 24.880597 | 101 | 0.559088 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | ProtoSDK/MS-RDPBCGR/ASNT125/Segmentation.cs | 1,669 | C# |
// Copyright (c) 2019-2021 ReactiveUI Association Incorporated. All rights reserved.
// ReactiveUI Association Incorporated licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace ReactiveMarbles.PropertyChanged.SourceGenerator.Helpers;
internal static class RoslynExtensions
{
public static IEnumerable<SyntaxKind> GetAccessibilityTokens(this Accessibility accessibility) => accessibility switch
{
Accessibility.Public => new[] { SyntaxKind.PublicKeyword },
Accessibility.Internal => new[] { SyntaxKind.InternalKeyword },
Accessibility.Private => new[] { SyntaxKind.PrivateKeyword },
Accessibility.NotApplicable => Array.Empty<SyntaxKind>(),
Accessibility.ProtectedAndInternal => new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword },
Accessibility.Protected => new[] { SyntaxKind.ProtectedKeyword },
Accessibility.ProtectedOrInternal => new[] { SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword },
_ => Array.Empty<SyntaxKind>(),
};
public static string ToNamespaceName(this INamespaceSymbol symbol)
{
var name = symbol.ToDisplayString();
return name.Equals("<global namespace>") ? string.Empty : name;
}
}
| 43.272727 | 122 | 0.742297 | [
"MIT"
] | cabauman/PropertyChanged | src/ReactiveMarbles.PropertyChanged.SourceGenerator/Helpers/RoslynExtensions.cs | 1,430 | C# |
/************************************************************************************
Copyright : Copyright 2017 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.4.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
/// <summary>
/// Allows you to reset VR input tracking with a gamepad button press.
/// </summary>
public class OVRResetOrientation : MonoBehaviour
{
/// <summary>
/// The gamepad button that will reset VR input tracking.
/// </summary>
public OVRInput.RawButton resetButton = OVRInput.RawButton.Y;
/// <summary>
/// Check input and reset orientation if necessary
/// See the input mapping setup in the Unity Integration guide
/// </summary>
void Update()
{
// NOTE: some of the buttons defined in OVRInput.RawButton are not available on the Android game pad controller
if (OVRInput.GetDown(resetButton))
{
//*************************
// reset orientation
//*************************
OVRManager.display.RecenterPose();
}
}
}
| 34.54 | 113 | 0.653156 | [
"MIT"
] | AIRobolab-unilu/vr-teleop | Assets/Oculus/VR/Scripts/Util/OVRResetOrientation.cs | 1,727 | C# |
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:AssemblyInfo.cs
****/
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("DemoAppUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DemoAppUI")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 42.306452 | 105 | 0.691956 | [
"MIT"
] | Bhaskers-Blu-Org2/pmod | samples/DemoApp/__build/vs.build/classic/DemoAppUI/Properties/AssemblyInfo.cs | 2,624 | C# |
using CodeTranslator.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeTranslator.Core.Parser.Components
{
internal class DeclaredFunction : Function
{
public override BasicType FunctionType => BasicType.Statement;
public DeclaredFunction(string content) : base(content)
{
}
}
}
| 20.333333 | 70 | 0.70765 | [
"MIT"
] | asd135hp/CodeTranslator | CodeTranslator/Core/Parser/Components/DeclaredFunction.cs | 368 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace T4FluentNH.Tests.EntityTypes
{
public partial class ETSimpleEntity : Domain.Entity
{
public virtual string Name { get; set; }
public virtual ETCodeListEntity CodeListEntity
{
get { return _codeListEntity; }
set { ResetField(ref _codeListEntity, value, ref _isCodeListEntityCodeSet); }
}
public virtual ETInheritedCodeListEntity InheritCodeListEntity
{
get { return _inheritCodeListEntity; }
set { ResetField(ref _inheritCodeListEntity, value, ref _isInheritCodeListEntityCodeSet); }
}
public virtual ETLengthCodeList LengthCodeListEntity
{
get { return _lengthCodeListEntity; }
set { ResetField(ref _lengthCodeListEntity, value, ref _isLengthCodeListEntityCodeSet); }
}
public virtual ETAttrLengthByIndexCodeList AttrLengthByIndexCodeList
{
get { return _attrLengthByIndexCodeList; }
set { ResetField(ref _attrLengthByIndexCodeList, value, ref _isAttrLengthByIndexCodeListCodeSet); }
}
public virtual ETAttrLengthByPropertyCodeList AttrLengthByPropertyCodeList
{
get { return _attrLengthByPropertyCodeList; }
set { ResetField(ref _attrLengthByPropertyCodeList, value, ref _isAttrLengthByPropertyCodeListCodeSet); }
}
}
}
| 34.409091 | 117 | 0.686262 | [
"MIT"
] | maca88/T4FluentNH | Source/T4FluentNH/T4FluentNH.Tests/EntityTypes/ETSimpleEntity.cs | 1,516 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NullableContext : CSharpTestBase
{
[Fact]
public void EmptyProject()
{
var source = @"";
var comp = CreateCompilation(source);
var expected =
@"";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"#nullable enable
public class Program
{
public object F(object arg) => arg;
}";
var comp = CreateCompilation(new[] { NullableContextAttributeDefinition, source });
var expected =
@"Program
[NullableContext(1)] System.Object! F(System.Object! arg)
System.Object! arg
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var comp = CreateCompilation(NullableContextAttributeDefinition);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source =
@"#nullable enable
public class Program
{
public object F(object arg) => arg;
}";
comp = CreateCompilation(source, references: new[] { ref0 });
var expected =
@"Program
[NullableContext(1)] System.Object! F(System.Object! arg)
System.Object! arg
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_MissingSingleByteConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableContextAttribute : Attribute
{
}
}";
var source2 =
@"public class Program
{
public object F(object arg) => arg;
}";
// C#7
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular7);
comp.VerifyEmitDiagnostics();
// C#8, nullable disabled
comp = CreateCompilation(new[] { source1, source2 }, options: WithNonNullTypesFalse());
comp.VerifyEmitDiagnostics();
// C#8, nullable enabled
comp = CreateCompilation(new[] { source1, source2 }, options: WithNonNullTypesTrue());
comp.VerifyEmitDiagnostics(
// (3,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableContextAttribute..ctor'
// public object F(object arg) => arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute", ".ctor").WithLocation(3, 19));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullableContextAttribute : System.Attribute
{
internal NullableContextAttribute(byte b) { }
}
}";
var source =
@"#pragma warning disable 169
using System.Runtime.CompilerServices;
[assembly: NullableContext(0)]
[module: NullableContext(0)]
[NullableContext(0)]
class Program
{
[NullableContext(0)]object F;
[NullableContext(0)]static object M1() => throw null;
[return: NullableContext(0)]static object M2() => throw null;
static void M3([NullableContext(0)]object arg) { }
}";
// C#7
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7);
verifyDiagnostics(comp);
// C#8
comp = CreateCompilation(new[] { sourceAttribute, source });
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (4,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [module: NullableContext(0)]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(4, 10),
// (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(5, 2),
// (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)]static object M1() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(9, 6));
}
}
[Fact]
public void ExplicitAttribute_WithNullableContext()
{
var sourceAttribute =
@"#nullable enable
namespace System.Runtime.CompilerServices
{
public sealed class NullableContextAttribute : Attribute
{
private object _f1;
private object _f2;
private object _f3;
public NullableContextAttribute(byte b)
{
}
}
}";
var comp = CreateCompilation(sourceAttribute);
var ref0 = comp.EmitToImageReference();
var expected =
@"[NullableContext(1)] [Nullable(0)] System.Runtime.CompilerServices.NullableContextAttribute
NullableContextAttribute(System.Byte b)
System.Byte b
";
AssertNullableAttributes(comp, expected);
var source =
@"#nullable enable
public class Program
{
private object _f1;
private object _f2;
private object _f3;
}";
comp = CreateCompilation(source, references: new[] { ref0 });
expected =
@"[NullableContext(1)] [Nullable(0)] Program
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")]
public void AttributeUsage()
{
var source =
@"#nullable enable
public class Program
{
private object _f1;
private object _f2;
private object _f3;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullableContextAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets = AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Struct;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"#pragma warning disable 169
#pragma warning disable 414
#nullable enable
public class Program
{
private object _f1 = null!;
private object _f2 = null!;
private object _f3 = null!;
}";
var comp = CreateCompilation(source);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void AttributeField()
{
var source =
@"#nullable enable
using System;
using System.Linq;
public class A
{
private object _f1;
private object _f2;
private object _f3;
}
public class B
{
private object? _f1;
private object? _f2;
private object? _f3;
}
class Program
{
static void Main()
{
Console.WriteLine(GetAttributeValue(typeof(A)));
Console.WriteLine(GetAttributeValue(typeof(B)));
}
static byte GetAttributeValue(Type type)
{
var attribute = type.GetCustomAttributes(false).Single(a => a.GetType().Name == ""NullableContextAttribute"");
var field = attribute.GetType().GetField(""Flag"");
return (byte)field.GetValue(attribute);
}
}";
var expectedOutput =
@"1
2";
var expectedAttributes =
@"[NullableContext(1)] [Nullable(0)] A
A()
[NullableContext(2)] [Nullable(0)] B
B()
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: module => AssertNullableAttributes(module, expectedAttributes));
}
[Fact]
public void MostCommonNullableValue()
{
Assert.Null(getMostCommonValue());
Assert.Null(getMostCommonValue((byte?)null));
Assert.Null(getMostCommonValue(null, null));
Assert.Equal((byte)0, getMostCommonValue(0));
Assert.Equal((byte)1, getMostCommonValue(1));
Assert.Equal((byte)2, getMostCommonValue(2));
#if !DEBUG
Assert.Throws<InvalidOperationException>(() => getMostCommonValue(3));
#endif
Assert.Equal((byte)0, getMostCommonValue(0, 0));
Assert.Equal((byte)0, getMostCommonValue(0, 1));
Assert.Equal((byte)0, getMostCommonValue(1, 0));
Assert.Equal((byte)1, getMostCommonValue(1, 1));
Assert.Equal((byte)1, getMostCommonValue(1, 2));
Assert.Equal((byte)1, getMostCommonValue(2, 1));
Assert.Equal((byte)2, getMostCommonValue(2, 2));
#if !DEBUG
Assert.Throws<InvalidOperationException>(() => getMostCommonValue(2, 3));
#endif
Assert.Equal((byte)0, getMostCommonValue(0, null));
Assert.Equal((byte)0, getMostCommonValue(null, 0));
Assert.Equal((byte)1, getMostCommonValue(1, null));
Assert.Equal((byte)1, getMostCommonValue(null, 1));
Assert.Equal((byte)0, getMostCommonValue(0, 1, 2, null));
Assert.Equal((byte)0, getMostCommonValue(null, 2, 1, 0));
Assert.Equal((byte)1, getMostCommonValue(1, 2, null));
Assert.Equal((byte)1, getMostCommonValue(null, 2, 1));
Assert.Equal((byte)2, getMostCommonValue(null, 2, null));
Assert.Equal((byte)0, getMostCommonValue(0, 1, 0));
Assert.Equal((byte)0, getMostCommonValue(1, 0, 0));
Assert.Equal((byte)1, getMostCommonValue(1, 0, 1));
Assert.Equal((byte)1, getMostCommonValue(1, 2, 1));
Assert.Equal((byte)2, getMostCommonValue(2, 2, 1));
static byte? getMostCommonValue(params byte?[] values)
{
var builder = new MostCommonNullableValueBuilder();
foreach (var value in values)
{
builder.AddValue(value);
}
return builder.MostCommonValue;
}
}
[Fact]
public void GetCommonNullableValue()
{
Assert.Null(getCommonValue());
Assert.Equal((byte)0, getCommonValue(0));
Assert.Equal((byte)1, getCommonValue(1));
Assert.Equal((byte)2, getCommonValue(2));
Assert.Equal((byte)3, getCommonValue(3));
Assert.Equal((byte)0, getCommonValue(0, 0));
Assert.Null(getCommonValue(0, 1));
Assert.Null(getCommonValue(1, 0));
Assert.Equal((byte)1, getCommonValue(1, 1));
Assert.Null(getCommonValue(1, 2));
Assert.Equal((byte)2, getCommonValue(2, 2));
Assert.Null(getCommonValue(0, 1, 0));
Assert.Null(getCommonValue(1, 0, 1));
Assert.Null(getCommonValue(2, 2, 1));
Assert.Equal((byte)3, getCommonValue(3, 3, 3));
static byte? getCommonValue(params byte[] values)
{
var builder = ArrayBuilder<byte>.GetInstance();
builder.AddRange(values);
var result = MostCommonNullableValueBuilder.GetCommonValue(builder);
builder.Free();
return result;
}
}
private void AssertNullableAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected));
}
private static void AssertNullableAttributes(ModuleSymbol module, string expected)
{
var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
}
}
| 39.745407 | 183 | 0.638579 | [
"MIT"
] | nikitaodnorob/pl-roslyn | src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_NullableContext.cs | 15,145 | C# |
namespace WeiboSharp.Classes
{
public enum InstaLoginResult
{
Success,
BadPassword,
InvalidUser,
TwoFactorRequired,
Exception,
ChallengeRequired,
LimitError,
InactiveUser,
CheckpointLoggedOut
}
} | 18.666667 | 32 | 0.589286 | [
"MIT"
] | TimothyMakkison/WeiboSharp | WeiboSharp/Enums/InstaLoginResult.cs | 282 | C# |
// Copyright (c) 2020 Soichiro Sugimoto
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace LowPassFilter
{
public class ButterwothFilterComponent : LowPassFilterComponent
{
[SerializeField] uint _Order = 2;
[SerializeField] float _CutoffFrequency = 10; // [Hz]
[SerializeField] float _SamplingFrequency = 60; // [Hz]
[SerializeField] uint _VectorSize = 3;
void Awake()
{
Debug.Log("Cutoff frequency: " + _CutoffFrequency + " [Hz]");
Debug.Log("Sampling frequency: " + _SamplingFrequency + " [Hz]");
_LowPassFilter = new ButterworthFilter(_Order, _SamplingFrequency, _CutoffFrequency, _VectorSize);
}
}
}
| 34 | 110 | 0.657289 | [
"MIT"
] | sotanmochi/LowPassFilter-Unity | Assets/LowPassFilter-Unity/Scripts/ButterwothFilterComponent.cs | 784 | C# |
using System.Collections.Generic;
using AutoMapper;
using Nancy;
using todoist.Infraestructure.DTOs;
using todoist.Infraestructure.Entities;
namespace todoist.Infraestructure.Helpers
{
public interface IBaseModuleService
{
Response RespondWithListOfEntitiesDTO<TEntity, TDTO>(INancyModule Module, IEnumerable<TEntity> Entities)
where TEntity : Entity
where TDTO : EntityDTO;
Response RespondWithEntitiyDTO<TEntity, TDTO>(INancyModule Module, TEntity Entity)
where TEntity : Entity
where TDTO : EntityDTO;
IList<TDTO> ConvertToDTOs<TEntity, TDTO>(IEnumerable<TEntity> Entities)
where TEntity : Entity
where TDTO : EntityDTO;
TDTO ConvertToDTO<TEntity, TDTO>(TEntity Entity)
where TEntity : Entity
where TDTO : EntityDTO;
}
public class BaseModuleService : IBaseModuleService
{
private IMapper _mapper;
public BaseModuleService(IMapper mapper)
{
this._mapper = mapper;
}
public Response RespondWithListOfEntitiesDTO<TEntity, TDTO>(INancyModule Module, IEnumerable<TEntity> Entities)
where TEntity : Entity
where TDTO : EntityDTO
{
var entitiesDTO = ConvertToDTOs<TEntity, TDTO>(Entities);
return Module.Response.AsJson<DataDTO<TDTO>>(new DataDTO<TDTO>(entitiesDTO), HttpStatusCode.OK);
}
public Response RespondWithEntitiyDTO<TEntity, TDTO>(INancyModule Module, TEntity Entity)
where TEntity : Entity
where TDTO : EntityDTO
{
var entityDTO = ConvertToDTO<TEntity, TDTO>(Entity);
return Module.Response.AsJson<TDTO>(entityDTO, HttpStatusCode.OK);
}
public TDTO ConvertToDTO<TEntity, TDTO>(TEntity Entity)
where TEntity : Entity
where TDTO : EntityDTO
{
return this._mapper.Map<TEntity, TDTO>(Entity);
}
public IList<TDTO> ConvertToDTOs<TEntity, TDTO>(IEnumerable<TEntity> Entities)
where TDTO : EntityDTO
where TEntity : Entity
{
var entitiesDTO = new List<TDTO>();
foreach (TEntity entity in Entities)
{
if (entity is ISoftDeletable && ((ISoftDeletable) entity).Deleted) continue;
entitiesDTO.Add(this._mapper.Map<TEntity, TDTO>(entity));
}
return entitiesDTO;
}
}
} | 32.693333 | 119 | 0.643556 | [
"MIT"
] | sebalr/core-todoist | Infraestructure/Helpers/BaseModuleService.cs | 2,452 | C# |
using Sdl.Web.Delivery.Service;
using SDL.ECommerce.Api.Model;
using SDL.ECommerce.Api.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SDL.ECommerce.OData
{
/// <summary>
/// E-Commerce Product Query Service
/// </summary>
public class ProductQueryService : IProductQueryService
{
private ODataV4Service service;
/// <summary>
/// Constructor (only available internally)
/// </summary>
/// <param name="service"></param>
internal ProductQueryService(ODataV4Service service)
{
this.service = service;
}
/// <summary>
/// Execute query towards the product catalog.
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public IProductQueryResult Query(Query query)
{
ODataV4ClientFunction func = new ODataV4ClientFunction("ProductQuery");
func.AllowCaching = false;
// Category
//
if ( query.Category != null )
{
func.WithParam("categoryId", query.Category.Id);
}
else if ( query.CategoryId != null )
{
func.WithParam("categoryId", query.CategoryId);
}
// Search phrase
//
if (query.SearchPhrase != null)
{
func.WithParam("searchPhrase", query.SearchPhrase);
}
// Facets
//
if ( query.Facets != null && query.Facets.Count > 0 )
{
var facetsString = new StringBuilder();
for (int i = 0; i < query.Facets.Count; i++)
{
var facet = query.Facets[i];
facetsString.Append(facet.ToUrl());
if (i + 1 < query.Facets.Count )
{
facetsString.Append("&");
}
}
func.WithParam("facets", facetsString.ToString());
}
if (query.StartIndex != null)
{
func.WithParam("startIndex", query.StartIndex);
}
if ( query.ViewSize != null)
{
func.WithParam("viewSize", query.ViewSize);
}
if ( query.ViewType != null )
{
func.WithParam("viewType", query.ViewType.ToString());
}
return Enumerable.FirstOrDefault<ProductQueryResult>(this.service.Execute<ProductQueryResult>(func));
/*
var uriString = string.Format("{0}/{1}", (object)this.service.Service.BaseUri, (object)func);
Uri uri = new Uri(uriString);
return Enumerable.FirstOrDefault<ProductQueryResult>(this.service.Service.Execute<ProductQueryResult>(uri));
*/
}
}
}
| 31.28125 | 120 | 0.509158 | [
"Apache-2.0"
] | erikssonorjan/ecommerce-framework | dxa.net/ecommerce-framework-dotnet/SDL.ECommerce.OData/Service/ProductQueryService.cs | 3,005 | 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("WindowThumbnail")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Neil Chen")]
[assembly: AssemblyProduct("WindowThumbnail")]
[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("862fddbd-93ef-4f91-a6aa-b022086efd4a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.749822 | [
"Apache-2.0"
] | neilchennc/WindowThumbnail | WindowThumbnail/Properties/AssemblyInfo.cs | 1,410 | C# |
using FistVR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Cityrobo
{
public class QBArmorPiece_Backpack : PlayerBackPack
{
[Header("QBArmorPiece_Backpack Config")]
public string layerName = "Default";
public string attachmentLayerName = "Default";
private int attachmentCountOnQBSlotEnter;
#if !(UNITY_EDITOR || UNITY_5)
public override void SetQuickBeltSlot(FVRQuickBeltSlot slot)
{
if (slot != null && !base.IsHeld)
{
if (this.AttachmentsList.Count > 0)
{
for (int i = 0; i < this.AttachmentsList.Count; i++)
{
if (this.AttachmentsList[i] != null)
{
this.AttachmentsList[i].SetAllCollidersToLayer(false, attachmentLayerName);
}
}
attachmentCountOnQBSlotEnter = AttachmentsList.Count;
}
}
else if (this.AttachmentsList.Count > 0)
{
for (int j = 0; j < this.AttachmentsList.Count; j++)
{
if (this.AttachmentsList[j] != null)
{
this.AttachmentsList[j].SetAllCollidersToLayer(false, "Default");
}
}
attachmentCountOnQBSlotEnter = AttachmentsList.Count;
}
if (this.m_quickbeltSlot != null && slot != this.m_quickbeltSlot)
{
this.m_quickbeltSlot.HeldObject = null;
this.m_quickbeltSlot.CurObject = null;
this.m_quickbeltSlot.IsKeepingTrackWithHead = false;
}
if (slot != null && !base.IsHeld)
{
base.SetAllCollidersToLayer(false, layerName);
slot.HeldObject = this;
slot.CurObject = this;
slot.IsKeepingTrackWithHead = this.DoesQuickbeltSlotFollowHead;
}
else
{
base.SetAllCollidersToLayer(false, "Default");
}
this.m_quickbeltSlot = slot;
}
public override void FVRUpdate()
{
base.FVRUpdate();
if (m_quickbeltSlot != null)
{
if (this.AttachmentsList.Count > attachmentCountOnQBSlotEnter)
{
if (this.AttachmentsList[attachmentCountOnQBSlotEnter] != null)
{
this.AttachmentsList[attachmentCountOnQBSlotEnter].SetAllCollidersToLayer(false, attachmentLayerName);
}
attachmentCountOnQBSlotEnter = this.AttachmentsList.Count;
}
}
}
#endif
}
} | 26 | 107 | 0.669683 | [
"MIT"
] | TrueLordChanka/FTWScripts | QBArmorPiece_Backpack.cs | 2,210 | C# |
using System;
using System.Threading;
// Tests that Exchange<object>(object, object) works on variety
// of casted types: It just casts a bunch of different types to
// object, then makes sure Exchange works on those objects.
public class InterlockedExchange7
{
private const int c_NUM_LOOPS = 100;
private const int c_MIN_STRING_LEN = 5;
private const int c_MAX_STRING_LEN = 128;
public static int Main()
{
InterlockedExchange7 test = new InterlockedExchange7();
TestLibrary.TestFramework.BeginTestCase("InterlockedExchange7");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Interlocked.Exchange<object>(object&,object)");
try
{
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte");
retVal = ExchangeObjects(
(object)TestLibrary.Generator.GetByte(-55),
(object)TestLibrary.Generator.GetByte(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte[]");
byte[] bArr1 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)];
byte[] bArr2 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)];
TestLibrary.Generator.GetBytes(-55, bArr1);
TestLibrary.Generator.GetBytes(-55, bArr2);
retVal = ExchangeObjects(
(object)bArr1,
(object)bArr2
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int16");
retVal = ExchangeObjects(
(object)TestLibrary.Generator.GetInt16(-55),
(object)TestLibrary.Generator.GetInt16(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int32");
retVal = ExchangeObjects(
(object)TestLibrary.Generator.GetInt32(-55),
(object)TestLibrary.Generator.GetInt32(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int64");
retVal = ExchangeObjects(
(object)(object)TestLibrary.Generator.GetInt64(-55),
(object)TestLibrary.Generator.GetInt64(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Single");
retVal = ExchangeObjects(
(object)(object)TestLibrary.Generator.GetSingle(-55),
(object)TestLibrary.Generator.GetSingle(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == Double");
retVal = ExchangeObjects(
(object)TestLibrary.Generator.GetDouble(-55),
(object)TestLibrary.Generator.GetDouble(-55)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == string");
retVal = ExchangeObjects(
TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN),
(object)TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN)
) && retVal;
TestLibrary.TestFramework.BeginScenario("PosTest1: object == char");
retVal = ExchangeObjects(
TestLibrary.Generator.GetChar(-55),
TestLibrary.Generator.GetChar(-55)
) && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool ExchangeObjects(object location, object value)
{
bool retVal = true;
object oldLocation;
object prevLocation;
prevLocation = location;
// this is the main change from InterlockedExchange2.cs
// here we use the <T> overload where T=object
oldLocation = Interlocked.Exchange<object>(ref location, value);
if (!location.Equals(value))
{
TestLibrary.TestFramework.LogError("003", "Interlocked.Exchange() did not do the exchange correctly: Expected(" + value + ") Actual(" + location + ")");
retVal = false;
}
if (!oldLocation.Equals(prevLocation))
{
TestLibrary.TestFramework.LogError("004", "Interlocked.Exchange() did not return the expected value: Expected(" + prevLocation + ") Actual(" + oldLocation + ")");
retVal = false;
}
return retVal;
}
}
| 38.231293 | 174 | 0.548221 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/CoreMangLib/cti/system/threading/interlocked/interlockedexchange7.cs | 5,620 | C# |
using Android.App;
using Android.Widget;
using Android.OS;
using Android;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Content.PM;
using System;
using System.Collections.Generic;
using System.Linq;
using NmeaParser.Messages;
namespace SampleApp.Droid
{
[Activity(Label = "NMEA Parser SampleApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private Button startButton;
private Button stopButton;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
startButton = FindViewById<Button>(Resource.Id.startButton);
startButton.Click += StartButton_Click;
stopButton = FindViewById<Button>(Resource.Id.stopButton);
stopButton.Click += StopButton_Click;
stopButton.Enabled = false;
devices.Add("System GPS", null);
var devicePicker = FindViewById<Spinner>(Resource.Id.device_picker);
foreach(var d in NmeaParser.BluetoothDevice.GetBluetoothSerialDevices())
{
devices[d.Name + " " + d.Address] = d.Address;
}
devicePicker.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, devices.Keys.ToArray());
devicePicker.SetSelection(0);
}
private Dictionary<string, string> devices = new Dictionary<string, string>();
private void StopButton_Click(object sender, EventArgs e)
{
if (listener?.IsOpen == true)
{
Stop();
}
}
private void Stop()
{
listener.MessageReceived -= Listener_MessageReceived;
monitor.LocationChanged -= Monitor_LocationChanged;
socket?.Close();
socket?.Dispose();
socket = null;
_ = listener.CloseAsync();
listener = null;
startButton.Enabled = !(stopButton.Enabled = false);
}
private void StartButton_Click(object sender, EventArgs e)
{
if (listener?.IsOpen != true)
{
Start();
}
}
private NmeaParser.NmeaDevice listener;
private NmeaParser.Gnss.GnssMonitor monitor;
private TextView status;
private bool launched;
private Android.Bluetooth.BluetoothSocket socket;
private async void Start()
{
startButton.Enabled = false;
status = FindViewById<TextView>(Resource.Id.output);
var devicePicker = FindViewById<Spinner>(Resource.Id.device_picker);
var id = devicePicker.SelectedItem.ToString();
var btAddress = devices[id];
if (btAddress == null)
{
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.AccessFineLocation }, 1000);
return;
}
if (launched)
return;
launched = true;
listener = new NmeaParser.SystemNmeaDevice(ApplicationContext);
}
else //Bluetooth
{
try
{
status.Text = "Opening bluetooth...";
var adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
var bt = Android.Bluetooth.BluetoothAdapter.DefaultAdapter.GetRemoteDevice(btAddress);
Java.Util.UUID SERIAL_UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for Serial Device Service
socket = bt.CreateRfcommSocketToServiceRecord(SERIAL_UUID);
try
{
await socket.ConnectAsync();
}
catch(Java.IO.IOException)
{
// This sometimes fails. Use fallback approach to open socket
// Based on https://stackoverflow.com/a/41627149
socket.Dispose();
var m = bt.Class.GetMethod("createRfcommSocket", new Java.Lang.Class[] { Java.Lang.Integer.Type });
socket = m.Invoke(bt, new Java.Lang.Object[] { 1 }) as Android.Bluetooth.BluetoothSocket;
socket.Connect();
}
listener = new NmeaParser.StreamDevice(socket.InputStream);
}
catch(System.Exception ex)
{
socket?.Dispose();
socket = null;
status.Text += "\nError opening Bluetooth device:\n" + ex.Message;
}
}
if (listener != null)
{
listener.MessageReceived += Listener_MessageReceived;
status.Text += "\nOpening device...";
await listener.OpenAsync();
status.Text += "\nConnected!";
startButton.Enabled = !(stopButton.Enabled = true);
monitor = new NmeaParser.Gnss.GnssMonitor(listener);
monitor.LocationChanged += Monitor_LocationChanged;
}
else
{
startButton.Enabled = !(stopButton.Enabled = false);
}
}
protected override void OnDestroy()
{
Stop();
base.OnDestroy();
}
protected override void OnResume()
{
base.OnResume();
// if it was resumed by the GPS permissions dialog
//Start();
}
Queue<NmeaParser.Messages.NmeaMessage> messages = new Queue<NmeaParser.Messages.NmeaMessage>(100);
private void Listener_MessageReceived(object sender, NmeaParser.NmeaMessageReceivedEventArgs e)
{
var message = e.Message;
RunOnUiThread(() =>
{
if (messages.Count == 100) messages.Dequeue();
messages.Enqueue(message);
status.Text = string.Join("\n", messages.Reverse().Select(n=>n.ToString()));
});
}
private void Monitor_LocationChanged(object sender, EventArgs e)
{
FindViewById<TextView>(Resource.Id.latitude).Text = "Latitude = " + monitor.Latitude.ToString("0.0000000");
FindViewById<TextView>(Resource.Id.longitude).Text = "Longitude = " + monitor.Longitude.ToString("0.0000000");
FindViewById<TextView>(Resource.Id.altitude).Text = "Altitude = " + monitor.Altitude.ToString();
}
}
}
| 39.296703 | 149 | 0.540688 | [
"Apache-2.0"
] | Haavard94/NmeaParser | src/SampleApp.Droid/MainActivity.cs | 7,154 | 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("Dan.IdentityNPocoStores")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dan.IdentityNPocoStores")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("e89dde13-966d-400c-b4f0-7588c5891220")]
| 42.833333 | 85 | 0.762646 | [
"Apache-2.0"
] | danclarke/AspNetIdentity3NPOCODataStores | src/Dan.IdentityNPocoStores/Properties/AssemblyInfo.cs | 1,031 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using P3Net.Kraken.Data;
using P3Net.Kraken.Data.Common;
namespace DataAccessDemo.Code
{
public static class Database
{
public static IEnumerable<Role> GetRoles ( this ConnectionManager source )
{
var cmd = new AdhocQuery("SELECT Id, Name FROM Roles");
return source.ExecuteQueryWithResults(cmd, r =>
new Role(r.GetInt32OrDefault("Id")) { Name = r.GetStringOrDefault("Name") }
);
}
public static Role GetRole ( this ConnectionManager source, int id )
{
var cmd = new AdhocQuery("SELECT Id, Name FROM Roles where Id = @id").WithParameters(
InputParameter.Named("id").WithValue(id)
);
return source.ExecuteQueryWithResult(cmd,
r => new Role(r.GetInt32OrDefault("Id")) { Name = r.GetStringOrDefault("Name") });
}
public static IEnumerable<User> GetUsers ( this ConnectionManager source )
{
var users = new List<User>();
var cmd = new AdhocQuery("SELECT Id, Name FROM Users");
var ds = new DataSet();
source.FillDataSet(cmd, ds);
if (ds.TableCount() > 0)
{
foreach (var row in ds.Tables[0].AsEnumerable())
{
users.Add(new User(row.GetInt32ValueOrDefault("Id")) { Name = row.GetStringValueOrDefault("Name") });
};
};
return users;
}
public static User GetUser (this ConnectionManager source, int id)
{
var cmd = new AdhocQuery("SELECT Id, Name FROM Users where Id = @id").WithParameters(
InputParameter.Named("id").WithValue(id)
);
return source.ExecuteQueryWithResult(cmd,
r => new User(r.GetInt32OrDefault("Id")) { Name = r.GetStringOrDefault("Name") });
}
}
} | 35.375 | 149 | 0.52606 | [
"MIT"
] | CoolDadTx/p3net-misc | DataAccessDemo/DataAccessDemo/Code/Database.cs | 2,266 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Disqord;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace MudaeFarm
{
public interface IMudaeRoller : IHostedService { }
public class MudaeRoller : BackgroundService, IMudaeRoller
{
readonly IDiscordClientService _discord;
readonly IOptionsMonitor<RollingOptions> _options;
readonly IOptionsMonitor<BotChannelList> _channelList;
readonly IMudaeCommandHandler _commandHandler;
readonly IMudaeOutputParser _outputParser;
readonly ILogger<MudaeRoller> _logger;
public MudaeRoller(IDiscordClientService discord, IOptionsMonitor<RollingOptions> options, IOptionsMonitor<BotChannelList> channelList, IMudaeCommandHandler commandHandler, IMudaeOutputParser outputParser, ILogger<MudaeRoller> logger)
{
_discord = discord;
_options = options;
_channelList = channelList;
_commandHandler = commandHandler;
_outputParser = outputParser;
_logger = logger;
}
sealed class Roller
{
public readonly CancellationTokenSource Cancellation;
public readonly BotChannelList.Item CurrentItem;
public Roller(BotChannelList.Item item, CancellationToken cancellationToken)
{
Cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
CurrentItem = item;
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var client = await _discord.GetClientAsync();
var rollers = new Dictionary<ulong, Roller>();
void handleChange(BotChannelList o)
{
var items = o.Items.GroupBy(x => x.Id).ToDictionary(x => x.Key, x => x.First());
lock (rollers)
{
foreach (var (id, item) in items)
{
if (!rollers.TryGetValue(id, out var roller) || !roller.CurrentItem.Equals(item))
{
roller?.Cancellation.Cancel();
roller?.Cancellation.Dispose();
var newRoller = new Roller(item, stoppingToken);
var cancellationToken = newRoller.Cancellation.Token;
rollers[id] = newRoller;
Task.Run(async () =>
{
try
{
await RunAsync(client, item, cancellationToken);
}
catch (OperationCanceledException) { }
}, cancellationToken);
}
}
foreach (var id in rollers.Keys.ToArray())
{
if (!items.ContainsKey(id) && rollers.Remove(id, out var roller))
{
roller.Cancellation.Cancel();
roller.Cancellation.Dispose();
}
}
}
}
var monitor = _channelList.OnChange(handleChange);
try
{
handleChange(_channelList.CurrentValue);
await Task.Delay(-1, stoppingToken);
}
finally
{
monitor.Dispose();
lock (rollers)
{
foreach (var roller in rollers.Values)
roller.Cancellation.Dispose();
rollers.Clear();
}
}
}
async Task RunAsync(DiscordClient client, BotChannelList.Item channelItem, CancellationToken cancellationToken = default)
{
if (!(client.GetChannel(channelItem.Id) is IMessageChannel channel))
{
_logger.LogWarning($"Could not find channel {channelItem.Id} to roll in.");
return;
}
await Task.WhenAll(RunRollAsync(client, channel, cancellationToken), RunDailyKakeraAsync(channel, cancellationToken));
}
async Task RunRollAsync(DiscordClient client, IMessageChannel channel, CancellationToken cancellationToken = default)
{
var logPlace = $"channel '{channel.Name}' ({channel.Id})";
var batches = 0;
var rolls = 0;
while (!cancellationToken.IsCancellationRequested)
{
var options = _options.CurrentValue;
if (!options.Enabled)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
continue;
}
IUserMessage response;
try
{
using (channel.Typing())
{
await Task.Delay(TimeSpan.FromSeconds(options.TypingDelaySeconds), cancellationToken);
response = await _commandHandler.SendAsync(channel, options.Command, cancellationToken);
}
}
catch (Exception e)
{
_logger.LogWarning(e, $"Could not roll '{options.Command}' in {logPlace}.");
await Task.Delay(TimeSpan.FromMinutes(30), cancellationToken);
continue;
}
++rolls;
if (response.Embeds.Count != 0)
{
_logger.LogInformation($"Sent roll {rolls} of batch {batches} in {logPlace}.");
await Task.Delay(TimeSpan.FromSeconds(options.IntervalSeconds), cancellationToken);
continue;
}
if (response.Content.StartsWith($"**{client.CurrentUser.Name}**", StringComparison.OrdinalIgnoreCase))
{
if (_outputParser.TryParseRollRemaining(response.Content, out var remaining))
{
_logger.LogInformation($"Sent roll {rolls} of batch {batches} in {logPlace}. {remaining} rolls are remaining.");
await Task.Delay(TimeSpan.FromSeconds(options.IntervalSeconds), cancellationToken);
continue;
}
if (_outputParser.TryParseRollLimited(response.Content, out var resetTime))
{
resetTime += TimeSpan.FromMinutes(1);
_logger.LogInformation($"Finished roll {rolls} of batch {batches} in {logPlace}. Next batch in {resetTime}.");
rolls = 0;
++batches;
await Task.Delay(resetTime, cancellationToken);
continue;
}
}
_logger.LogWarning($"Could not handle Mudae response for command '{options.Command}'. Assuming a sane default of 5 rolls per hour ({rolls} right now). Response: {response.Content}");
if (rolls >= 5)
{
_logger.LogInformation($"Preemptively finished roll {rolls} of batch {batches} in {logPlace}. Next batch in an hour.");
rolls = 0;
++batches;
await Task.Delay(TimeSpan.FromHours(1), cancellationToken);
continue;
}
}
}
async Task RunDailyKakeraAsync(IMessageChannel channel, CancellationToken cancellationToken = default)
{
var logPlace = $"channel '{channel.Name}' ({channel.Id})";
while (!cancellationToken.IsCancellationRequested)
{
var options = _options.CurrentValue;
if (!options.DailyKakeraEnabled)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
continue;
}
IUserMessage response;
try
{
using (channel.Typing())
{
await Task.Delay(TimeSpan.FromSeconds(options.TypingDelaySeconds), cancellationToken);
response = await _commandHandler.SendAsync(channel, options.DailyKakeraCommand, cancellationToken);
}
}
catch (Exception e)
{
_logger.LogWarning(e, $"Could not roll daily kakera in {logPlace}.");
await Task.Delay(TimeSpan.FromMinutes(30), cancellationToken);
continue;
}
if (_outputParser.TryParseTime(response.Content, out var resetTime))
{
_logger.LogInformation($"Could not claim daily kakera in {logPlace}. Next reset in {resetTime}.");
await Task.Delay(resetTime, cancellationToken);
continue;
}
// dk output doesn't really matter, because we'll have to wait a day anyway
_logger.LogInformation($"Claimed daily kakera in {logPlace}.");
await Task.Delay(TimeSpan.FromDays(1), cancellationToken);
}
}
}
} | 37.941176 | 242 | 0.515659 | [
"MIT"
] | Dogeek/MudaeFarm | MudaeFarm/MudaeRoller.cs | 9,675 | C# |
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using SteamKit2;
using System.Net;
using Newtonsoft.Json;
using SteamAPI.TradeOffers.Enums;
using SteamAPI.TradeOffers.Objects;
namespace SteamAPI.TradeOffers
{
public class TradeOffers
{
public List<ulong> OurPendingTradeOffers;
private readonly object _ourPendingTradeOffersLock;
private readonly SteamID _botId;
private readonly SteamWeb _steamWeb;
private readonly List<ulong> _handledTradeOffers;
private readonly List<ulong> _awaitingConfirmationTradeOffers;
private readonly List<ulong> _inEscrowTradeOffers;
private readonly string _accountApiKey;
private bool _shouldCheckPendingTradeOffers;
private readonly int _tradeOfferRefreshRate;
public TradeOffers(SteamID botId, SteamWeb steamWeb, string accountApiKey, int tradeOfferRefreshRate, List<ulong> pendingTradeOffers = null)
{
_botId = botId;
_steamWeb = steamWeb;
_accountApiKey = accountApiKey;
_shouldCheckPendingTradeOffers = true;
_tradeOfferRefreshRate = tradeOfferRefreshRate;
OurPendingTradeOffers = pendingTradeOffers ?? new List<ulong>();
_ourPendingTradeOffersLock = new object();
_handledTradeOffers = new List<ulong>();
_awaitingConfirmationTradeOffers = new List<ulong>();
_inEscrowTradeOffers = new List<ulong>();
new Thread(CheckPendingTradeOffers).Start();
}
/// <summary>
/// Create a new trade offer session.
/// </summary>
/// <param name="partnerId">The SteamID of the user you want to send a trade offer to.</param>
/// <returns>A 'Trade' object in which you can apply further actions</returns>
public Trade CreateTrade(SteamID partnerId)
{
return new Trade(this, partnerId, _steamWeb);
}
/// <summary>
/// Accepts a pending trade offer.
/// </summary>
/// <param name="tradeOfferId">The ID of the trade offer</param>
/// <param name="tradeId">The trade ID of the completed trade</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool AcceptTrade(ulong tradeOfferId, out ulong tradeId)
{
tradeId = 0;
var tradeOfferResponse = GetTradeOffer(tradeOfferId);
return tradeOfferResponse.Offer != null && AcceptTrade(tradeOfferResponse.Offer, out tradeId);
}
/// <summary>
/// Accepts a pending trade offer
/// </summary>
/// <param name="tradeOffer">The trade offer object</param>
/// <param name="tradeId">The trade ID of the completed trade</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool AcceptTrade(TradeOffer tradeOffer, out ulong tradeId)
{
tradeId = 0;
var tradeOfferId = tradeOffer.Id;
var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/accept";
var referer = "http://steamcommunity.com/tradeoffer/" + tradeOfferId + "/";
var data = new NameValueCollection
{
{"sessionid", _steamWeb.SessionId},
{"serverid", "1"},
{"tradeofferid", tradeOfferId.ToString()},
{"partner", tradeOffer.OtherSteamId.ToString()}
};
try
{
var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer);
if (string.IsNullOrEmpty(response)) return false;
dynamic json = JsonConvert.DeserializeObject(response);
if (json.strError != null) throw new TradeOfferSteamException(Convert.ToString(json.strError));
if (json.needs_mobile_confirmation != null && Convert.ToBoolean(json.needs_mobile_confirmation)) return true;
if (json.needs_email_confirmation != null && Convert.ToBoolean(json.needs_email_confirmation)) return true;
if (json.tradeid == null) return false;
tradeId = Convert.ToUInt64(json.tradeid);
return true;
}
catch (JsonReaderException)
{
return false;
}
}
/// <summary>
/// Declines a pending trade offer
/// </summary>
/// <param name="tradeOffer">The trade offer object</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool DeclineTrade(TradeOffer tradeOffer)
{
return DeclineTrade(tradeOffer.Id);
}
/// <summary>
/// Declines a pending trade offer
/// </summary>
/// <param name="tradeOfferId">The trade offer ID</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool DeclineTrade(ulong tradeOfferId)
{
var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/decline";
const string referer = "http://steamcommunity.com/";
var data = new NameValueCollection {{"sessionid", _steamWeb.SessionId}, {"serverid", "1"}};
try
{
var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer);
dynamic json = JsonConvert.DeserializeObject(response);
if (json.strError != null) throw new TradeOfferSteamException(Convert.ToString(json.strError));
return json.tradeofferid != null;
}
catch (JsonReaderException)
{
return false;
}
}
/// <summary>
/// Cancels a pending sent trade offer
/// </summary>
/// <param name="tradeOffer">The trade offer object</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool CancelTrade(TradeOffer tradeOffer)
{
return CancelTrade(tradeOffer.Id);
}
/// <summary>
/// Cancels a pending sent trade offer
/// </summary>
/// <param name="tradeOfferId">The trade offer ID</param>
/// <exception cref="TradeOfferSteamException">Thrown if and only if Steam returns a response with an error message and error code.</exception>
/// <returns>True if successful, false if not</returns>
public bool CancelTrade(ulong tradeOfferId)
{
var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/cancel";
const string referer = "http://steamcommunity.com/";
var data = new NameValueCollection {{"sessionid", _steamWeb.SessionId}};
var response = RetryWebRequest(_steamWeb, url, "POST", data, true, referer);
dynamic json = JsonConvert.DeserializeObject(response);
if (json.strError != null) throw new TradeOfferSteamException(Convert.ToString(json.strError));
return json.tradeofferid != null;
}
/// <summary>
/// Get a list of incoming trade offers.
/// </summary>
/// <returns>An 'int' list of trade offer IDs</returns>
public List<ulong> GetIncomingTradeOffers()
{
var incomingTradeOffers = new List<ulong>();
var url = "http://steamcommunity.com/profiles/" + _botId.ConvertToUInt64() + "/tradeoffers/";
var html = RetryWebRequest(_steamWeb, url, "GET", null);
var reg = new Regex("ShowTradeOffer\\((.*?)\\);");
var matches = reg.Matches(html);
foreach (Match match in matches)
{
if (match.Success)
{
var tradeId = Convert.ToUInt64(match.Groups[1].Value.Replace("'", ""));
if (!incomingTradeOffers.Contains(tradeId))
incomingTradeOffers.Add(tradeId);
}
}
return incomingTradeOffers;
}
public GetTradeOffer.GetTradeOfferResponse GetTradeOffer(ulong tradeOfferId)
{
var url = string.Format("https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key={0}&tradeofferid={1}&language={2}", _accountApiKey, tradeOfferId, "en_us");
var response = RetryWebRequest(_steamWeb, url, "GET", null, false, "http://steamcommunity.com");
try
{
var result = JsonConvert.DeserializeObject<GetTradeOffer>(response);
if (result.Response != null)
{
return result.Response;
}
}
catch (JsonReaderException)
{
}
return null;
}
/// <summary>
/// Get list of trade offers from API
/// </summary>
/// <param name="getActive">Set this to true to get active-only trade offers</param>
/// <returns>list of trade offers</returns>
public List<TradeOffer> GetTradeOffers(bool getActive = false)
{
var temp = new List<TradeOffer>();
var url = "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=" + _accountApiKey + "&get_sent_offers=1&get_received_offers=1";
if (getActive)
{
url += "&active_only=1&time_historical_cutoff=" + (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
else
{
url += "&active_only=0";
}
var response = RetryWebRequest(_steamWeb, url, "GET", null, false, "http://steamcommunity.com");
try
{
var json = JsonConvert.DeserializeObject<dynamic>(response);
var sentTradeOffers = json.response.trade_offers_sent;
if (sentTradeOffers != null)
{
foreach (var tradeOffer in sentTradeOffers)
{
TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer));
temp.Add(tempTrade);
}
}
var receivedTradeOffers = json.response.trade_offers_received;
if (receivedTradeOffers != null)
{
foreach (var tradeOffer in receivedTradeOffers)
{
TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer));
temp.Add(tempTrade);
}
}
}
catch (JsonReaderException)
{
}
return temp;
}
/// <summary>
/// Manually validate if a trade offer went through by checking /inventoryhistory/
/// You shouldn't use this since it may be exploitable. I'm keeping it here in case I want to rework this in the future.
/// </summary>
/// <param name="tradeOffer">A 'TradeOffer' object</param>
/// <returns>True if the trade offer was successfully accepted, false if otherwise</returns>
public bool ValidateTradeAccept(TradeOffer tradeOffer)
{
try
{
var history = GetTradeHistory();
foreach (var completedTrade in history)
{
if (tradeOffer.ItemsToGive.Length == completedTrade.GivenItems.Count && tradeOffer.ItemsToReceive.Length == completedTrade.ReceivedItems.Count)
{
var numFoundGivenItems = 0;
var numFoundReceivedItems = 0;
var foundItemIds = new List<ulong>();
foreach (var historyItem in completedTrade.GivenItems)
{
foreach (var tradeOfferItem in tradeOffer.ItemsToGive)
{
if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
{
if (!foundItemIds.Contains(tradeOfferItem.AssetId))
{
foundItemIds.Add(tradeOfferItem.AssetId);
numFoundGivenItems++;
}
}
}
}
foreach (var historyItem in completedTrade.ReceivedItems)
{
foreach (var tradeOfferItem in tradeOffer.ItemsToReceive)
{
if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
{
if (!foundItemIds.Contains(tradeOfferItem.AssetId))
{
foundItemIds.Add(tradeOfferItem.AssetId);
numFoundReceivedItems++;
}
}
}
}
if (numFoundGivenItems == tradeOffer.ItemsToGive.Length && numFoundReceivedItems == tradeOffer.ItemsToReceive.Length)
{
return true;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error validating trade:");
Console.WriteLine(ex);
}
return false;
}
/// <summary>
/// Retrieves completed trades from /inventoryhistory/
/// </summary>
/// <param name="limit">Max number of trades to retrieve</param>
/// <param name="numPages">How many pages to retrieve</param>
/// <returns>A List of 'TradeHistory' objects</returns>
public List<TradeHistory> GetTradeHistory(int limit = 0, int numPages = 1)
{
var tradeHistoryPages = new Dictionary<int, TradeHistory[]>();
for (var i = 0; i < numPages; i++)
{
var tradeHistoryPageList = new TradeHistory[30];
try
{
var url = "http://steamcommunity.com/profiles/" + _botId.ConvertToUInt64() + "/inventoryhistory/?p=" + i;
var html = RetryWebRequest(_steamWeb, url, "GET", null);
// TODO: handle rgHistoryCurrency as well
var reg = new Regex("rgHistoryInventory = (.*?)};");
var m = reg.Match(html);
if (m.Success)
{
var json = m.Groups[1].Value + "}";
var schemaResult = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<ulong, Dictionary<ulong, TradeHistory.HistoryItem>>>>(json);
var trades = new Regex("HistoryPageCreateItemHover\\((.*?)\\);");
var tradeMatches = trades.Matches(html);
foreach (Match match in tradeMatches)
{
if (!match.Success) continue;
var historyString = match.Groups[1].Value.Replace("'", "").Replace(" ", "");
var split = historyString.Split(',');
var tradeString = split[0];
var tradeStringSplit = tradeString.Split('_');
var tradeNum = Convert.ToInt32(tradeStringSplit[0].Replace("trade", ""));
if (limit > 0 && tradeNum >= limit) break;
if (tradeHistoryPageList[tradeNum] == null)
{
tradeHistoryPageList[tradeNum] = new TradeHistory();
}
var tradeHistoryItem = tradeHistoryPageList[tradeNum];
var appId = Convert.ToInt32(split[1]);
var contextId = Convert.ToUInt64(split[2]);
var itemId = Convert.ToUInt64(split[3]);
var amount = Convert.ToInt32(split[4]);
var historyItem = schemaResult[appId][contextId][itemId];
if (historyItem.OwnerId == 0)
tradeHistoryItem.ReceivedItems.Add(historyItem);
else
tradeHistoryItem.GivenItems.Add(historyItem);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error retrieving trade history:");
Console.WriteLine(ex);
}
tradeHistoryPages.Add(i, tradeHistoryPageList);
}
return tradeHistoryPages.Values.SelectMany(tradeHistoryPage => tradeHistoryPage).ToList();
}
public void AddPendingTradeOfferToList(ulong tradeOfferId)
{
lock (_ourPendingTradeOffersLock)
{
if (!OurPendingTradeOffers.Contains(tradeOfferId)) OurPendingTradeOffers.Add(tradeOfferId);
}
}
private void RemovePendingTradeOfferFromList(ulong tradeOfferId)
{
lock (_ourPendingTradeOffersLock)
{
OurPendingTradeOffers.Remove(tradeOfferId);
}
}
public void StopCheckingPendingTradeOffers()
{
_shouldCheckPendingTradeOffers = false;
}
private void CheckPendingTradeOffers()
{
new Thread(() =>
{
while (_shouldCheckPendingTradeOffers)
{
var tradeOffers = GetTradeOffers(true);
foreach (var tradeOffer in tradeOffers)
{
if (tradeOffer.IsOurOffer)
{
lock (_ourPendingTradeOffersLock)
{
if (OurPendingTradeOffers.Contains(tradeOffer.Id)) continue;
}
AddPendingTradeOfferToList(tradeOffer.Id);
}
else
{
var args = new TradeOfferEventArgs(tradeOffer);
if (tradeOffer.State == TradeOfferState.Active)
{
if (tradeOffer.ConfirmationMethod != TradeOfferConfirmationMethod.Invalid)
{
OnTradeOfferNeedsConfirmation(args);
}
else
{
OnTradeOfferReceived(args);
}
}
}
}
Thread.Sleep(_tradeOfferRefreshRate);
}
}).Start();
while (_shouldCheckPendingTradeOffers)
{
var checkingThreads = new List<Thread>();
List<ulong> ourPendingTradeOffers;
lock (_ourPendingTradeOffersLock)
{
ourPendingTradeOffers = OurPendingTradeOffers.ToList();
}
foreach (var thread in ourPendingTradeOffers.Select(tradeOfferId => new Thread(() =>
{
var pendingTradeOffer = GetTradeOffer(tradeOfferId);
if (pendingTradeOffer.Offer == null)
{
// Steam's GetTradeOffer/v1 API only gives data for the last 1000 received and 500 sent trade offers, so sometimes this happens
pendingTradeOffer.Offer = new TradeOffer { Id = tradeOfferId };
OnTradeOfferNoData(new TradeOfferEventArgs(pendingTradeOffer.Offer));
}
else
{
var args = new TradeOfferEventArgs(pendingTradeOffer.Offer);
if (pendingTradeOffer.Offer.State == TradeOfferState.Active)
{
// fire this so that trade can be cancelled in UserHandler if the bot owner wishes (e.g. if pending too long)
OnTradeOfferChecked(args);
}
else
{
// check if trade offer has been accepted/declined, or items unavailable (manually validate)
if (pendingTradeOffer.Offer.State == TradeOfferState.Accepted)
{
// fire event
OnTradeOfferAccepted(args);
// remove from list
RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id);
}
else
{
if (pendingTradeOffer.Offer.State == TradeOfferState.NeedsConfirmation)
{
// fire event
OnTradeOfferNeedsConfirmation(args);
}
else if (pendingTradeOffer.Offer.State == TradeOfferState.Invalid || pendingTradeOffer.Offer.State == TradeOfferState.InvalidItems)
{
OnTradeOfferInvalid(args);
RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id);
}
else if (pendingTradeOffer.Offer.State == TradeOfferState.InEscrow)
{
OnTradeOfferInEscrow(args);
}
else
{
if (pendingTradeOffer.Offer.State == TradeOfferState.Canceled)
{
OnTradeOfferCanceled(args);
}
else
{
OnTradeOfferDeclined(args);
}
RemovePendingTradeOfferFromList(pendingTradeOffer.Offer.Id);
}
}
}
}
})))
{
checkingThreads.Add(thread);
thread.Start();
}
foreach (var thread in checkingThreads)
{
thread.Join();
}
Thread.Sleep(_tradeOfferRefreshRate);
}
}
protected virtual void OnTradeOfferChecked(TradeOfferEventArgs e)
{
var handler = TradeOfferChecked;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnTradeOfferReceived(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferReceived;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferAccepted(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferAccepted;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferDeclined(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferDeclined;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferCanceled(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferCanceled;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferInvalid(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferInvalid;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferNeedsConfirmation(TradeOfferEventArgs e)
{
if (!_awaitingConfirmationTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferNeedsConfirmation;
if (handler != null)
{
handler(this, e);
}
_awaitingConfirmationTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferInEscrow(TradeOfferEventArgs e)
{
if (!_inEscrowTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferInEscrow;
if (handler != null)
{
handler(this, e);
}
_inEscrowTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferNoData(TradeOfferEventArgs e)
{
if (!_handledTradeOffers.Contains(e.TradeOffer.Id))
{
var handler = TradeOfferNoData;
if (handler != null)
{
handler(this, e);
}
_handledTradeOffers.Add(e.TradeOffer.Id);
}
}
public event TradeOfferStatusEventHandler TradeOfferChecked;
public event TradeOfferStatusEventHandler TradeOfferReceived;
public event TradeOfferStatusEventHandler TradeOfferAccepted;
public event TradeOfferStatusEventHandler TradeOfferDeclined;
public event TradeOfferStatusEventHandler TradeOfferCanceled;
public event TradeOfferStatusEventHandler TradeOfferInvalid;
public event TradeOfferStatusEventHandler TradeOfferNeedsConfirmation;
public event TradeOfferStatusEventHandler TradeOfferInEscrow;
public event TradeOfferStatusEventHandler TradeOfferNoData;
public class TradeOfferEventArgs : EventArgs
{
public TradeOffer TradeOffer { get; private set; }
public TradeOfferEventArgs(TradeOffer tradeOffer)
{
TradeOffer = tradeOffer;
}
}
public delegate void TradeOfferStatusEventHandler(Object sender, TradeOfferEventArgs e);
public static string RetryWebRequest(SteamWeb steamWeb, string url, string method, NameValueCollection data, bool ajax = false, string referer = "")
{
for (var i = 0; i < 10; i++)
{
try
{
var response = steamWeb.Request(url, method, data, ajax, referer);
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null) continue;
using (var reader = new System.IO.StreamReader(responseStream))
{
var result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
{
Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode);
Thread.Sleep(1000);
}
else
{
return result;
}
}
}
}
catch (WebException ex)
{
try
{
using (var responseStream = ex.Response.GetResponseStream())
{
if (responseStream == null) continue;
using (var reader = new System.IO.StreamReader(responseStream))
{
var result = reader.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
return result;
}
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code: {0}, {1} for {2}", (int)((HttpWebResponse)ex.Response).StatusCode, ((HttpWebResponse)ex.Response).StatusDescription, url);
}
}
}
}
catch
{
// ignored
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
return "";
}
}
} | 45.134094 | 190 | 0.494042 | [
"MIT"
] | MariusJusc/csgo_cf | SteamAPI/TradeOffers/TradeOffers.cs | 31,639 | C# |
using System;
using System.Reflection;
namespace MyWebAppForDeployment.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 22.166667 | 64 | 0.759398 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | heartysoft/quicksilver | MyWebAppForDeployment/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 266 | 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.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query
{
/// <inheritdoc />
public class SqlExpressionFactory : ISqlExpressionFactory
{
private readonly IRelationalTypeMappingSource _typeMappingSource;
private readonly RelationalTypeMapping _boolTypeMapping;
/// <summary>
/// Creates a new instance of the <see cref="SqlExpressionFactory" /> class.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this class. </param>
public SqlExpressionFactory([NotNull] SqlExpressionFactoryDependencies dependencies)
{
Check.NotNull(dependencies, nameof(dependencies));
_typeMappingSource = dependencies.TypeMappingSource;
_boolTypeMapping = _typeMappingSource.FindMapping(typeof(bool));
}
/// <inheritdoc />
public virtual SqlExpression ApplyDefaultTypeMapping(SqlExpression sqlExpression)
{
return sqlExpression == null
|| sqlExpression.TypeMapping != null
? sqlExpression
: sqlExpression is SqlUnaryExpression sqlUnaryExpression
&& sqlUnaryExpression.OperatorType == ExpressionType.Convert
&& sqlUnaryExpression.Type == typeof(object)
? sqlUnaryExpression.Operand
: ApplyTypeMapping(sqlExpression, _typeMappingSource.FindMapping(sqlExpression.Type));
}
/// <inheritdoc />
public virtual SqlExpression ApplyTypeMapping(SqlExpression sqlExpression, RelationalTypeMapping typeMapping)
{
#pragma warning disable IDE0046 // Convert to conditional expression
if (sqlExpression == null
#pragma warning restore IDE0046 // Convert to conditional expression
|| sqlExpression.TypeMapping != null)
{
return sqlExpression;
}
return sqlExpression switch
{
CaseExpression e => ApplyTypeMappingOnCase(e, typeMapping),
CollateExpression e => ApplyTypeMappingOnCollate(e, typeMapping),
LikeExpression e => ApplyTypeMappingOnLike(e),
SqlBinaryExpression e => ApplyTypeMappingOnSqlBinary(e, typeMapping),
SqlUnaryExpression e => ApplyTypeMappingOnSqlUnary(e, typeMapping),
SqlConstantExpression e => e.ApplyTypeMapping(typeMapping),
SqlFragmentExpression e => e,
SqlFunctionExpression e => e.ApplyTypeMapping(typeMapping),
SqlParameterExpression e => e.ApplyTypeMapping(typeMapping),
_ => sqlExpression
};
}
private SqlExpression ApplyTypeMappingOnLike(LikeExpression likeExpression)
{
var inferredTypeMapping = (likeExpression.EscapeChar == null
? ExpressionExtensions.InferTypeMapping(
likeExpression.Match, likeExpression.Pattern)
: ExpressionExtensions.InferTypeMapping(
likeExpression.Match, likeExpression.Pattern, likeExpression.EscapeChar))
?? _typeMappingSource.FindMapping(likeExpression.Match.Type);
return new LikeExpression(
ApplyTypeMapping(likeExpression.Match, inferredTypeMapping),
ApplyTypeMapping(likeExpression.Pattern, inferredTypeMapping),
ApplyTypeMapping(likeExpression.EscapeChar, inferredTypeMapping),
_boolTypeMapping);
}
private SqlExpression ApplyTypeMappingOnCase(
CaseExpression caseExpression, RelationalTypeMapping typeMapping)
{
var whenClauses = new List<CaseWhenClause>();
foreach (var caseWhenClause in caseExpression.WhenClauses)
{
whenClauses.Add(
new CaseWhenClause(
caseWhenClause.Test,
ApplyTypeMapping(caseWhenClause.Result, typeMapping)));
}
var elseResult = ApplyTypeMapping(caseExpression.ElseResult, typeMapping);
return caseExpression.Update(caseExpression.Operand, whenClauses, elseResult);
}
private SqlExpression ApplyTypeMappingOnCollate(
CollateExpression collateExpression, RelationalTypeMapping typeMapping)
=> new CollateExpression(
ApplyTypeMapping(collateExpression.Operand, typeMapping),
collateExpression.Collation);
private SqlExpression ApplyTypeMappingOnSqlUnary(
SqlUnaryExpression sqlUnaryExpression, RelationalTypeMapping typeMapping)
{
SqlExpression operand;
Type resultType;
RelationalTypeMapping resultTypeMapping;
switch (sqlUnaryExpression.OperatorType)
{
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Not
when sqlUnaryExpression.IsLogicalNot():
{
resultTypeMapping = _boolTypeMapping;
resultType = typeof(bool);
operand = ApplyDefaultTypeMapping(sqlUnaryExpression.Operand);
break;
}
case ExpressionType.Convert:
resultTypeMapping = typeMapping;
// Since we are applying convert, resultTypeMapping decides the clrType
resultType = resultTypeMapping?.ClrType ?? sqlUnaryExpression.Type;
operand = ApplyDefaultTypeMapping(sqlUnaryExpression.Operand);
break;
case ExpressionType.Not:
case ExpressionType.Negate:
resultTypeMapping = typeMapping;
// While Not is logical, negate is numeric hence we use clrType from TypeMapping
resultType = resultTypeMapping?.ClrType ?? sqlUnaryExpression.Type;
operand = ApplyTypeMapping(sqlUnaryExpression.Operand, typeMapping);
break;
default:
throw new InvalidOperationException(CoreStrings.UnsupportedUnary);
}
return new SqlUnaryExpression(sqlUnaryExpression.OperatorType, operand, resultType, resultTypeMapping);
}
private SqlExpression ApplyTypeMappingOnSqlBinary(
SqlBinaryExpression sqlBinaryExpression, RelationalTypeMapping typeMapping)
{
var left = sqlBinaryExpression.Left;
var right = sqlBinaryExpression.Right;
Type resultType;
RelationalTypeMapping resultTypeMapping;
RelationalTypeMapping inferredTypeMapping;
switch (sqlBinaryExpression.OperatorType)
{
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
{
inferredTypeMapping = ExpressionExtensions.InferTypeMapping(left, right)
// We avoid object here since the result does not get typeMapping from outside.
?? (left.Type != typeof(object)
? _typeMappingSource.FindMapping(left.Type)
: _typeMappingSource.FindMapping(right.Type));
resultType = typeof(bool);
resultTypeMapping = _boolTypeMapping;
break;
}
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
{
inferredTypeMapping = _boolTypeMapping;
resultType = typeof(bool);
resultTypeMapping = _boolTypeMapping;
break;
}
case ExpressionType.Add:
case ExpressionType.Subtract:
case ExpressionType.Multiply:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.Or:
{
inferredTypeMapping = typeMapping ?? ExpressionExtensions.InferTypeMapping(left, right);
resultType = inferredTypeMapping?.ClrType ?? left.Type;
resultTypeMapping = inferredTypeMapping;
break;
}
default:
throw new InvalidOperationException(CoreStrings.IncorrectOperatorType);
}
return new SqlBinaryExpression(
sqlBinaryExpression.OperatorType,
ApplyTypeMapping(left, inferredTypeMapping),
ApplyTypeMapping(right, inferredTypeMapping),
resultType,
resultTypeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression MakeBinary(
ExpressionType operatorType, SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
if (!SqlBinaryExpression.IsValidOperator(operatorType))
{
return null;
}
var returnType = left.Type;
switch (operatorType)
{
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
returnType = typeof(bool);
break;
}
return (SqlBinaryExpression)ApplyTypeMapping(
new SqlBinaryExpression(operatorType, left, right, returnType, null), typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Equal(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Equal, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression NotEqual(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.NotEqual, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression GreaterThan(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.GreaterThan, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression GreaterThanOrEqual(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.GreaterThanOrEqual, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression LessThan(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.LessThan, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression LessThanOrEqual(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.LessThanOrEqual, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression AndAlso(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.AndAlso, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression OrElse(SqlExpression left, SqlExpression right)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.OrElse, left, right, null);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Add(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Add, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Subtract(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Subtract, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Multiply(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Multiply, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Divide(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Divide, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Modulo(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Modulo, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression And(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.And, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlBinaryExpression Or(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
return MakeBinary(ExpressionType.Or, left, right, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression Coalesce(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
var resultType = right.Type;
var inferredTypeMapping = typeMapping
?? ExpressionExtensions.InferTypeMapping(left, right)
?? _typeMappingSource.FindMapping(resultType);
var typeMappedArguments = new List<SqlExpression>()
{
ApplyTypeMapping(left, inferredTypeMapping),
ApplyTypeMapping(right, inferredTypeMapping)
};
return new SqlFunctionExpression(
"COALESCE",
typeMappedArguments,
nullable: true,
// COALESCE is handled separately since it's only nullable if *both* arguments are null
argumentsPropagateNullability: new[] { false, false },
resultType,
inferredTypeMapping);
}
/// <inheritdoc />
public virtual SqlUnaryExpression MakeUnary(
ExpressionType operatorType, SqlExpression operand, Type type, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(operatorType, nameof(operand));
Check.NotNull(operand, nameof(operand));
Check.NotNull(type, nameof(type));
if (!SqlUnaryExpression.IsValidOperator(operatorType))
{
return null;
}
return (SqlUnaryExpression)ApplyTypeMapping(new SqlUnaryExpression(operatorType, operand, type, null), typeMapping);
}
/// <inheritdoc />
public virtual SqlUnaryExpression IsNull(SqlExpression operand)
{
Check.NotNull(operand, nameof(operand));
return MakeUnary(ExpressionType.Equal, operand, typeof(bool));
}
/// <inheritdoc />
public virtual SqlUnaryExpression IsNotNull(SqlExpression operand)
{
Check.NotNull(operand, nameof(operand));
return MakeUnary(ExpressionType.NotEqual, operand, typeof(bool));
}
/// <inheritdoc />
public virtual SqlUnaryExpression Convert(SqlExpression operand, Type type, RelationalTypeMapping typeMapping = null)
{
Check.NotNull(operand, nameof(operand));
Check.NotNull(type, nameof(type));
return MakeUnary(ExpressionType.Convert, operand, type, typeMapping);
}
/// <inheritdoc />
public virtual SqlUnaryExpression Not(SqlExpression operand)
{
Check.NotNull(operand, nameof(operand));
return MakeUnary(ExpressionType.Not, operand, operand.Type, operand.TypeMapping);
}
/// <inheritdoc />
public virtual SqlUnaryExpression Negate(SqlExpression operand)
{
Check.NotNull(operand, nameof(operand));
return MakeUnary(ExpressionType.Negate, operand, operand.Type, operand.TypeMapping);
}
/// <inheritdoc />
public virtual CaseExpression Case(SqlExpression operand, params CaseWhenClause[] whenClauses)
{
Check.NotNull(operand, nameof(operand));
Check.NotNull(whenClauses, nameof(whenClauses));
var operandTypeMapping = operand.TypeMapping
?? whenClauses.Select(wc => wc.Test.TypeMapping).FirstOrDefault(t => t != null)
// Since we never look at type of Operand/Test after this place,
// we need to find actual typeMapping based on non-object type.
?? new[] { operand.Type }.Concat(whenClauses.Select(wc => wc.Test.Type))
.Where(t => t != typeof(object)).Select(t => _typeMappingSource.FindMapping(t)).FirstOrDefault();
var resultTypeMapping = whenClauses.Select(wc => wc.Result.TypeMapping).FirstOrDefault(t => t != null);
operand = ApplyTypeMapping(operand, operandTypeMapping);
var typeMappedWhenClauses = new List<CaseWhenClause>();
foreach (var caseWhenClause in whenClauses)
{
typeMappedWhenClauses.Add(
new CaseWhenClause(
ApplyTypeMapping(caseWhenClause.Test, operandTypeMapping),
ApplyTypeMapping(caseWhenClause.Result, resultTypeMapping)));
}
return new CaseExpression(operand, typeMappedWhenClauses);
}
/// <inheritdoc />
public virtual CaseExpression Case(IReadOnlyList<CaseWhenClause> whenClauses, SqlExpression elseResult)
{
Check.NotNull(whenClauses, nameof(whenClauses));
var resultTypeMapping = elseResult?.TypeMapping
?? whenClauses.Select(wc => wc.Result.TypeMapping).FirstOrDefault(t => t != null);
var typeMappedWhenClauses = new List<CaseWhenClause>();
foreach (var caseWhenClause in whenClauses)
{
typeMappedWhenClauses.Add(
new CaseWhenClause(
ApplyTypeMapping(caseWhenClause.Test, _boolTypeMapping),
ApplyTypeMapping(caseWhenClause.Result, resultTypeMapping)));
}
elseResult = ApplyTypeMapping(elseResult, resultTypeMapping);
return new CaseExpression(typeMappedWhenClauses, elseResult);
}
/// <inheritdoc />
[Obsolete("Use overload that explicitly specifies value for 'argumentsPropagateNullability' argument.")]
public virtual SqlFunctionExpression Function(
string name,
IEnumerable<SqlExpression> arguments,
Type returnType,
RelationalTypeMapping typeMapping = null)
=> Function(name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, typeMapping);
/// <inheritdoc />
[Obsolete("Use overload that explicitly specifies value for 'argumentsPropagateNullability' argument.")]
public virtual SqlFunctionExpression Function(
string schema,
string name,
IEnumerable<SqlExpression> arguments,
Type returnType,
RelationalTypeMapping typeMapping = null)
=> Function(schema, name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, typeMapping);
/// <inheritdoc />
[Obsolete("Use overload that explicitly specifies values for 'instancePropagatesNullability' and 'argumentsPropagateNullability' arguments.")]
public virtual SqlFunctionExpression Function(
SqlExpression instance,
string name,
IEnumerable<SqlExpression> arguments,
Type returnType,
RelationalTypeMapping typeMapping = null)
=> Function(
instance,
name,
arguments,
nullable: true,
instancePropagatesNullability: false,
argumentsPropagateNullability: arguments.Select(a => false),
returnType,
typeMapping);
/// <inheritdoc />
[Obsolete("Use NiladicFunction method.")]
public virtual SqlFunctionExpression Function(string name, Type returnType, RelationalTypeMapping typeMapping = null)
=> NiladicFunction(name, nullable: true, returnType, typeMapping);
/// <inheritdoc />
[Obsolete("Use NiladicFunction method.")]
public virtual SqlFunctionExpression Function(string schema, string name, Type returnType, RelationalTypeMapping typeMapping = null)
=> NiladicFunction(schema, name, nullable: true, returnType, typeMapping);
/// <inheritdoc />
[Obsolete("Use NiladicFunction method.")]
public virtual SqlFunctionExpression Function(SqlExpression instance, string name, Type returnType, RelationalTypeMapping typeMapping = null)
=> NiladicFunction(instance, name, nullable: true, instancePropagatesNullability: false, returnType, typeMapping);
/// <inheritdoc />
public virtual SqlFunctionExpression Function(
string name,
IEnumerable<SqlExpression> arguments,
bool nullable,
IEnumerable<bool> argumentsPropagateNullability,
Type returnType,
RelationalTypeMapping typeMapping = null)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(arguments, nameof(arguments));
Check.NotNull(argumentsPropagateNullability, nameof(argumentsPropagateNullability));
Check.NotNull(returnType, nameof(returnType));
var typeMappedArguments = new List<SqlExpression>();
foreach (var argument in arguments)
{
typeMappedArguments.Add(ApplyDefaultTypeMapping(argument));
}
return new SqlFunctionExpression(name, typeMappedArguments, nullable, argumentsPropagateNullability, returnType, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression Function(
string schema,
string name,
IEnumerable<SqlExpression> arguments,
bool nullable,
IEnumerable<bool> argumentsPropagateNullability,
Type returnType,
RelationalTypeMapping typeMapping = null)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(arguments, nameof(arguments));
Check.NotNull(argumentsPropagateNullability, nameof(argumentsPropagateNullability));
Check.NotNull(returnType, nameof(returnType));
var typeMappedArguments = new List<SqlExpression>();
foreach (var argument in arguments)
{
typeMappedArguments.Add(ApplyDefaultTypeMapping(argument));
}
return new SqlFunctionExpression(schema, name, typeMappedArguments, nullable, argumentsPropagateNullability, returnType, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression Function(
SqlExpression instance,
string name,
IEnumerable<SqlExpression> arguments,
bool nullable,
bool instancePropagatesNullability,
IEnumerable<bool> argumentsPropagateNullability,
Type returnType,
RelationalTypeMapping typeMapping = null)
{
Check.NotNull(instance, nameof(instance));
Check.NotEmpty(name, nameof(name));
Check.NotNull(arguments, nameof(arguments));
Check.NotNull(argumentsPropagateNullability, nameof(argumentsPropagateNullability));
Check.NotNull(returnType, nameof(returnType));
instance = ApplyDefaultTypeMapping(instance);
var typeMappedArguments = new List<SqlExpression>();
foreach (var argument in arguments)
{
typeMappedArguments.Add(ApplyDefaultTypeMapping(argument));
}
return new SqlFunctionExpression(instance, name, typeMappedArguments, nullable, instancePropagatesNullability, argumentsPropagateNullability, returnType, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression NiladicFunction(string name, bool nullable, Type returnType, RelationalTypeMapping typeMapping = null)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(returnType, nameof(returnType));
return new SqlFunctionExpression(name, nullable, returnType, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression NiladicFunction(string schema, string name, bool nullable, Type returnType, RelationalTypeMapping typeMapping = null)
{
Check.NotEmpty(schema, nameof(schema));
Check.NotEmpty(name, nameof(name));
Check.NotNull(returnType, nameof(returnType));
return new SqlFunctionExpression(schema, name, nullable, returnType, typeMapping);
}
/// <inheritdoc />
public virtual SqlFunctionExpression NiladicFunction(
SqlExpression instance,
string name,
bool nullable,
bool instancePropagatesNullability,
Type returnType,
RelationalTypeMapping typeMapping = null)
{
Check.NotNull(instance, nameof(instance));
Check.NotEmpty(name, nameof(name));
Check.NotNull(returnType, nameof(returnType));
return new SqlFunctionExpression(ApplyDefaultTypeMapping(instance), name, nullable, instancePropagatesNullability, returnType, typeMapping);
}
/// <inheritdoc />
public virtual ExistsExpression Exists(SelectExpression subquery, bool negated)
{
Check.NotNull(subquery, nameof(subquery));
return new ExistsExpression(subquery, negated, _boolTypeMapping);
}
/// <inheritdoc />
public virtual InExpression In(SqlExpression item, SqlExpression values, bool negated)
{
Check.NotNull(item, nameof(item));
Check.NotNull(values, nameof(values));
var typeMapping = item.TypeMapping ?? _typeMappingSource.FindMapping(item.Type);
item = ApplyTypeMapping(item, typeMapping);
values = ApplyTypeMapping(values, typeMapping);
return new InExpression(item, values, negated, _boolTypeMapping);
}
/// <inheritdoc />
public virtual InExpression In(SqlExpression item, SelectExpression subquery, bool negated)
{
Check.NotNull(item, nameof(item));
Check.NotNull(subquery, nameof(subquery));
var sqlExpression = subquery.Projection.Single().Expression;
var typeMapping = sqlExpression.TypeMapping;
if (typeMapping == null)
{
throw new InvalidOperationException(RelationalStrings.NoTypeMappingFoundForSubquery(subquery.Print(), sqlExpression.Type));
}
item = ApplyTypeMapping(item, typeMapping);
return new InExpression(item, subquery, negated, _boolTypeMapping);
}
/// <inheritdoc />
public virtual LikeExpression Like(SqlExpression match, SqlExpression pattern, SqlExpression escapeChar = null)
{
Check.NotNull(match, nameof(match));
Check.NotNull(pattern, nameof(pattern));
return (LikeExpression)ApplyDefaultTypeMapping(new LikeExpression(match, pattern, escapeChar, null));
}
/// <inheritdoc />
public virtual SqlFragmentExpression Fragment(string sql)
{
Check.NotNull(sql, nameof(sql));
return new SqlFragmentExpression(sql);
}
/// <inheritdoc />
public virtual SqlConstantExpression Constant(object value, RelationalTypeMapping typeMapping = null)
=> new SqlConstantExpression(Expression.Constant(value), typeMapping);
/// <inheritdoc />
public virtual SelectExpression Select(SqlExpression projection) => new SelectExpression(projection);
/// <inheritdoc />
public virtual SelectExpression Select(IEntityType entityType)
{
Check.NotNull(entityType, nameof(entityType));
var selectExpression = new SelectExpression(entityType);
AddConditions(selectExpression, entityType);
return selectExpression;
}
/// <inheritdoc />
public virtual SelectExpression Select(IEntityType entityType, TableExpressionBase tableExpressionBase)
{
Check.NotNull(entityType, nameof(entityType));
Check.NotNull(tableExpressionBase, nameof(tableExpressionBase));
var selectExpression = new SelectExpression(entityType, tableExpressionBase);
AddConditions(selectExpression, entityType);
return selectExpression;
}
/// <inheritdoc />
[Obsolete("Use overload which takes TableExpressionBase by passing FromSqlExpression directly.")]
public virtual SelectExpression Select(IEntityType entityType, string sql, Expression sqlArguments)
{
Check.NotNull(entityType, nameof(entityType));
Check.NotNull(sql, nameof(sql));
var tableExpression = new FromSqlExpression(
(entityType.GetViewOrTableMappings().SingleOrDefault()?.Table.Name ?? entityType.ShortName()).Substring(0, 1).ToLower(),
sql, sqlArguments);
var selectExpression = new SelectExpression(entityType, tableExpression);
AddConditions(selectExpression, entityType);
return selectExpression;
}
private void AddConditions(
SelectExpression selectExpression,
IEntityType entityType,
ITableBase table = null,
bool skipJoins = false)
{
if (entityType.FindPrimaryKey() == null)
{
AddDiscriminatorCondition(selectExpression, entityType);
}
else
{
var tableMappings = entityType.GetViewOrTableMappings();
if (!tableMappings.Any())
{
return;
}
table ??= tableMappings.Single().Table;
var discriminatorAdded = AddDiscriminatorCondition(selectExpression, entityType);
var linkingFks = table.GetRowInternalForeignKeys(entityType);
if (linkingFks.Any())
{
if (!discriminatorAdded)
{
AddOptionalDependentConditions(selectExpression, entityType, table);
}
if (!skipJoins)
{
var first = true;
foreach (var foreignKey in linkingFks)
{
if (!(entityType.FindOwnership() == foreignKey
&& foreignKey.PrincipalEntityType.BaseType == null))
{
var otherSelectExpression = first
? selectExpression
: new SelectExpression(entityType);
AddInnerJoin(otherSelectExpression, foreignKey, table, skipInnerJoins: false);
if (first)
{
first = false;
}
else
{
selectExpression.ApplyUnion(otherSelectExpression, distinct: true);
}
}
}
}
}
}
}
private void AddInnerJoin(
SelectExpression selectExpression, IForeignKey foreignKey, ITableBase table, bool skipInnerJoins)
{
var joinPredicate = GenerateJoinPredicate(selectExpression, foreignKey, table, skipInnerJoins, out var innerSelect);
selectExpression.AddInnerJoin(innerSelect, joinPredicate);
}
private SqlExpression GenerateJoinPredicate(
SelectExpression selectExpression,
IForeignKey foreignKey,
ITableBase table,
bool skipInnerJoins,
out SelectExpression innerSelect)
{
var outerEntityProjection = GetMappedEntityProjectionExpression(selectExpression);
var outerIsPrincipal = foreignKey.PrincipalEntityType.IsAssignableFrom(outerEntityProjection.EntityType);
innerSelect = outerIsPrincipal
? new SelectExpression(foreignKey.DeclaringEntityType)
: new SelectExpression(foreignKey.PrincipalEntityType);
AddConditions(
innerSelect,
outerIsPrincipal ? foreignKey.DeclaringEntityType : foreignKey.PrincipalEntityType,
table,
skipInnerJoins);
var innerEntityProjection = GetMappedEntityProjectionExpression(innerSelect);
var outerKey = (outerIsPrincipal ? foreignKey.PrincipalKey.Properties : foreignKey.Properties)
.Select(p => outerEntityProjection.BindProperty(p));
var innerKey = (outerIsPrincipal ? foreignKey.Properties : foreignKey.PrincipalKey.Properties)
.Select(p => innerEntityProjection.BindProperty(p));
return outerKey.Zip<SqlExpression, SqlExpression, SqlExpression>(innerKey, Equal)
.Aggregate(AndAlso);
}
private bool AddDiscriminatorCondition(SelectExpression selectExpression, IEntityType entityType)
{
if (entityType.GetRootType().GetIsDiscriminatorMappingComplete()
&& entityType.GetAllBaseTypesInclusiveAscending()
.All(e => (e == entityType || e.IsAbstract()) && !HasSiblings(e)))
{
return false;
}
SqlExpression predicate;
var concreteEntityTypes = entityType.GetConcreteDerivedTypesInclusive().ToList();
if (concreteEntityTypes.Count == 1)
{
var concreteEntityType = concreteEntityTypes[0];
if (concreteEntityType.BaseType == null)
{
return false;
}
var discriminatorColumn = GetMappedEntityProjectionExpression(selectExpression)
.BindProperty(concreteEntityType.GetDiscriminatorProperty());
predicate = Equal(discriminatorColumn, Constant(concreteEntityType.GetDiscriminatorValue()));
}
else
{
var discriminatorColumn = GetMappedEntityProjectionExpression(selectExpression)
.BindProperty(concreteEntityTypes[0].GetDiscriminatorProperty());
predicate = In(
discriminatorColumn, Constant(concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()), negated: false);
}
selectExpression.ApplyPredicate(predicate);
return true;
bool HasSiblings(IEntityType entityType)
{
return entityType.BaseType?.GetDirectlyDerivedTypes().Any(i => i != entityType) == true;
}
}
private void AddOptionalDependentConditions(
SelectExpression selectExpression, IEntityType entityType, ITableBase table)
{
SqlExpression predicate = null;
var requiredNonPkProperties = entityType.GetProperties().Where(p => !p.IsNullable && !p.IsPrimaryKey()).ToList();
if (requiredNonPkProperties.Count > 0)
{
var entityProjectionExpression = GetMappedEntityProjectionExpression(selectExpression);
predicate = IsNotNull(requiredNonPkProperties[0], entityProjectionExpression);
if (requiredNonPkProperties.Count > 1)
{
predicate
= requiredNonPkProperties
.Skip(1)
.Aggregate(
predicate, (current, property) =>
AndAlso(
IsNotNull(property, entityProjectionExpression),
current));
}
selectExpression.ApplyPredicate(predicate);
}
else
{
var allNonPkProperties = entityType.GetProperties().Where(p => !p.IsPrimaryKey()).ToList();
if (allNonPkProperties.Count > 0)
{
var entityProjectionExpression = GetMappedEntityProjectionExpression(selectExpression);
predicate = IsNotNull(allNonPkProperties[0], entityProjectionExpression);
if (allNonPkProperties.Count > 1)
{
predicate
= allNonPkProperties
.Skip(1)
.Aggregate(
predicate, (current, property) =>
OrElse(
IsNotNull(property, entityProjectionExpression),
current));
}
selectExpression.ApplyPredicate(predicate);
foreach (var referencingFk in entityType.GetReferencingForeignKeys())
{
var otherSelectExpression = new SelectExpression(entityType);
var sameTable = table.GetRowInternalForeignKeys(referencingFk.DeclaringEntityType).Any();
AddInnerJoin(
otherSelectExpression, referencingFk,
sameTable ? table : null,
skipInnerJoins: sameTable);
selectExpression.ApplyUnion(otherSelectExpression, distinct: true);
}
}
}
}
private EntityProjectionExpression GetMappedEntityProjectionExpression(SelectExpression selectExpression)
=> (EntityProjectionExpression)selectExpression.GetMappedProjection(new ProjectionMember());
private SqlExpression IsNotNull(IProperty property, EntityProjectionExpression entityProjection)
=> IsNotNull(entityProjection.BindProperty(property));
/// <inheritdoc />
[Obsolete("Use IRelationalTypeMappingSource directly.")]
public virtual RelationalTypeMapping GetTypeMappingForValue(object value) => _typeMappingSource.GetMappingForValue(value);
/// <inheritdoc />
[Obsolete("Use IRelationalTypeMappingSource directly.")]
public virtual RelationalTypeMapping FindMapping(Type type) => _typeMappingSource.FindMapping(Check.NotNull(type, nameof(type)));
}
}
| 42.421578 | 179 | 0.605383 | [
"Apache-2.0"
] | DotNetArtist/efcore | src/EFCore.Relational/Query/SqlExpressionFactory.cs | 42,464 | 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.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
private string _str;
private int[] _indexes;
// Legacy constructor
public StringInfo() : this("") { }
// Primary, useful constructor
public StringInfo(string value)
{
this.String = value;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (_str.Equals(that._str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return _str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes
{
get
{
if ((null == _indexes) && (0 < this.String.Length))
{
_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return (_indexes);
}
}
public string String
{
get
{
return (_str);
}
set
{
if (null == value)
{
throw new ArgumentNullException("String",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
_str = value;
_indexes = null;
}
}
public int LengthInTextElements
{
get
{
if (null == this.Indexes)
{
// Indexes not initialized, so assume length zero
return (0);
}
return (this.Indexes.Length);
}
}
public string SubstringByTextElements(int startingTextElement)
{
// If the string is empty, no sense going further.
if (null == this.Indexes)
{
// Just decide which error to give depending on the param they gave us....
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
else
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
}
return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement));
}
public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
if (this.String.Length == 0 || startingTextElement >= Indexes.Length)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
if (lengthInTextElements < 0)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum);
}
if (startingTextElement > Indexes.Length - lengthInTextElements)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException);
}
int start = Indexes[startingTextElement];
if (startingTextElement + lengthInTextElements == Indexes.Length)
{
// We are at the last text element in the string and because of that
// must handle the call differently.
return (this.String.Substring(start));
}
else
{
return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static string GetNextTextElement(string str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return (String.Empty);
}
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| 39.019553 | 191 | 0.538335 | [
"MIT"
] | LaudateCorpus1/corert | src/System.Private.CoreLib/src/System/Globalization/StringInfo.cs | 13,969 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BLL.DTOs;
using BLL.DTOs.Objects.Insurance;
using BLL.DTOs.Objects.InsuranceOffer;
using BLL.Facades.Common;
using BLL.QueryObjects;
using BLL.Services.Insurance;
using BLL.Services.InsuranceOffer;
using DAL.Infrastructure.UnitOfWork;
namespace BLL.Facades.Insurance
{
public class InsuranceFacade : FacadeBase, IInsuranceFacade
{
private readonly IInsuranceService insuranceService;
private readonly IInsuranceOfferService insuranceOfferService;
public InsuranceFacade(IUnitOfWorkProvider unitOfWorkProvider,
IInsuranceService insuranceService,
IInsuranceOfferService insuranceOfferService) : base(unitOfWorkProvider)
{
this.insuranceService = insuranceService;
this.insuranceOfferService = insuranceOfferService;
}
public async Task<bool> DeleteInsuranceAsync(int id)
{
using (var uow = unitOfWorkProvider.Create())
{
if ((await insuranceService.GetAsync(id, false)) == null)
{
return false;
}
await insuranceService.DeleteAsync(id);
await uow.CommitAsync();
return true;
}
}
public async Task<int> CreateInsuranceOfferAsync(InsuranceOfferCreateDTO entityDto)
{
using (var uow = unitOfWorkProvider.Create())
{
var id = await insuranceOfferService.CreateAsync(entityDto);
await uow.CommitAsync();
return id;
}
}
public async Task<int> CreateInsuranceAsync(InsuranceCreateDTO entityDto)
{
using (var uow = unitOfWorkProvider.Create())
{
var id = await insuranceService.CreateAsync(entityDto);
await uow.CommitAsync();
return id;
}
}
public async Task<InsuranceOfferGetDTO> GetInsuranceOfferAsync(int id, bool include=true)
{
using (var uow = unitOfWorkProvider.Create())
{
return await insuranceOfferService.GetAsync(id, include);
}
}
public async Task<InsuranceGetDTO> GetInsuranceAsync(int id, bool include = true)
{
using (var uow = unitOfWorkProvider.Create())
{
return await insuranceService.GetAsync(id, include);
}
}
private async Task<bool> UpdateAsync<TUpdateDto, TGetDto>(TUpdateDto entityDto, Func<TUpdateDto,
Task> updateAsync, Func<int, bool, Task<TGetDto>> getAsync)
where TUpdateDto : DTOBase, new()
{
using (var uow = unitOfWorkProvider.Create())
{
if ((await getAsync(entityDto.Id, false)) == null)
{
return false; // not in database
}
await updateAsync(entityDto);
await uow.CommitAsync();
}
return true;
}
public Task<bool> UpdateInsuranceAsync(InsuranceUpdateDTO entityDto)
{
return UpdateAsync(entityDto, insuranceService.UpdateAsync, insuranceService.GetAsync);
}
public Task<bool> UpdateInsuranceOfferAsync(InsuranceOfferUpdateDTO entityDto)
{
return UpdateAsync(entityDto, insuranceOfferService.UpdateAsync, insuranceOfferService.GetAsync);
}
public async Task<IEnumerable<InsuranceOfferGetDTO>> GetAllInsuranceOffersAsync(
int? directorId = null, bool active = true, bool sorted=true, QueryPagingDTO? queryPagingDto = null)
{
using (var uow = unitOfWorkProvider.Create())
{
return (await insuranceOfferService.GetAllOffersAsync(
directorId, active, sorted, queryPagingDto)).Dtos;
}
}
public async Task<IEnumerable<InsuranceOfferGetDTO>> GetAllInsuranceOffersWithIncludesAsync(
int? directorId = null, bool active = true, bool sorted = true, QueryPagingDTO? queryPagingDto = null)
{
using (var uow = unitOfWorkProvider.Create())
{
return (await insuranceOfferService.GetAllOffersWithIncludesAsync(
directorId, active, sorted, queryPagingDto)).Dtos;
}
}
public async Task<IEnumerable<InsuranceGetDTO>> GetAllInsurancesAsync(
int? clientId = null, bool active=true, bool sorted=true, QueryPagingDTO? queryPagingDto = null)
{
using (var uow = unitOfWorkProvider.Create())
{
return (await insuranceService.GetAllInsurancesAsync(
clientId, active, sorted, queryPagingDto)).Dtos;
}
}
public async Task<IEnumerable<InsuranceGetDTO>> GetAllInsurancesWithIncludesAsync(
int? clientId = null, bool active = true, bool sorted = true, QueryPagingDTO? queryPagingDto = null)
{
using (var uow = unitOfWorkProvider.Create())
{
return (await insuranceService.GetAllInsurancesWithIncludesAsync(
clientId, active, sorted, queryPagingDto)).Dtos;
}
}
}
} | 36.972789 | 113 | 0.599448 | [
"MIT"
] | michalSali/InsuranceAgency | src/BLL/Facades/Insurance/InsuranceFacade.cs | 5,435 | C# |
using System;
using System.Runtime.InteropServices;
namespace GtkDotNet.Raw
{
public class WebKitContext
{
[DllImport(Globals.LibWebKit, EntryPoint="webkit_web_context_get_default", CallingConvention = CallingConvention.Cdecl)]
public extern static IntPtr GetDefault();
[DllImport(Globals.LibWebKit, EntryPoint="webkit_web_context_clear_cache", CallingConvention = CallingConvention.Cdecl)]
public extern static void ClearCache(IntPtr context);
}
}
| 31 | 128 | 0.758065 | [
"MIT"
] | uriegel/GtkDotNet | GtkDotNet/Raw/WebKitContext.cs | 496 | 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.ContainerInstance.V20180401
{
/// <summary>
/// A container group.
/// </summary>
[AzureNativeResourceType("azure-native:containerinstance/v20180401:ContainerGroup")]
public partial class ContainerGroup : Pulumi.CustomResource
{
/// <summary>
/// The containers within the container group.
/// </summary>
[Output("containers")]
public Output<ImmutableArray<Outputs.ContainerResponse>> Containers { get; private set; } = null!;
/// <summary>
/// The image registry credentials by which the container group is created from.
/// </summary>
[Output("imageRegistryCredentials")]
public Output<ImmutableArray<Outputs.ImageRegistryCredentialResponse>> ImageRegistryCredentials { get; private set; } = null!;
/// <summary>
/// The instance view of the container group. Only valid in response.
/// </summary>
[Output("instanceView")]
public Output<Outputs.ContainerGroupResponseInstanceView> InstanceView { get; private set; } = null!;
/// <summary>
/// The IP address type of the container group.
/// </summary>
[Output("ipAddress")]
public Output<Outputs.IpAddressResponse?> IpAddress { get; private set; } = null!;
/// <summary>
/// The resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The operating system type required by the containers in the container group.
/// </summary>
[Output("osType")]
public Output<string> OsType { get; private set; } = null!;
/// <summary>
/// The provisioning state of the container group. This only appears in the response.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Restart policy for all containers within the container group.
/// - `Always` Always restart
/// - `OnFailure` Restart on failure
/// - `Never` Never restart
/// </summary>
[Output("restartPolicy")]
public Output<string?> RestartPolicy { get; private set; } = null!;
/// <summary>
/// The resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The list of volumes that can be mounted by containers in this container group.
/// </summary>
[Output("volumes")]
public Output<ImmutableArray<Outputs.VolumeResponse>> Volumes { get; private set; } = null!;
/// <summary>
/// Create a ContainerGroup resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ContainerGroup(string name, ContainerGroupArgs args, CustomResourceOptions? options = null)
: base("azure-native:containerinstance/v20180401:ContainerGroup", name, args ?? new ContainerGroupArgs(), MakeResourceOptions(options, ""))
{
}
private ContainerGroup(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:containerinstance/v20180401:ContainerGroup", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180401:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/latest:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/latest:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20170801preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20170801preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20171001preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20171001preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20171201preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20171201preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20180201preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180201preview:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20180601:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180601:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20180901:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20180901:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20181001:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20181001:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20191201:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20191201:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20201101:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20201101:ContainerGroup"},
new Pulumi.Alias { Type = "azure-native:containerinstance/v20210301:ContainerGroup"},
new Pulumi.Alias { Type = "azure-nextgen:containerinstance/v20210301:ContainerGroup"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ContainerGroup resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ContainerGroup Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ContainerGroup(name, id, options);
}
}
public sealed class ContainerGroupArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the container group.
/// </summary>
[Input("containerGroupName")]
public Input<string>? ContainerGroupName { get; set; }
[Input("containers", required: true)]
private InputList<Inputs.ContainerArgs>? _containers;
/// <summary>
/// The containers within the container group.
/// </summary>
public InputList<Inputs.ContainerArgs> Containers
{
get => _containers ?? (_containers = new InputList<Inputs.ContainerArgs>());
set => _containers = value;
}
[Input("imageRegistryCredentials")]
private InputList<Inputs.ImageRegistryCredentialArgs>? _imageRegistryCredentials;
/// <summary>
/// The image registry credentials by which the container group is created from.
/// </summary>
public InputList<Inputs.ImageRegistryCredentialArgs> ImageRegistryCredentials
{
get => _imageRegistryCredentials ?? (_imageRegistryCredentials = new InputList<Inputs.ImageRegistryCredentialArgs>());
set => _imageRegistryCredentials = value;
}
/// <summary>
/// The IP address type of the container group.
/// </summary>
[Input("ipAddress")]
public Input<Inputs.IpAddressArgs>? IpAddress { get; set; }
/// <summary>
/// The resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The operating system type required by the containers in the container group.
/// </summary>
[Input("osType", required: true)]
public InputUnion<string, Pulumi.AzureNative.ContainerInstance.V20180401.OperatingSystemTypes> OsType { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Restart policy for all containers within the container group.
/// - `Always` Always restart
/// - `OnFailure` Restart on failure
/// - `Never` Never restart
/// </summary>
[Input("restartPolicy")]
public InputUnion<string, Pulumi.AzureNative.ContainerInstance.V20180401.ContainerGroupRestartPolicy>? RestartPolicy { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// The resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("volumes")]
private InputList<Inputs.VolumeArgs>? _volumes;
/// <summary>
/// The list of volumes that can be mounted by containers in this container group.
/// </summary>
public InputList<Inputs.VolumeArgs> Volumes
{
get => _volumes ?? (_volumes = new InputList<Inputs.VolumeArgs>());
set => _volumes = value;
}
public ContainerGroupArgs()
{
}
}
}
| 45.100775 | 151 | 0.61241 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ContainerInstance/V20180401/ContainerGroup.cs | 11,636 | C# |
using System.Data;
using System.Data.Common;
namespace DbFacade.DataLayer.ConnectionService.MockDb
{
/// <summary>
///
/// </summary>
internal class MockDbParameter : DbParameter
{
/// <summary>
/// Gets or sets the type of the database.
/// </summary>
/// <value>
/// The type of the database.
/// </value>
private DbType _DbType { get; set; }
/// <summary>
/// Gets or sets the direction.
/// </summary>
/// <value>
/// The direction.
/// </value>
private ParameterDirection _Direction { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is nullable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is nullable; otherwise, <c>false</c>.
/// </value>
private bool _IsNullable { get; set; }
/// <summary>
/// Gets or sets the name of the parameter.
/// </summary>
/// <value>
/// The name of the parameter.
/// </value>
private string _ParameterName { get; set; }
/// <summary>
/// Gets or sets the size.
/// </summary>
/// <value>
/// The size.
/// </value>
private int _Size { get; set; }
/// <summary>
/// Gets or sets the source column.
/// </summary>
/// <value>
/// The source column.
/// </value>
private string _SourceColumn { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [source column null mapping].
/// </summary>
/// <value>
/// <c>true</c> if [source column null mapping]; otherwise, <c>false</c>.
/// </value>
private bool _SourceColumnNullMapping { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
private object _Value { get; set; }
/// <summary>
/// Gets or sets the type of the database.
/// </summary>
/// <value>
/// The type of the database.
/// </value>
public override DbType DbType { get => _DbType; set => _DbType=value; }
/// <summary>
/// Gets or sets the direction.
/// </summary>
/// <value>
/// The direction.
/// </value>
public override ParameterDirection Direction { get => _Direction; set => _Direction = value; }
/// <summary>
/// Gets or sets a value indicating whether this instance is nullable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is nullable; otherwise, <c>false</c>.
/// </value>
public override bool IsNullable { get => _IsNullable; set => _IsNullable = value; }
/// <summary>
/// Gets or sets the name of the parameter.
/// </summary>
/// <value>
/// The name of the parameter.
/// </value>
public override string ParameterName { get => _ParameterName; set => _ParameterName = value; }
/// <summary>
/// Parameters the name as key.
/// </summary>
/// <returns></returns>
public string ParameterNameAsKey() => _ParameterName.Replace("@", "");
/// <summary>
/// Gets or sets the size.
/// </summary>
/// <value>
/// The size.
/// </value>
public override int Size { get => _Size; set => _Size = value; }
/// <summary>
/// Gets or sets the source column.
/// </summary>
/// <value>
/// The source column.
/// </value>
public override string SourceColumn { get => _SourceColumn; set => _SourceColumn = value; }
/// <summary>
/// Gets or sets a value indicating whether [source column null mapping].
/// </summary>
/// <value>
/// <c>true</c> if [source column null mapping]; otherwise, <c>false</c>.
/// </value>
public override bool SourceColumnNullMapping { get => _SourceColumnNullMapping; set => _SourceColumnNullMapping = value; }
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
public override object Value { get => _Value; set => _Value = value; }
/// <summary>
/// Resets the type of the database.
/// </summary>
public override void ResetDbType() => _DbType = DbType.Int32;
}
}
| 34.073529 | 130 | 0.503237 | [
"MIT"
] | JSystemsTech/DBFacade.Net | DbFacadeShared/DataLayer/ConnectionService/MockDb/MockDbParameter.cs | 4,636 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Scores = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<double>>>;
namespace LightGBMSharp
{
public static class LGBM
{
/// <summary>
///
/// </summary>
/// <returns>a trained <see cref="Booster"/></returns>
public static Booster Train(Estimator estimator, Dataset trainSet, Scores evalResult, params Dataset[] validationSets)
{
//var estParameters = estimator.ToDictionary(Constants.BoosterParameters);
var estParameters = estimator.ToDictionary();
var earlyStoppingRound = estimator.EarlyStoppingRound ;
var paramString = estParameters.ToParamsString();
var booster = new Booster(trainSet, paramString);
if (validationSets.Length > 0)
{
for (int testNdx = 0; testNdx < validationSets.Length; testNdx++)
{
var testName = $"Test_{testNdx}";
// booster.add_valid(valid_set, name_valid_set)
booster.AddValidData(validationSets[testNdx], testName);
}
}
var initIteration = 0;
var trainDataName = "training";
List<Callback> cbs = new List<Callback>();
cbs.Add(DefaultCallback.PrintScore());
evalResult = new Scores();
if (evalResult != null)
{
cbs.Add(DefaultCallback.StoreScore(evalResult));
}
if (earlyStoppingRound.HasValue)
cbs.Add(DefaultCallback.EarlyStopping(earlyStoppingRound.Value));
var evaluationResultList = new List<EvaluationResult>();
// start training
for (int iter = initIteration; iter < estimator.NumIterations; iter++)
{
var isFinished = booster.Update();
#if DEBUG
ConsoleColor cc = isFinished ? ConsoleColor.Red : ConsoleColor.Green;
Console.ForegroundColor = cc;
Console.WriteLine($"Iter {iter} ::: IsFinished = {isFinished}");
Console.ResetColor();
#endif
evaluationResultList.Clear();
//if valid_sets is not None:
if (validationSets.Length > 0)
{
var evData = booster.EvaluateValidationData();
evaluationResultList.AddRange(evData);
}
var cbenv = new CallbackEnv
{
Booster = booster,
Estimator = estimator,
Iteration = iter,
EvaluationList = evaluationResultList.ToList()
};
try
{
foreach (var cb in cbs)
cb(cbenv);
}
catch (EarlyStopException esex)
{
booster.BestIteration = esex.BestIteration + 1;
evaluationResultList = esex.BestScoreList as List<EvaluationResult> ?? esex.BestScoreList.ToList();
break;
}
}
var grp = evaluationResultList
.GroupBy(evr => evr.TestName)
.ToDictionary(
g => g.Key,
g => g
.ToDictionary(
g1 => g1.MetricName,
g1 => g1.Score)
);
booster.BestScore.Clear();
booster.BestScore.Merge(grp);
return booster;
}
}
}
| 36.446602 | 149 | 0.511987 | [
"MIT"
] | ttustonic/LightGBMSharp | LightGBM/LGBM.cs | 3,756 | 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.ConnectedMachine.Models.Api20
{
using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Extensions;
/// <summary>The error detail.</summary>
public partial class ErrorDetail
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject into a new instance of <see cref="ErrorDetail" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject instance to deserialize from.</param>
internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_code = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString>("code"), out var __jsonCode) ? (string)__jsonCode : (string)Code;}
{_message = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString>("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;}
{_target = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString>("target"), out var __jsonTarget) ? (string)__jsonTarget : (string)Target;}
{_detail = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonArray>("details"), out var __jsonDetails) ? If( __jsonDetails as Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorDetail[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.ErrorDetail.FromJson(__u) )) ))() : null : Detail;}
{_additionalInfo = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonArray>("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonArray, out var __q) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorAdditionalInfo[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : AdditionalInfo;}
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorDetail.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorDetail.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject json ? new ErrorDetail(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="ErrorDetail" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ErrorDetail" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._detail)
{
var __w = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.XNodeArray();
foreach( var __x in this._detail )
{
AddIf(__x?.ToJson(null, serializationMode) ,__w.Add);
}
container.Add("details",__w);
}
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._additionalInfo)
{
var __r = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.XNodeArray();
foreach( var __s in this._additionalInfo )
{
AddIf(__s?.ToJson(null, serializationMode) ,__r.Add);
}
container.Add("additionalInfo",__r);
}
}
AfterToJson(ref container);
return container;
}
}
} | 77.096552 | 726 | 0.686018 | [
"MIT"
] | Agazoth/azure-powershell | src/ConnectedMachine/generated/api/Models/Api20/ErrorDetail.json.cs | 11,035 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Gadgeteer.Designer {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class CodeGenerationResource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal CodeGenerationResource() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Gadgeteer.Designer.CodeGenerationResource", typeof(CodeGenerationResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static byte[] CustomToolTemplateFile {
get {
object obj = ResourceManager.GetObject("CustomToolTemplateFile", resourceCulture);
return ((byte[])(obj));
}
}
internal static byte[] CustomToolTemplateFileVB {
get {
object obj = ResourceManager.GetObject("CustomToolTemplateFileVB", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?>
///<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
/// xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
///>
/// <xsl:output method="html" indent="yes"/>
///
/// <xsl:param name="moreInfoUrl"/>
///
/// <xsl:template match="/">
/// <head>
/// <title>
/// <xsl:value-of select="doc/assembly/name"/>
/// </title>
/// <style>
/// div, h1, h2, .pageTitle, table, dl, h3, p {font-family: "Segoe UI", Verdana, Arial; margin: 0px 12px [rest of string was truncated]";.
/// </summary>
internal static string xmldoc2html {
get {
return ResourceManager.GetString("xmldoc2html", resourceCulture);
}
}
}
}
| 44.485149 | 209 | 0.590919 | [
"Apache-2.0"
] | martinca-msft/Gadgeteer | NETMF_42/GadgeteerCore/VisualStudio/Designer/DslPackage/CodeGenerationResource.Designer.cs | 4,495 | C# |
namespace P03_FootballBetting.Data.Models
{
using System.Collections.Generic;
public class Country
{
//------------ Properties -------------
public int CountryId { get; set; }
public string Name { get; set; }
//------ Towns ----- [FK]
public ICollection<Town> Towns { get; set; } = new HashSet<Town>();
}
}
| 24.4 | 75 | 0.530055 | [
"MIT"
] | radrex/SoftuniCourses | C# Web Developer/C# DB/02.Entity Framework Core/05.Entity Relations/Exercise/P03_FootballBetting/P03_FootballBetting.Data.Models/Country.cs | 368 | C# |
using UnityEngine;
using System.Collections;
public class EnterSceneArgs {
//----进入场景事件的参数
//场景ID
public int LevelID;
//场景名
public string CurrentSceneName
{
get
{
return Application.loadedLevelName;
}
}
}
| 15.111111 | 47 | 0.580882 | [
"MIT"
] | yuqtj/UnityGame_college | Assets/Scripts/Application/Args/EnterSceneArgs.cs | 302 | C# |
// Copyright (c) 2019-2021 Andreas Atteneder, All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// TODO: Re-using transcoders does not work consistently. Fix and enable!
// #define POOL_TRANSCODERS
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Experimental.Rendering;
using Unity.Jobs;
using Unity.Collections;
namespace KtxUnity {
public static class BasisUniversal
{
static bool initialized;
static int transcoderCountAvailable = 8;
#if POOL_TRANSCODERS
static Stack<TranscoderInstance> transcoderPool;
#endif
static void InitInternal()
{
initialized = true;
TranscodeFormatHelper.Init();
ktx_basisu_basis_init();
transcoderCountAvailable = UnityEngine.SystemInfo.processorCount;
}
public static BasisUniversalTranscoderInstance GetTranscoderInstance() {
if (!initialized) {
InitInternal();
}
#if POOL_TRANSCODERS
if(transcoderPool!=null) {
return transcoderPool.Pop();
}
#endif
if (transcoderCountAvailable > 0) {
transcoderCountAvailable--;
return new BasisUniversalTranscoderInstance(ktx_basisu_create_basis());
} else {
return null;
}
}
public static void ReturnTranscoderInstance(BasisUniversalTranscoderInstance transcoder) {
#if POOL_TRANSCODERS
if(transcoderPool==null) {
transcoderPool = new Stack<TranscoderInstance>();
}
transcoderPool.Push(transcoder);
#endif
transcoderCountAvailable++;
}
public unsafe static JobHandle LoadBytesJob(
ref BasisUniversalJob job,
BasisUniversalTranscoderInstance basis,
NativeSlice<byte> basisuData,
TranscodeFormat transF )
{
Profiler.BeginSample("BasisU.LoadBytesJob");
var numLevels = basis.GetLevelCount(job.imageIndex);
int levelsNeeded = (int)((uint)numLevels - job.mipLevel);
if (job.mipChain == false)
levelsNeeded = 1;
var sizes = new NativeArray<uint>((int)levelsNeeded, KtxNativeInstance.defaultAllocator);
var offsets = new NativeArray<uint>((int)levelsNeeded, KtxNativeInstance.defaultAllocator);
uint totalSize = 0;
for (uint i = job.mipLevel; i<numLevels; i++)
{
offsets[(int)i - (int)job.mipLevel] = totalSize;
var size = basis.GetImageTranscodedSize(job.imageIndex, i, transF);
sizes[(int)i - (int)job.mipLevel] = size;
totalSize += size;
if (job.mipChain == false)
break;
}
job.format = transF;
job.sizes = sizes;
job.offsets = offsets;
job.nativeReference = basis.nativeReference;
job.textureData = new NativeArray<byte>((int) totalSize, KtxNativeInstance.defaultAllocator);
bool separateAlpha = false;
if (basis.GetHasAlpha() && (
(transF == TranscodeFormat.ETC1_RGB) ||
(transF == TranscodeFormat.BC1_RGB) ||
(transF == TranscodeFormat.BC4_R)||
(transF == TranscodeFormat.PVRTC1_4_RGB) ||
(transF == TranscodeFormat.ATC_RGB))
)
{
UnityEngine.Debug.Log("Target does not support alpha creating separate alpha mask as source has alpha");
separateAlpha = true;
}
if (separateAlpha)
{
job.textureDataAlpha = new NativeArray<byte>((int) totalSize, KtxNativeInstance.defaultAllocator);
}
else
{
job.textureDataAlpha = new NativeArray<byte>((int)0, KtxNativeInstance.defaultAllocator); ;
}
var jobHandle = job.Schedule();
Profiler.EndSample();
return jobHandle;
}
[DllImport(KtxNativeInstance.INTERFACE_DLL)]
private static extern void ktx_basisu_basis_init();
[DllImport(KtxNativeInstance.INTERFACE_DLL)]
private static unsafe extern System.IntPtr ktx_basisu_create_basis();
}
} | 37.248175 | 121 | 0.589065 | [
"Apache-2.0"
] | kyapp69/KtxUnity | Runtime/Scripts/BasisUniversal.cs | 5,105 | C# |
//-----------------------------------------------------------------------
// <copyright file="Page1.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary></summary>
//-----------------------------------------------------------------------
using System;
using Wisej.Web;
namespace ActionExtenderSample
{
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var id = "aea60714-d38b-4c08-9c5c-22fe6e0e7e64";
var orderId = new Guid(id);
var frm = new OrderMaint(orderId);
frm.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
var id = "aea60714-d38b-4c08-9c5c-22fe6e0e7e64";
var orderId = new Guid(id);
var frm = new OrderMaint2(orderId);
frm.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
var id = "aea60714-d38b-4c08-9c5c-22fe6e0e7e64";
var orderId = new Guid(id);
var frm = new OrderMaint3(orderId);
frm.ShowDialog();
}
}
}
| 24.9375 | 74 | 0.553049 | [
"MIT"
] | MarimerLLC/cslacontrib | trunk/samples/ActionExtenderSample/ActionExtenderSample.WisejWeb/Page1.cs | 1,199 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GamingRecorderAssistant
{
public class programConfig
{
#region Config vars
//CONTROLS - Vars for restoring control values
public bool recording_ctrl, recording_shift, recording_alt = false;
public string recording_mainKey = "Numpad 1";
public bool break_ctrl, break_shift, break_alt = false;
public string break_mainKey = "Numpad 2";
public bool poi_ctrl, poi_shift, poi_alt = false;
public string poi_mainKey = "Numpad 3";
//Absolute Values
public int keyBindSumRecording = 97;
public int keyBindModifierSumRecording = 0;
public int keyBindSumBreak = 98;
public int keyBindModifierSumBreak = 0;
public int keyBindSumPOI = 99;
public int keyBindModifierSumPOI = 0;
#endregion
public static object DeserializeObject<T>(string toDeserialize)
{
//XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize.GetType());
//StringReader textReader = new StringReader(toDeserialize);
return JsonConvert.DeserializeObject<programConfig>(toDeserialize);
//return xmlSerializer.Deserialize(textReader);
}
public static string SerializeObject<T>(T toSerialize)
{
return JsonConvert.SerializeObject(toSerialize);
}
}
}
| 28.716981 | 87 | 0.671485 | [
"Apache-2.0"
] | Erlendftw/GamingRecorderAssistant | GamingRecorderAssistant/programConfig.cs | 1,524 | C# |
using Centaurus.Models;
using Centaurus.DAL;
using Centaurus.Exchange.Analytics;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Centaurus.Test.Exchange.Analytics
{
public class AnalyticsManagerTest : BaseAnalyticsTest
{
[Test]
public async Task RestoreTest()
{
GenerateTrades(10_000);
await analyticsManager.SaveUpdates(storage);
var restoredAnalyticsManager = new AnalyticsManager(storage, new List<double> { 1 }, markets, new List<OrderInfo>(), historyLength);
await restoredAnalyticsManager.Restore(now);
foreach (var market in markets)
{
foreach (var period in Enum.GetValues(typeof(PriceHistoryPeriod)).Cast<PriceHistoryPeriod>())
{
var frames = await analyticsManager.PriceHistoryManager.GetPriceHistory(0, market, period);
var restoredFrames = await restoredAnalyticsManager.PriceHistoryManager.GetPriceHistory(0, market, period);
Assert.AreEqual(frames.frames.Count, restoredFrames.frames.Count, "Current frames unit and restored frames unit have different size.");
for (var i = 0; i < frames.frames.Count; i++)
{
var frame = frames.frames[i];
var restoredFrame = restoredFrames.frames[i];
Assert.IsTrue(frame.StartTime == restoredFrame.StartTime &&
frame.Period == restoredFrame.Period &&
frame.Market == restoredFrame.Market &&
frame.High == restoredFrame.High &&
frame.Low == restoredFrame.Low &&
frame.Open == restoredFrame.Open &&
frame.Close == restoredFrame.Close &&
frame.BaseVolume == restoredFrame.BaseVolume &&
frame.CounterVolume == restoredFrame.CounterVolume,
"Restored frame doesn't equal to current frame.");
}
}
}
}
}
}
| 42.735849 | 155 | 0.573951 | [
"MIT"
] | PinkDiamond1/centaurus | Centaurus.Test.Exchange.Analytics/AnalyticsManagerTest.cs | 2,267 | C# |
using System.Linq;
using Clarity.App.Worlds.Helpers;
using Clarity.App.Worlds.Interaction.Tools;
using Clarity.App.Worlds.StoryGraph.Editing.Flowchart;
using Clarity.Common.CodingUtilities.Sugar.Extensions.Collections;
using Clarity.Engine.Interaction.Input;
using Clarity.Engine.Interaction.Input.Mouse;
using Clarity.Engine.Interaction.RayHittables;
namespace Clarity.App.Worlds.StoryGraph.Editing
{
public class StoryBranchIntoTool : ITool
{
private readonly IRayHitIndex rayHitIndex;
private readonly IStoryService storyService;
private readonly IToolService toolService;
private readonly ICommonNodeFactory commonNodeFactory;
private readonly int from;
public StoryBranchIntoTool(int from, IRayHitIndex rayHitIndex, IToolService toolService, IStoryService storyService, ICommonNodeFactory commonNodeFactory)
{
this.from = from;
this.rayHitIndex = rayHitIndex;
this.toolService = toolService;
this.storyService = storyService;
this.commonNodeFactory = commonNodeFactory;
}
public bool TryHandleInputEvent(IInputEvent eventArgs)
{
if (!(eventArgs is MouseEvent args))
return false;
if (!args.IsLeftClickEvent())
return false;
var clickInfo = new RayCastInfo(args.Viewport, args.Viewport.View.Layers.Single(), args.State.Position);
var hitResult = rayHitIndex.CastRay(clickInfo).FirstOrNull() ?? RayHitResult.Failure();
if (hitResult.Successful)
{
int? to = null;
var gizmoComponentTo = hitResult.Node.GetComponent<StoryFlowchartNodeGizmoComponent>();
if (gizmoComponentTo != null && gizmoComponentTo.ReferencedNode.Id != from)
to = gizmoComponentTo.ReferencedNode.Id;
if (storyService.GlobalGraph.NodeIds.Contains(hitResult.Node.Id))
to = hitResult.Node.Id;
if (to.HasValue)
{
var child = StoryOperations.AddChild(storyService, commonNodeFactory, to.Value, this);
storyService.AddEdge(from, child.Id);
toolService.CurrentTool = null;
return true;
}
}
toolService.CurrentTool = null;
return false;
}
public void Dispose()
{
}
}
} | 39.84127 | 162 | 0.628685 | [
"MIT"
] | Zulkir/ClarityWorlds | Source/Clarity.App.Worlds/StoryGraph/Editing/StoryBranchIntoTool.cs | 2,512 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static LiteDB.Constants;
namespace LiteDB.Engine
{
/// <summary>
/// Internal class to read all datafile documents - use only Stream - no cache system (database are modified during this read - shrink)
/// </summary>
internal class FileReaderV8 : IFileReader
{
private readonly Dictionary<string, uint> _collections;
private readonly Stream _stream;
private readonly byte[] _buffer = new byte[PAGE_SIZE];
private BasePage _cachedPage = null;
public FileReaderV8(HeaderPage header, DiskService disk)
{
_collections = header.GetCollections().ToDictionary(x => x.Key, x => x.Value);
// using writer stream from pool (no need to return)
_stream = disk.GetPool(FileOrigin.Data).Writer;
}
/// <summary>
/// Read all collection based on header page
/// </summary>
public IEnumerable<string> GetCollections()
{
return _collections.Keys;
}
/// <summary>
/// Read all indexes from all collection pages (except _id index)
/// </summary>
public IEnumerable<IndexInfo> GetIndexes(string collection)
{
var page = this.ReadPage<CollectionPage>(_collections[collection]);
foreach(var index in page.GetCollectionIndexes().Where(x => x.Name != "_id"))
{
yield return new IndexInfo
{
Collection = collection,
Name = index.Name,
Expression = index.Expression,
Unique = index.Unique
};
}
}
/// <summary>
/// Read all documents from current collection with NO index use - read direct from free lists
/// There is no document order
/// </summary>
public IEnumerable<BsonDocument> GetDocuments(string collection)
{
var colPage = this.ReadPage<CollectionPage>(_collections[collection]);
for (var slot = 0; slot < PAGE_FREE_LIST_SLOTS; slot++)
{
var next = colPage.FreeDataPageList[slot];
while (next != uint.MaxValue)
{
var page = this.ReadPage<DataPage>(next);
foreach (var block in page.GetBlocks().ToArray())
{
using (var r = new BufferReader(this.ReadBlocks(block)))
{
var doc = r.ReadDocument(null);
yield return doc;
}
}
next = page.NextPageID;
}
}
}
/// <summary>
/// Read page from stream - do not use cache system
/// </summary>
private T ReadPage<T>(uint pageID)
where T : BasePage
{
var position = BasePage.GetPagePosition(pageID);
if (_cachedPage?.PageID == pageID) return (T)_cachedPage;
_stream.Position = position;
_stream.Read(_buffer, 0, PAGE_SIZE);
var buffer = new PageBuffer(_buffer, 0, 0);
return (T)(_cachedPage = BasePage.ReadPage<T>(buffer));
}
/// <summary>
/// Get all data blocks from first data block
/// </summary>
public IEnumerable<BufferSlice> ReadBlocks(PageAddress address)
{
while (address != PageAddress.Empty)
{
var dataPage = this.ReadPage<DataPage>(address.PageID);
var block = dataPage.GetBlock(address.Index);
yield return block.Buffer;
address = block.NextBlock;
}
}
}
} | 32.196721 | 139 | 0.537678 | [
"MIT"
] | 7eXx/LiteDB | LiteDB/Engine/FileReader/FileReaderV8.cs | 3,930 | C# |
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Wexflow.Tasks.Tests
{
[TestClass]
public class Movedir
{
private static readonly string Src = @"C:\WexflowTesting\Folder";
private static readonly string Dest = @"C:\WexflowTesting\Folder1";
[TestInitialize]
public void TestInitialize()
{
if (Directory.Exists(Dest))
{
Helper.DeleteFilesAndFolders(Dest);
Directory.Delete(Dest);
}
}
[TestCleanup]
public void TestCleanup()
{
Directory.Move(Dest, Src);
}
[TestMethod]
public void MovedirTest()
{
Assert.AreEqual(true, Directory.Exists(Src));
Assert.AreEqual(false, Directory.Exists(Dest));
Helper.StartWorkflow(44);
Assert.AreEqual(false, Directory.Exists(Src));
Assert.AreEqual(true, Directory.Exists(Dest));
}
}
}
| 26.076923 | 75 | 0.567355 | [
"MIT"
] | Nongzhsh/WexFlow | tests/Wexflow.Tasks.Tests/Movedir.cs | 1,019 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KeyManagementService.Model
{
/// <summary>
/// Container for the parameters to the DeleteCustomKeyStore operation.
/// Deletes a <a href="https://docs.aws.amazon.com/kms/latest/developerguide/custom-key-store-overview.html">custom
/// key store</a>. This operation does not delete the AWS CloudHSM cluster that is associated
/// with the custom key store, or affect any users or keys in the cluster.
///
///
/// <para>
/// The custom key store that you delete cannot contain any AWS KMS <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys">customer
/// master keys (CMKs)</a>. Before deleting the key store, verify that you will never
/// need to use any of the CMKs in the key store for any <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations">cryptographic
/// operations</a>. Then, use <a>ScheduleKeyDeletion</a> to delete the AWS KMS customer
/// master keys (CMKs) from the key store. When the scheduled waiting period expires,
/// the <code>ScheduleKeyDeletion</code> operation deletes the CMKs. Then it makes a best
/// effort to delete the key material from the associated cluster. However, you might
/// need to manually <a href="https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html#fix-keystore-orphaned-key">delete
/// the orphaned key material</a> from the cluster and its backups.
/// </para>
///
/// <para>
/// After all CMKs are deleted from AWS KMS, use <a>DisconnectCustomKeyStore</a> to disconnect
/// the key store from AWS KMS. Then, you can delete the custom key store.
/// </para>
///
/// <para>
/// Instead of deleting the custom key store, consider using <a>DisconnectCustomKeyStore</a>
/// to disconnect it from AWS KMS. While the key store is disconnected, you cannot create
/// or use the CMKs in the key store. But, you do not need to delete CMKs and you can
/// reconnect a disconnected custom key store at any time.
/// </para>
///
/// <para>
/// If the operation succeeds, it returns a JSON object with no properties.
/// </para>
///
/// <para>
/// This operation is part of the <a href="https://docs.aws.amazon.com/kms/latest/developerguide/custom-key-store-overview.html">Custom
/// Key Store feature</a> feature in AWS KMS, which combines the convenience and extensive
/// integration of AWS KMS with the isolation and control of a single-tenant key store.
/// </para>
/// </summary>
public partial class DeleteCustomKeyStoreRequest : AmazonKeyManagementServiceRequest
{
private string _customKeyStoreId;
/// <summary>
/// Gets and sets the property CustomKeyStoreId.
/// <para>
/// Enter the ID of the custom key store you want to delete. To find the ID of a custom
/// key store, use the <a>DescribeCustomKeyStores</a> operation.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string CustomKeyStoreId
{
get { return this._customKeyStoreId; }
set { this._customKeyStoreId = value; }
}
// Check to see if CustomKeyStoreId property is set
internal bool IsSetCustomKeyStoreId()
{
return this._customKeyStoreId != null;
}
}
} | 44.865979 | 177 | 0.680377 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/KeyManagementService/Generated/Model/DeleteCustomKeyStoreRequest.cs | 4,352 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:760c4f0cb9ab138b84236a19eac9de4cbe1b9dde11cf9ab4bb474c4fb2242dda
size 2983
| 32.25 | 75 | 0.883721 | [
"Apache-2.0"
] | cybex-dev/VRAdventure2 | Assets/Moe Baker/Moe Tools/_Editor/Tools/InspectorTools.cs | 129 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Imazen.PersistentCache
{
internal static class ClockExtensions
{
public static uint GetMinutes(this IClock clock)
{
return (uint)(clock.GetTicks() / clock.TicksPerSecond / 60);
}
}
internal class UsageTracker
{
struct UsageRecord
{
internal uint lastRead;
internal uint frequency;
internal UsageRecord(IClock clock)
{
lastRead = clock.GetMinutes();
frequency = 1;
}
internal uint GetCurrentFrequency(uint nowMinutes, uint halfLifeMinutes)
{
if (nowMinutes - lastRead > halfLifeMinutes)
{
long decayTimes = (nowMinutes - lastRead) / halfLifeMinutes;
return (uint)(frequency / (2 * decayTimes));
}
else
{
return frequency;
}
}
}
long pingCount = 0;
readonly uint halfLifeMinutes;
readonly IClock clock;
readonly ConcurrentDictionary<uint, UsageRecord> usage = new ConcurrentDictionary<uint, UsageRecord>();
/// <summary>
/// Creates a usage tracker
/// </summary>
/// <param name="clock">The source of time info</param>
/// <param name="halfLifeMinutes">How often (int minutes) to halve the usage counter</param>
internal UsageTracker(IClock clock, uint halfLifeMinutes)
{
this.halfLifeMinutes = halfLifeMinutes;
this.clock = clock;
}
private UsageRecord PingUpdate(uint key, UsageRecord oldValue)
{
var now = clock.GetMinutes();
// Saturating addition
var oldFrequency = oldValue.GetCurrentFrequency(now, halfLifeMinutes);
oldValue.frequency = Math.Max(oldFrequency + 1, oldFrequency);
oldValue.lastRead = now;
return oldValue;
}
internal void Ping(uint key)
{
usage.AddOrUpdate(key, new UsageRecord(clock), PingUpdate);
Interlocked.Increment(ref this.pingCount);
}
internal long PingCount()
{
return this.pingCount;
}
internal uint GetFrequency(uint key)
{
if (usage.TryGetValue(key, out UsageRecord r))
{
return r.GetCurrentFrequency(clock.GetMinutes(), halfLifeMinutes);
}
else
{
return 0;
}
}
void MergeRecord(uint key, UsageRecord record)
{
usage.AddOrUpdate(key, record, (k, oldValue) =>
{
if (oldValue.lastRead > record.lastRead)
{
return oldValue;
}
else
{
return record;
}
});
}
internal async Task MergeLoad(Stream stream, CancellationToken cancellationToken)
{
const int recordLength = 12;
var buffer = new byte[recordLength * 200];
int bytesRead;
do
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
for (int i = 0; i <= bytesRead - recordLength; i += recordLength)
{
cancellationToken.ThrowIfCancellationRequested();
var key = BitConverter.ToUInt32(buffer, i);
var record = new UsageRecord {
lastRead = BitConverter.ToUInt32(buffer, i + 4),
frequency = BitConverter.ToUInt32(buffer, i + 8)
};
MergeRecord(key, record);
}
} while (bytesRead > 0);
}
internal byte[] Serialize()
{
var data = new List<byte>((usage.Count + 10) * 12);
var now = clock.GetMinutes();
foreach (var pair in usage)
{
// Filter out frequencies below 2, they have expired
if (pair.Value.GetCurrentFrequency(now, halfLifeMinutes) > 1)
{
data.AddRange(BitConverter.GetBytes(pair.Key));
data.AddRange(BitConverter.GetBytes(pair.Value.lastRead));
data.AddRange(BitConverter.GetBytes(pair.Value.frequency));
}
}
return data.ToArray();
}
}
}
| 32.099338 | 111 | 0.522385 | [
"Apache-2.0"
] | ajbeaven/imageflow-dotnet-server | src/Imazen.PersistentCache/UsageTracker.cs | 4,849 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace pxr {
public class SWIGTYPE_p_VtDictionary__IteratorT_std__mapT_std__string_VtValue_std__lessT_t_t_p_std__mapT_std__string_VtValue_std__lessT_t_t__iterator_t {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal SWIGTYPE_p_VtDictionary__IteratorT_std__mapT_std__string_VtValue_std__lessT_t_t_p_std__mapT_std__string_VtValue_std__lessT_t_t__iterator_t(global::System.IntPtr cPtr, bool futureUse) {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
protected SWIGTYPE_p_VtDictionary__IteratorT_std__mapT_std__string_VtValue_std__lessT_t_t_p_std__mapT_std__string_VtValue_std__lessT_t_t__iterator_t() {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_VtDictionary__IteratorT_std__mapT_std__string_VtValue_std__lessT_t_t_p_std__mapT_std__string_VtValue_std__lessT_t_t__iterator_t obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
}
}
| 51.4 | 220 | 0.748379 | [
"Apache-2.0"
] | MrDice/usd-unity-sdk | src/USD.NET/generated/SWIG/SWIGTYPE_p_VtDictionary__IteratorT_std__mapT_std__string_VtValue_std__lessT_t_t_p_std__mapT_std__string_VtValue_std__lessT_t_t__iterator_t.cs | 1,542 | C# |
namespace TeamBuilder.Models
{
public class EventTeam
{
public int EventID { get; set; }
public Event Event { get; set; }
public int TeamId { get; set; }
public Team Team { get; set; }
}
}
| 19.583333 | 40 | 0.557447 | [
"MIT"
] | Javorov1103/SoftUni-Course | Databases Advanced - Entity Framework/14. Workshop - Team Builder/TeamBuilder.Models/EventTeam.cs | 237 | C# |
using System;
using System.Collections.Generic;
using ff14bot;
using ff14bot.Managers;
using LlamaLibrary.Memory.Attributes;
using NavigationTest.InclusionShop;
namespace LlamaLibrary.RemoteAgents
{
public class AgentInclusionShop : AgentInterface<AgentInclusionShop>, IAgent
{
internal static class Offsets
{
//0x
[Offset("Search 48 8D 05 ? ? ? ? 48 89 01 48 8D 05 ? ? ? ? 48 89 41 ? 48 8D 05 ? ? ? ? 48 89 41 ? E9 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 48 89 5C 24 ? Add 3 TraceRelative")]
internal static IntPtr Vtable;
//(__int64 AgentPointer, char Category)
[Offset("Search 48 8B 41 ? 4C 8B D1 80 88 ? ? ? ? ?")]
internal static IntPtr SetCategory;
//0x18
[Offset("Search 48 8B 49 ? 4C 89 74 24 ? 48 85 C9 Add 3 Read8")]
internal static int FirstPointer;
//0x10
[Offset("Search 48 8B 49 ? 49 8B C0 48 8B DA Add 3 Read8")]
internal static int SecondPointer;
//0x20
[Offset("41 8B 47 ? 48 C1 EB ? Add 3 Read8")]
[OffsetCN("Search 41 8B 46 ? 48 C1 EE ? Add 3 Read8")]
internal static int ShopKey;
//0x38
[Offset("48 8B 4F ? 89 81 ? ? ? ? 48 8B 47 ? C6 80 ? ? ? ? ? Add 3 Read8")]
internal static int PointerToStartOfShopThing;
//0x1177
[Offset("44 3A B0 ? ? ? ? 0F 82 ? ? ? ? 4C 8B 7C 24 ? Add 3 Read32")]
internal static int NumberOfCategories;
//0x1223
[Offset("40 38 B1 ? ? ? ? 0F 86 ? ? ? ? 66 66 0F 1F 84 00 ? ? ? ? Add 3 Read32")]
[OffsetCN("40 38 B1 ? ? ? ? 0F 86 ? ? ? ? 66 0F 1F 44 00 ? Add 3 Read32")]
internal static int NumberOfSubCategories;
//0x11A9
[Offset("41 0F B6 81 ? ? ? ? 48 69 D1 ? ? ? ? 48 69 C8 ? ? ? ? 41 0F B6 81 ? ? ? ? 4E 8B AC 0A ? ? ? ? Add 4 Read32")]
internal static int SubCategory;
//0x11A8
[Offset("41 0F B6 80 ? ? ? ? 42 0F B6 94 00 ? ? ? ? Add 4 Read32")]
internal static int Category;
//0x1158
[Offset("42 0F B6 8C 08 ? ? ? ? 41 0F B6 81 ? ? ? ? 48 69 D1 ? ? ? ? 48 69 C8 ? ? ? ? 41 0F B6 81 ? ? ? ? 4E 8B AC 0A ? ? ? ? Add 5 Read32")]
internal static int CategoryArray;
//0x1E0
[Offset("4E 8B AC 0A ? ? ? ? Add 4 Read32")]
internal static int SubCategoryArrayStart;
//0x88
[Offset("48 69 D1 ? ? ? ? 48 69 C8 ? ? ? ? 41 0F B6 81 ? ? ? ? 4E 8B AC 0A ? ? ? ? Add 3 Read8")]
internal static int StructSizeCategory;
//
[Offset("0F B6 98 ? ? ? ? E8 ? ? ? ? 80 7C 24 ? ? Add 3 Read32")]
internal static int ItemCount;
//0x19d0
[Offset("48 69 C8 ? ? ? ? 41 0F B6 81 ? ? ? ? 4E 8B AC 0A ? ? ? ? Add 3 Read32")]
internal static int StructSizeSubCategory;
//0x6C
[Offset("48 6B C8 ? 48 8B 47 ? 4C 03 E9 Add 3 Read8")]
internal static int StructSizeItem;
//0x175
[Offset("41 3A 81 ? ? ? ? 72 ? Add 3 Read32")]
internal static int CategorySubCount;
//0x19C9
[Offset("F6 84 0A ? ? ? ? ? 75 ? 49 8B 52 ? Add 3 Read32")]
internal static int SubCategoryEnabled;
}
public IntPtr RegisteredVtable => Offsets.Vtable;
public uint ShopKey => Core.Memory.Read<uint>(
Core.Memory.Read<IntPtr>(Core.Memory.Read<IntPtr>(Pointer + Offsets.FirstPointer)
+ Offsets.SecondPointer) + Offsets.ShopKey);
public IntPtr StartOfShopThing => Core.Memory.Read<IntPtr>(Pointer + Offsets.PointerToStartOfShopThing);
public byte NumberOfSubCategories => Core.Memory.Read<byte>(StartOfShopThing + Offsets.NumberOfSubCategories);
public byte SelectedCategory => Core.Memory.Read<byte>(StartOfShopThing + Offsets.Category);
public byte SelectedSubCategory => Core.Memory.Read<byte>(StartOfShopThing + Offsets.SubCategory);
public byte ItemCount => Core.Memory.Read<byte>(StartOfShopThing + Offsets.ItemCount);
public byte CategoryCount => Core.Memory.Read<byte>(StartOfShopThing + Offsets.NumberOfCategories);
public byte[] CategoryArray => Core.Memory.ReadArray<byte>(StartOfShopThing + Offsets.CategoryArray, CategoryCount);
public int TrueCategory => Core.Memory.Read<byte>(StartOfShopThing + Offsets.CategoryArray + SelectedCategory);
public IntPtr CategoryPtr => Core.Memory.Read<IntPtr>(StartOfShopThing +
(TrueCategory * Offsets.StructSizeCategory) +
Offsets.SubCategoryArrayStart);
public IntPtr CategoryPtrPtr => StartOfShopThing + (TrueCategory * Offsets.StructSizeCategory);
public IntPtr CategoryPtrPtrByIndex(int index) => StartOfShopThing +
(index * Offsets.StructSizeCategory);
public IntPtr CategoryPtrByIndex(int index) => Core.Memory.Read<IntPtr>(StartOfShopThing +
(index * Offsets.StructSizeCategory) +
Offsets.SubCategoryArrayStart);
public IntPtr SubCategoryPtr => CategoryPtr + (Offsets.StructSizeSubCategory * SelectedSubCategory) + Offsets.StructSizeCategory;
public IntPtr SubCategoryPtrByIndex(IntPtr categoryPtr, int sub) => categoryPtr + (Offsets.StructSizeSubCategory * sub);
public uint SubCategoryCost => Core.Memory.Read<uint>(CategoryPtr + (Offsets.StructSizeSubCategory * SelectedSubCategory) + Offsets.StructSizeItem);
public List<InclusionShopItem> ShopItems
{
get
{
var shopItems = new List<InclusionShopItem>();
foreach (var cat in Instance.CategoryArray)
{
var category = Instance.CategoryPtrByIndex(cat);
var categoryPtr = Instance.CategoryPtrPtrByIndex(cat);
var subCount = Core.Memory.Read<byte>(categoryPtr + Offsets.CategorySubCount);
for (byte i = 0; i < subCount; i++)
{
var subCategory = Instance.SubCategoryPtrByIndex(category, i);
var enabledByte =
Core.Memory.Read<byte>(subCategory + Offsets.SubCategoryEnabled);
int itemNum = 0;
InclusionShopItemStruct shopItemStruct;
do
{
var pointer = subCategory + Offsets.StructSizeCategory + (Offsets.StructSizeItem * itemNum);
shopItemStruct = Core.Memory.Read<InclusionShopItemStruct>(pointer);
if (shopItemStruct.ItemId == 0)
{
break;
}
shopItems.Add(new InclusionShopItem(shopItemStruct, cat, i, itemNum, (enabledByte & 1) == 1));
itemNum += shopItemStruct.NumberOfItems;
}
while (shopItemStruct.ItemId > 0);
}
}
return shopItems;
}
}
protected AgentInclusionShop(IntPtr pointer) : base(pointer)
{
}
}
} | 44.976608 | 179 | 0.534521 | [
"MIT"
] | nt153133/__LlamaLibrary | RemoteAgents/AgentInclusionShop.cs | 7,693 | C# |
using DeepCard.Client.SDK;
using DeepCard.Client.Server.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.IO;
using System.Linq;
namespace DeepCard.Client.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
ServerController.ApiServerUrl = Configuration["API_SERVER"];
RecognitionClient.BaseUrl = ServerController.ApiServerUrl;
services.AddHttpClient();
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
app.UseRouting();
app.UseClientSideBlazorFiles<Client.Startup>();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
});
}
}
}
| 33.671875 | 122 | 0.653828 | [
"Apache-2.0"
] | StardustDL/DeepCard | src/DeepCard.Client.Server/Startup.cs | 2,155 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using Ascend2018.Business;
using EPiServer.Web.Mvc.Html;
using EPiServer.Web.Routing;
using EPiServer;
namespace Ascend2018.Helpers
{
public static class HtmlHelpers
{
/// <summary>
/// Returns an element for each child page of the rootLink using the itemTemplate.
/// </summary>
/// <param name="helper">The html helper in whose context the list should be created</param>
/// <param name="rootLink">A reference to the root whose children should be listed</param>
/// <param name="itemTemplate">A template for each page which will be used to produce the return value. Can be either a delegate or a Razor helper.</param>
/// <param name="includeRoot">Wether an element for the root page should be returned</param>
/// <param name="requireVisibleInMenu">Wether pages that do not have the "Display in navigation" checkbox checked should be excluded</param>
/// <param name="requirePageTemplate">Wether page that do not have a template (i.e. container pages) should be excluded</param>
/// <remarks>
/// Filter by access rights and publication status.
/// </remarks>
public static IHtmlString MenuList(
this HtmlHelper helper,
ContentReference rootLink,
Func<MenuItem, HelperResult> itemTemplate = null,
bool includeRoot = false,
bool requireVisibleInMenu = true,
bool requirePageTemplate = true)
{
itemTemplate = itemTemplate ?? GetDefaultItemTemplate(helper);
var currentContentLink = helper.ViewContext.RequestContext.GetContentLink();
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
Func<IEnumerable<PageData>, IEnumerable<PageData>> filter =
pages => pages.FilterForDisplay(requirePageTemplate, requireVisibleInMenu);
var pagePath = contentLoader.GetAncestors(currentContentLink)
.Reverse()
.Select(x => x.ContentLink)
.SkipWhile(x => !x.CompareToIgnoreWorkID(rootLink))
.ToList();
var menuItems = contentLoader.GetChildren<PageData>(rootLink)
.FilterForDisplay(requirePageTemplate, requireVisibleInMenu)
.Select(x => CreateMenuItem(x, currentContentLink, pagePath, contentLoader, filter))
.ToList();
if(includeRoot)
{
menuItems.Insert(0, CreateMenuItem(contentLoader.Get<PageData>(rootLink), currentContentLink, pagePath, contentLoader, filter));
}
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
foreach (var menuItem in menuItems)
{
itemTemplate(menuItem).WriteTo(writer);
}
return new MvcHtmlString(buffer.ToString());
}
private static MenuItem CreateMenuItem(PageData page, ContentReference currentContentLink, List<ContentReference> pagePath, IContentLoader contentLoader, Func<IEnumerable<PageData>, IEnumerable<PageData>> filter)
{
var menuItem = new MenuItem(page)
{
Selected = page.ContentLink.CompareToIgnoreWorkID(currentContentLink) ||
pagePath.Contains(page.ContentLink),
HasChildren =
new Lazy<bool>(() => filter(contentLoader.GetChildren<PageData>(page.ContentLink)).Any())
};
return menuItem;
}
private static Func<MenuItem, HelperResult> GetDefaultItemTemplate(HtmlHelper helper)
{
return x => new HelperResult(writer => writer.Write(helper.PageLink(x.Page)));
}
public class MenuItem
{
public MenuItem(PageData page)
{
Page = page;
}
public PageData Page { get; set; }
public bool Selected { get; set; }
public Lazy<bool> HasChildren { get; set; }
}
/// <summary>
/// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true.
/// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag
/// to the response if the shouldWriteLink argument is true.
/// </summary>
public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink, IHtmlString url, string title = null, string cssClass = null)
{
if(shouldWriteLink)
{
var linkTag = new TagBuilder("a");
linkTag.Attributes.Add("href", url.ToHtmlString());
if(!string.IsNullOrWhiteSpace(title))
{
linkTag.Attributes.Add("title", helper.Encode(title));
}
if (!string.IsNullOrWhiteSpace(cssClass))
{
linkTag.Attributes.Add("class", cssClass);
}
helper.ViewContext.Writer.Write(linkTag.ToString(TagRenderMode.StartTag));
}
return new ConditionalLink(helper.ViewContext, shouldWriteLink);
}
/// <summary>
/// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true.
/// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag
/// to the response if the shouldWriteLink argument is true.
/// </summary>
/// <remarks>
/// Overload which only executes the delegate for retrieving the URL if the link should be written.
/// This may be used to prevent null reference exceptions by adding null checkes to the shouldWriteLink condition.
/// </remarks>
public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink, Func<IHtmlString> urlGetter, string title = null, string cssClass = null)
{
IHtmlString url = MvcHtmlString.Empty;
if(shouldWriteLink)
{
url = urlGetter();
}
return helper.BeginConditionalLink(shouldWriteLink, url, title, cssClass);
}
public class ConditionalLink : IDisposable
{
private readonly ViewContext _viewContext;
private readonly bool _linked;
private bool _disposed;
public ConditionalLink(ViewContext viewContext, bool isLinked)
{
_viewContext = viewContext;
_linked = isLinked;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (_linked)
{
_viewContext.Writer.Write("</a>");
}
}
}
}
}
| 40.254054 | 220 | 0.592319 | [
"Apache-2.0"
] | episerver/ascend2018-lab-extend-ui | Alloy/Ascend2018/Helpers/HtmlHelpers.cs | 7,447 | C# |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil.Matrices;
using System.Text;
using Encog.Util.KMeans;
namespace Encog.ML.Data.Specific
{
/// <summary>
/// A NeuralData implementation designed to work with bipolar data.
/// Bipolar data contains two values. True is stored as 1, and false
/// is stored as -1.
/// </summary>
[Serializable]
public class BiPolarMLData: IMLDataModifiable
{
/// <summary>
/// The data held by this object.
/// </summary>
private bool[] _data;
/// <summary>
/// Construct this object with the specified data.
/// </summary>
/// <param name="d">The data to create this object with.</param>
public BiPolarMLData(bool[] d) : this(d.Length)
{
for (int i = 0; i < d.Length; i++)
{
_data[i] = d[i];
}
}
/// <summary>
/// Construct a data object with the specified size.
/// </summary>
/// <param name="size">The size of this data object.</param>
public BiPolarMLData(int size)
{
_data = new bool[size];
}
/// <summary>
/// Allowes indexed access to the data.
/// </summary>
/// <param name="x">The index.</param>
/// <returns>The value at the specified index.</returns>
public double this[int x]
{
get { return BiPolarUtil.Bipolar2double(_data[x]); }
set { _data[x] = BiPolarUtil.Double2bipolar(value); }
}
/// <summary>
/// Get the data as an array.
/// </summary>
public double[] Data
{
get { return BiPolarUtil.Bipolar2double(_data); }
internal set { _data = BiPolarUtil.Double2bipolar(value); }
}
/// <summary>
/// The size of the array.
/// </summary>
public int Count
{
get { return _data.Length; }
}
/// <summary>
/// Get the specified data item as a boolean.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public bool GetBoolean(int i)
{
return _data[i];
}
/// <summary>
/// Clone this object.
/// </summary>
/// <returns>A clone of this object.</returns>
public virtual object Clone()
{
return new BiPolarMLData(_data);
}
/// <summary>
/// Set the value as a boolean.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="b">The boolean value.</param>
public void SetBoolean(int index, bool b)
{
_data[index] = b;
}
/// <summary>
/// Clear to false.
/// </summary>
public void Clear()
{
for (int i = 0; i < _data.Length; i++)
{
_data[i] = false;
}
}
/// <inheritdoc/>
public override String ToString()
{
var result = new StringBuilder();
result.Append('[');
for (var i = 0; i < Count; i++)
{
result.Append(this[i] > 0 ? "T" : "F");
if (i != Count - 1)
{
result.Append(",");
}
}
result.Append(']');
return (result.ToString());
}
/// <summary>
/// Not supported.
/// </summary>
/// <returns>Nothing.</returns>
public ICentroid<IMLData> CreateCentroid()
{
return null;
}
public void CopyTo(double[] target, int targetIndex, int count)
{
for(int i = 0; i < count; i++)
target[i + targetIndex] = _data[i] ? 1.0 : -1.0;
}
}
}
| 29.30303 | 76 | 0.501138 | [
"BSD-3-Clause"
] | asad4237/encog-dotnet-core | encog-core-cs/ML/Data/Specific/BiPolarMlData.cs | 4,835 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using myTask.Domain.Models;
using myTask.Helpers;
using myTask.Services.Navigation;
using myTask.Services.UserConfigManager;
using myTask.ViewModels.Base;
using myTask.Views;
using Neemacademy.CustomControls.Xam.Plugin.TabView;
using Xamarin.Forms;
using XF.Material.Forms.UI.Dialogs;
namespace myTask.ViewModels
{
public class SetWorkingHoursViewModel : BaseViewModel
{
private readonly IUserConfigManager _configManager;
private int[] _selectedIndices;
public override Type WiredPageType => typeof(InitWorkingHoursPage);
public ObservableCollection<DayTab> Days { get; set; }
public ICommand AddAssignmentsCommand { get; set; }
public ICommand GoBackCommand { get; set; }
public ICommand RefreshCommand { get; set; }
public SetWorkingHoursViewModel(INavigationService navigationService, IUserConfigManager configManager) : base(navigationService)
{
_configManager = configManager;
_navigationService = navigationService;
AddAssignmentsCommand = new Command(GoToAddPage);
GoBackCommand = new Command(GoBack);
RefreshCommand = new Command(Refresh);
}
private async void GoToAddPage()
{
await FinishSetup();
}
private async void GoBack()
{
await _navigationService.NavigateToAsync<SetWorkingDaysViewModel>();
await _navigationService.ClearTheStackAsync();
}
private async void Refresh()
{
Days = Days;
}
private async Task FinishSetup()
{
double[] workingHours = new double[7];
foreach (var index in _selectedIndices)
{
workingHours[index] = Days
.First(x => x.TabViewControlTabItemTitle == ((DayOfWeek) index).ToFriendlyString())
.NumberOfHours;
}
await _configManager.SetConfigAsync(new UserConfig()
{
WeeklyAvailableTimeInHours = workingHours,
IsInit = true
});
await _navigationService.InitMainNavigation();
}
public override async Task Init(object param)
{
if (param is List<int> daysIndices)
{
daysIndices.Sort();
var days = new List<DayTab>(daysIndices.Count);
foreach (var id in daysIndices)
{
days.Add(new DayTab()
{
TabViewControlTabItemTitle = ((DayOfWeek) id).ToFriendlyString(),
});
}
Days = new ObservableCollection<DayTab>(days);
_selectedIndices = daysIndices.ToArray();
OnPropertyChanged(nameof(Days));
}
}
public class DayTab : INotifyPropertyChanged, ITabViewControlTabItem
{
private string _tabViewControlTabItemTitle;
private int _numberOfHours = 1;
private ImageSource _tabViewControlTabItemIconSource;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void TabViewControlTabItemFocus()
{
}
public double NumberOfHours
{
get => _numberOfHours;
set
{
_numberOfHours = (int)Math.Round(value);
OnPropertyChanged(nameof(NumberOfHoursLabel));
}
}
public string NumberOfHoursLabel => $"{_numberOfHours} hour(s)";
public string TabViewControlTabItemTitle
{
get => _tabViewControlTabItemTitle;
set => _tabViewControlTabItemTitle = value;
}
public ImageSource TabViewControlTabItemIconSource { get; set; } = "icon.png";
}
}
} | 33.725191 | 137 | 0.594839 | [
"MIT"
] | SkymanOne/myTask | myTask/myTask/ViewModels/SetWorkingHoursViewModel.cs | 4,418 | C# |
using System;
using Earlz.LucidMVC;
using Moq;
using System.Web;
using Earlz.LucidMVC.Authentication;
using System.Collections.Generic;
using Earlz.LucidMVC.Authentication.Experimental;
namespace Earlz.LucidMVC.Tests.Extensions.ServerMocking
{
/// <summary>
/// Server mocking helper extensions
/// Prefix Keywords:
/// "Has" -- Will use mock.Verify and should be used after the call has taken place. These are past-tense
/// "Will" -- Uses mock.Setup and should be used before the call has taken place, followed by mock.Verify. These are future-tense
/// "Is" -- Uses mock.Setup to setup initial parameters for a scenario, but does not place anything verifiable into the mock. These are present-tense
/// "Get" -- Gets a captured piece of information from an earlier call. These are past-tense
/// "WillCapture" -- Uses mock.Setup to capture a piece of information that can later be retrieved using the matching "Get" method. these are future-tense
/// </summary>
public static class ServerMockingHelpers
{
public static Mock<IServerContext> IsNotLoggedIn(this Mock<IServerContext> mock)
{
mock.Setup(x=>x.GetHeaders("Authorization")).Returns<List<string>>(null);
mock.Setup(x=>x.GetItem("fscauth_currentuser")).Returns<UserData>(null);
mock.Setup(x=>x.GetCookie(It.IsAny<string>())).Returns<string>(null);
return mock;
}
public static Mock<IServerContext> HasLoggedIn(this Mock<IServerContext> mock, FSCAuth auth)
{
mock.Verify(x=>x.SetCookie(
It.Is<HttpCookie>(c=>
c.Name==auth.Config.SiteName+"_login" &&
c.Values["secret"].Length>0
)
));
return mock;
}
static HttpCookie logincookie=null;
public static HttpCookie LoginCookie
{
get
{
if(logincookie==null)
{
throw new ApplicationException("The login cookie has not been captured!");
}
return logincookie;
}
private set
{
logincookie=value;
}
}
public static Mock<IServerContext> WillCaptureLoginCookie(this Mock<IServerContext> mock)
{
LoginCookie=null;
mock.Setup(x=>x.SetCookie(
It.Is<HttpCookie>(c=>true) //don't care about the parameter specification
)).Callback<HttpCookie>(c=>LoginCookie=c);
return mock;
}
public static HttpCookie GetCapturedLoginCookie(this Mock<IServerContext> mock)
{
return LoginCookie;
}
public static Mock<IServerContext> WillNotBeKilled(this Mock<IServerContext> mock)
{
mock.Setup(x=>x.KillIt()).Throws(new ApplicationException("This should not be killed -- KillIt should not be called"));
return mock;
}
public static Mock<IServerContext> HasNotBeenKilled(this Mock<IServerContext> mock)
{
mock.Verify(x=>x.KillIt(), Times.Never());
return mock;
}
public static Mock<IServerContext> WillBeKilled(this Mock<IServerContext> mock)
{
mock.Setup(x=>x.KillIt()).Verifiable();
return mock;
}
public static Mock<IServerContext> HasBeenKilled(this Mock<IServerContext> mock)
{
mock.Verify(x=>x.KillIt());
return mock;
}
static Dictionary<string, object> Items=new Dictionary<string, object>();
public static Mock<IServerContext> IsUsingItems(this Mock<IServerContext> mock)
{
mock.Setup(x=>x.GetItem(It.IsAny<string>())).Returns<string>(k=>Items.ContainsKey(k) ? Items[k] : null);
mock.Setup(x=>x.SetItem(It.IsAny<string>(), It.IsAny<object>())).Returns<string, object>((k, v) => Items[k]=v); //this actually isn't a proper mock. Oh well
return mock;
}
public static void RemoveLoginItem(this Mock<IServerContext> mock)
{
Items.Remove("fscauth_currentuser");
}
}
}
| 34.295238 | 159 | 0.710081 | [
"BSD-3-Clause"
] | Earlz/lucidmvc | LucidMVC.Tests/utilities/ServerMockingExtensions.cs | 3,601 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.