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.Reflection;
namespace MVCServer.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 21.166667 | 52 | 0.748031 | [
"Apache-2.0"
] | Bigsby/PoC | Web/Certifying/Tests/MVCServer/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 254 | C# |
using System;
public class StartUp
{
static void Main()
{
try
{
double length = double.Parse(Console.ReadLine());
double width = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
Box box = new Box(length, width, height);
box.GetSurfaceArea();
box.GetLateralSurfaceArea();
box.GetVolume();
Console.WriteLine(box.ToString());
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
| 23.307692 | 61 | 0.533003 | [
"MIT"
] | inser788/CSharp-Fundamentals-OOP-Basics | Exercises/08 ENCAPSULATION - EXERCISES/Encapsulation-Exercises/01_Class_Box/StartUp.cs | 608 | C# |
using Phloem.ViewModels;
using System;
using System.Windows.Threading;
using System.Windows;
using Microsoft.Win32;
namespace Phloem
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
/// <summary>
/// This is the ViewModel of this view. It is only used to set the DataContext
/// </summary>
private readonly GameViewModel GameViewModel = new();
/// <summary>
/// This timer will jump to the next generation at a given interval.
/// </summary>
// TODO[baptiste]: Timer belongs to the view or viewmodel? Both seems
// acceptable.
private readonly DispatcherTimer Timer = new();
/// <summary>
/// Gets if the game is paused or not.
/// </summary>
private bool IsPaused = true;
public MainWindow()
{
InitializeComponent();
DataContext = GameViewModel;
Timer.Interval = TimeSpan.FromMilliseconds((int)IntervalSlider.Value);
Timer.Tick += TimerTick;
}
/// <summary>
/// Method called by the timer at a given interval.
/// </summary>
private void TimerTick(object? sender, EventArgs e)
{
// TODO[baptiste]: Can I pass a timer events to the ViewModel with
// an ICommand?
GameViewModel.Next(null!);
}
/// <summary>
/// Method called by the import button.
/// </summary>
private void ImportClick(object sender, RoutedEventArgs e)
{
OpenFileDialog browser = new()
{
FileName = "Select a text file",
Filter = "Text files (*.txt)|*.txt",
Title = "Open text file"
};
if (browser.ShowDialog() == true)
{
bool error = GameViewModel.Import(browser.FileName);
if (error)
{
MessageBox.Show("The config file is incorrect", "Error", MessageBoxButton.OK);
}
}
}
/// <summary>
/// Method called by the reset button.
/// </summary>
private void ResetClick(object sender, RoutedEventArgs e)
{
if (!IsPaused)
{
Pause();
}
}
/// <summary>
/// Method called by the pause button.
/// </summary>
private void PauseClick(object sender, System.Windows.RoutedEventArgs e)
{
if (IsPaused)
{
Resume();
}
else
{
Pause();
}
}
/// <summary>
/// Method called by the next button.
/// </summary>
private void NextClick(object sender, System.Windows.RoutedEventArgs e)
{
if (!IsPaused)
{
Pause();
}
}
/// <summary>
/// Method called by the next10 button.
/// </summary>
private void Next10Click(object sender, System.Windows.RoutedEventArgs e)
{
if (!IsPaused)
{
Pause();
}
}
/// <summary>
/// Pause the game.
/// </summary>
private void Pause()
{
Timer.Stop();
PauseButton.Content = "Play";
IsPaused = true;
}
/// <summary>
/// Resume the game.
/// </summary>
private void Resume()
{
Timer.Start();
PauseButton.Content = "Pause";
IsPaused = false;
}
/// <summary>
/// method called by the slider.
/// </summary>
private void SliderChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
var interval = (int)IntervalSlider.Value;
GameViewModel.IntervalNumber = interval;
Timer.Interval = TimeSpan.FromMilliseconds(interval);
}
}
}
| 27.758389 | 106 | 0.49323 | [
"MIT"
] | MokkaCicc/Phloem | Phloem/MainWindow.xaml.cs | 4,138 | C# |
namespace ClearHl7.Codes.V270
{
/// <summary>
/// HL7 Version 2 Table 0146 - Amount Type.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0146</remarks>
public enum CodeAmountType
{
/// <summary>
/// DF - Differential.
/// </summary>
Differential,
/// <summary>
/// LM - Limit.
/// </summary>
Limit,
/// <summary>
/// PC - Percentage.
/// </summary>
Percentage,
/// <summary>
/// RT - Rate.
/// </summary>
Rate,
/// <summary>
/// UL - Unlimited.
/// </summary>
Unlimited
}
} | 20.794118 | 59 | 0.413013 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V270/CodeAmountType.cs | 709 | C# |
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("WpfMessenger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WpfMessenger")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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")]
| 39.535714 | 94 | 0.760163 | [
"MIT"
] | bpe78/WpfExamples | src/WpfMessenger/WpfMessenger/Properties/AssemblyInfo.cs | 2,217 | C# |
// Copyright (c) DNN Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Dnn.DynamicContent;
using Moq;
using NUnit.Framework;
namespace Dnn.Tests.DynamicContent.UnitTests
{
[TestFixture]
class ValidationRuleTests
{
[Test]
public void Constructor_Sets_Default_Properties()
{
//Arrange
//Act
var rule = new ValidationRule();
//Assert
Assert.AreEqual(-1, rule.ValidatorTypeId);
Assert.AreEqual(-1, rule.ValidationRuleId);
Assert.AreEqual(-1, rule.FieldDefinitionId);
}
[Test]
public void Constructor_Instantiates_Settings_Collection()
{
//Arrange
//Act
var rule = new ValidationRule();
//Assert
Assert.AreEqual(0, rule.ValidationSettings.Count);
}
[Test]
public void ValidatorType_Property_Calls_ValidatorTypeController_Get()
{
//Arrange
var rule = new ValidationRule();
var mockValidatorTypeController = new Mock<IValidatorTypeManager>();
ValidatorTypeManager.SetTestableInstance(mockValidatorTypeController.Object);
//Act
// ReSharper disable once UnusedVariable
var validatorType = rule.ValidatorType;
//Assert
mockValidatorTypeController.Verify(c => c.GetValidatorTypes(), Times.Once);
}
[Test]
public void ValidatorType_Property_Calls_ValidatorTypeController_Get_Once_Only()
{
//Arrange
var validatorTypeId = 2;
var rule = new ValidationRule() { ValidatorTypeId = validatorTypeId };
var mockValidatorTypeController = new Mock<IValidatorTypeManager>();
mockValidatorTypeController.Setup(dt => dt.GetValidatorTypes())
.Returns(new List<ValidatorType>() { new ValidatorType() { ValidatorTypeId = validatorTypeId } }.AsQueryable());
ValidatorTypeManager.SetTestableInstance(mockValidatorTypeController.Object);
//Act
// ReSharper disable UnusedVariable
var validatorType = rule.ValidatorType;
var validatorType1 = rule.ValidatorType;
var validatorType2 = rule.ValidatorType;
// ReSharper restore UnusedVariable
//Assert
mockValidatorTypeController.Verify(c => c.GetValidatorTypes(), Times.AtMostOnce);
}
}
}
| 32.493827 | 128 | 0.625 | [
"MIT"
] | 51Degrees/Dnn.Platform | DNN Platform/Tests/Dnn.Tests.DynamicContent.UnitTests/ValidationRuleTests.cs | 2,634 | C# |
using System.Collections.Generic;
namespace essentialMix.Data.Patterns.Parameters;
public struct GetSettings : IGetSettings, IIncludeSettings, IFilterSettings
{
/// <inheritdoc />
public GetSettings(params object[] keys)
: this()
{
KeyValue = keys;
}
/// <inheritdoc />
public object[] KeyValue { get; set; }
/// <inheritdoc />
public IList<string> Include { get; set; }
/// <inheritdoc />
public string FilterExpression { get; set; }
} | 20.727273 | 75 | 0.695175 | [
"MIT"
] | asm2025/essentialMix | Standard/essentialMix.Data/Patterns/Parameters/GetSettings.cs | 458 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TO8CHTX_GraceNote
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Usage: TO8CHTX_GraceNote ChatFilename NewDBFilename GracesJapanese");
return;
}
String Filename = args[0];
String NewDB = args[1];
String GracesDB = args[2];
ChatFile c = new ChatFile(System.IO.File.ReadAllBytes(Filename));
System.IO.File.Copy("VTemplate", NewDB, true);
c.InsertSQL("Data Source=" + NewDB, "Data Source=" + GracesDB);
return;
}
}
}
| 24.290323 | 104 | 0.553785 | [
"MIT"
] | AdmiralCurtiss/ToVPatcher | Scripts/tools/TO8CHTX_GraceNote/TO8CHTX_GraceNote/Program.cs | 755 | C# |
using System;
using System.Collections.Generic;
using Avalonia.Media.TextFormatting.Unicode;
using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting
{
internal class TextLineImpl : TextLine
{
private static readonly Comparer<int> s_compareStart = Comparer<int>.Default;
private static readonly Comparison<ShapedTextCharacters> s_compareLogicalOrder =
(a, b) => s_compareStart.Compare(a.Text.Start, b.Text.Start);
private readonly List<ShapedTextCharacters> _textRuns;
private readonly double _paragraphWidth;
private readonly TextParagraphProperties _paragraphProperties;
private TextLineMetrics _textLineMetrics;
private readonly FlowDirection _flowDirection;
public TextLineImpl(List<ShapedTextCharacters> textRuns, TextRange textRange, double paragraphWidth,
TextParagraphProperties paragraphProperties, FlowDirection flowDirection = FlowDirection.LeftToRight,
TextLineBreak? lineBreak = null, bool hasCollapsed = false)
{
TextRange = textRange;
TextLineBreak = lineBreak;
HasCollapsed = hasCollapsed;
_textRuns = textRuns;
_paragraphWidth = paragraphWidth;
_paragraphProperties = paragraphProperties;
_flowDirection = flowDirection;
}
/// <inheritdoc/>
public override IReadOnlyList<TextRun> TextRuns => _textRuns;
/// <inheritdoc/>
public override TextRange TextRange { get; }
/// <inheritdoc/>
public override TextLineBreak? TextLineBreak { get; }
/// <inheritdoc/>
public override bool HasCollapsed { get; }
/// <inheritdoc/>
public override bool HasOverflowed => _textLineMetrics.HasOverflowed;
/// <inheritdoc/>
public override double Baseline => _textLineMetrics.TextBaseline;
/// <inheritdoc/>
public override double Extent => _textLineMetrics.Height;
/// <inheritdoc/>
public override double Height => _textLineMetrics.Height;
/// <inheritdoc/>
public override int NewLineLength => _textLineMetrics.NewLineLength;
/// <inheritdoc/>
public override double OverhangAfter => 0;
/// <inheritdoc/>
public override double OverhangLeading => 0;
/// <inheritdoc/>
public override double OverhangTrailing => 0;
/// <inheritdoc/>
public override int TrailingWhitespaceLength => _textLineMetrics.TrailingWhitespaceLength;
/// <inheritdoc/>
public override double Start => _textLineMetrics.Start;
/// <inheritdoc/>
public override double Width => _textLineMetrics.Width;
/// <inheritdoc/>
public override double WidthIncludingTrailingWhitespace => _textLineMetrics.WidthIncludingTrailingWhitespace;
/// <inheritdoc/>
public override void Draw(DrawingContext drawingContext, Point lineOrigin)
{
var (currentX, currentY) = lineOrigin;
foreach (var textRun in _textRuns)
{
var offsetY = Baseline - textRun.GlyphRun.BaselineOrigin.Y;
textRun.Draw(drawingContext, new Point(currentX, currentY + offsetY));
currentX += textRun.Size.Width;
}
}
/// <inheritdoc/>
public override TextLine Collapse(params TextCollapsingProperties[] collapsingPropertiesList)
{
if (collapsingPropertiesList.Length == 0)
{
return this;
}
var collapsingProperties = collapsingPropertiesList[0];
var collapsedRuns = collapsingProperties.Collapse(this);
if (collapsedRuns is List<ShapedTextCharacters> shapedRuns)
{
var collapsedLine = new TextLineImpl(shapedRuns, TextRange, _paragraphWidth, _paragraphProperties, _flowDirection, TextLineBreak, true);
if (shapedRuns.Count > 0)
{
collapsedLine.FinalizeLine();
}
return collapsedLine;
}
return this;
}
/// <inheritdoc/>
public override CharacterHit GetCharacterHitFromDistance(double distance)
{
distance -= Start;
if (distance <= 0)
{
// hit happens before the line, return the first position
var firstRun = _textRuns[0];
return firstRun.GlyphRun.GetCharacterHitFromDistance(distance, out _);
}
// process hit that happens within the line
var characterHit = new CharacterHit();
foreach (var run in _textRuns)
{
characterHit = run.GlyphRun.GetCharacterHitFromDistance(distance, out _);
if (distance <= run.Size.Width)
{
break;
}
distance -= run.Size.Width;
}
return characterHit;
}
/// <inheritdoc/>
public override double GetDistanceFromCharacterHit(CharacterHit characterHit)
{
var characterIndex = characterHit.FirstCharacterIndex + (characterHit.TrailingLength != 0 ? 1 : 0);
var currentDistance = Start;
GlyphRun? lastRun = null;
for (var index = 0; index < _textRuns.Count; index++)
{
var textRun = _textRuns[index];
var currentRun = textRun.GlyphRun;
if (lastRun != null)
{
if (!lastRun.IsLeftToRight && currentRun.IsLeftToRight &&
currentRun.Characters.Start == characterHit.FirstCharacterIndex &&
characterHit.TrailingLength == 0)
{
return currentDistance;
}
}
//Look for a hit in within the current run
if (characterIndex >= textRun.Text.Start && characterIndex <= textRun.Text.End)
{
var distance = currentRun.GetDistanceFromCharacterHit(characterHit);
return currentDistance + distance;
}
//Look at the left and right edge of the current run
if (currentRun.IsLeftToRight)
{
if (lastRun == null || lastRun.IsLeftToRight)
{
if (characterIndex <= textRun.Text.Start)
{
return currentDistance;
}
}
else
{
if (characterIndex == textRun.Text.Start)
{
return currentDistance;
}
}
if (characterIndex == textRun.Text.Start + textRun.Text.Length && characterHit.TrailingLength > 0)
{
return currentDistance + currentRun.Size.Width;
}
}
else
{
if (characterIndex == textRun.Text.Start)
{
return currentDistance + currentRun.Size.Width;
}
var nextRun = index + 1 < _textRuns.Count ? _textRuns[index + 1] : null;
if (nextRun != null)
{
if (characterHit.FirstCharacterIndex == textRun.Text.End && nextRun.ShapedBuffer.IsLeftToRight)
{
return currentDistance;
}
if (characterIndex > textRun.Text.End && nextRun.Text.End < textRun.Text.End)
{
return currentDistance;
}
}
else
{
if (characterIndex > textRun.Text.End)
{
return currentDistance;
}
}
}
//No hit hit found so we add the full width
currentDistance += currentRun.Size.Width;
lastRun = currentRun;
}
return currentDistance;
}
/// <inheritdoc/>
public override CharacterHit GetNextCaretCharacterHit(CharacterHit characterHit)
{
if (TryFindNextCharacterHit(characterHit, out var nextCharacterHit))
{
return nextCharacterHit;
}
// Can't move, we're after the last character
var runIndex = GetRunIndexAtCharacterIndex(TextRange.End, LogicalDirection.Forward);
var textRun = _textRuns[runIndex];
characterHit = textRun.GlyphRun.GetNextCaretCharacterHit(characterHit);
return characterHit;
}
/// <inheritdoc/>
public override CharacterHit GetPreviousCaretCharacterHit(CharacterHit characterHit)
{
if (TryFindPreviousCharacterHit(characterHit, out var previousCharacterHit))
{
return previousCharacterHit;
}
if (characterHit.FirstCharacterIndex <= TextRange.Start)
{
characterHit = new CharacterHit(TextRange.Start);
}
return characterHit; // Can't move, we're before the first character
}
/// <inheritdoc/>
public override CharacterHit GetBackspaceCaretCharacterHit(CharacterHit characterHit)
{
// same operation as move-to-previous
return GetPreviousCaretCharacterHit(characterHit);
}
public static void SortRuns(List<ShapedTextCharacters> textRuns)
{
textRuns.Sort(s_compareLogicalOrder);
}
public TextLineImpl FinalizeLine()
{
BidiReorder();
_textLineMetrics = CreateLineMetrics();
return this;
}
private void BidiReorder()
{
// Build up the collection of ordered runs.
var run = _textRuns[0];
OrderedBidiRun orderedRun = new(run);
var current = orderedRun;
for (var i = 1; i < _textRuns.Count; i++)
{
run = _textRuns[i];
current.Next = new OrderedBidiRun(run);
current = current.Next;
}
// Reorder them into visual order.
orderedRun = LinearReOrder(orderedRun);
// Now perform a recursive reversal of each run.
// From the highest level found in the text to the lowest odd level on each line, including intermediate levels
// not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
// https://unicode.org/reports/tr9/#L2
sbyte max = 0;
var min = sbyte.MaxValue;
for (var i = 0; i < _textRuns.Count; i++)
{
var level = _textRuns[i].BidiLevel;
if (level > max)
{
max = level;
}
if ((level & 1) != 0 && level < min)
{
min = level;
}
}
if (min > max)
{
min = max;
}
if (max == 0 || (min == max && (max & 1) == 0))
{
// Nothing to reverse.
return;
}
// Now apply the reversal and replace the original contents.
var minLevelToReverse = max;
while (minLevelToReverse >= min)
{
current = orderedRun;
while (current != null)
{
if (current.Level >= minLevelToReverse && current.Level % 2 != 0)
{
if (!current.Run.IsReversed)
{
current.Run.Reverse();
}
}
current = current.Next;
}
minLevelToReverse--;
}
_textRuns.Clear();
current = orderedRun;
while (current != null)
{
_textRuns.Add(current.Run);
current = current.Next;
}
}
/// <summary>
/// Reorders a series of runs from logical to visual order, returning the left most run.
/// <see href="https://github.com/fribidi/linear-reorder/blob/f2f872257d4d8b8e137fcf831f254d6d4db79d3c/linear-reorder.c"/>
/// </summary>
/// <param name="run">The ordered bidi run.</param>
/// <returns>The <see cref="OrderedBidiRun"/>.</returns>
private static OrderedBidiRun LinearReOrder(OrderedBidiRun? run)
{
BidiRange? range = null;
while (run != null)
{
var next = run.Next;
while (range != null && range.Level > run.Level
&& range.Previous != null && range.Previous.Level >= run.Level)
{
range = BidiRange.MergeWithPrevious(range);
}
if (range != null && range.Level >= run.Level)
{
// Attach run to the range.
if ((run.Level & 1) != 0)
{
// Odd, range goes to the right of run.
run.Next = range.Left;
range.Left = run;
}
else
{
// Even, range goes to the left of run.
range.Right!.Next = run;
range.Right = run;
}
range.Level = run.Level;
}
else
{
var r = new BidiRange();
r.Left = r.Right = run;
r.Level = run.Level;
r.Previous = range;
range = r;
}
run = next;
}
while (range?.Previous != null)
{
range = BidiRange.MergeWithPrevious(range);
}
// Terminate.
range!.Right!.Next = null;
return range.Left!;
}
/// <summary>
/// Tries to find the next character hit.
/// </summary>
/// <param name="characterHit">The current character hit.</param>
/// <param name="nextCharacterHit">The next character hit.</param>
/// <returns></returns>
private bool TryFindNextCharacterHit(CharacterHit characterHit, out CharacterHit nextCharacterHit)
{
nextCharacterHit = characterHit;
var codepointIndex = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
if (codepointIndex >= TextRange.End)
{
return false; // Cannot go forward anymore
}
if (codepointIndex < TextRange.Start)
{
codepointIndex = TextRange.Start;
}
var runIndex = GetRunIndexAtCharacterIndex(codepointIndex, LogicalDirection.Forward);
while (runIndex < _textRuns.Count)
{
var run = _textRuns[runIndex];
var foundCharacterHit =
run.GlyphRun.FindNearestCharacterHit(characterHit.FirstCharacterIndex + characterHit.TrailingLength,
out _);
var isAtEnd = foundCharacterHit.FirstCharacterIndex + foundCharacterHit.TrailingLength ==
TextRange.Start + TextRange.Length;
if (isAtEnd && !run.GlyphRun.IsLeftToRight)
{
nextCharacterHit = foundCharacterHit;
return true;
}
var characterIndex = codepointIndex - run.Text.Start;
if (characterIndex < 0 && run.ShapedBuffer.IsLeftToRight)
{
foundCharacterHit = new CharacterHit(foundCharacterHit.FirstCharacterIndex);
}
nextCharacterHit = isAtEnd || characterHit.TrailingLength != 0 ?
foundCharacterHit :
new CharacterHit(foundCharacterHit.FirstCharacterIndex + foundCharacterHit.TrailingLength);
if (isAtEnd || nextCharacterHit.FirstCharacterIndex > characterHit.FirstCharacterIndex)
{
return true;
}
runIndex++;
}
return false;
}
/// <summary>
/// Tries to find the previous character hit.
/// </summary>
/// <param name="characterHit">The current character hit.</param>
/// <param name="previousCharacterHit">The previous character hit.</param>
/// <returns></returns>
private bool TryFindPreviousCharacterHit(CharacterHit characterHit, out CharacterHit previousCharacterHit)
{
var characterIndex = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
if (characterIndex == TextRange.Start)
{
previousCharacterHit = new CharacterHit(TextRange.Start);
return true;
}
previousCharacterHit = characterHit;
if (characterIndex < TextRange.Start)
{
return false; // Cannot go backward anymore.
}
var runIndex = GetRunIndexAtCharacterIndex(characterIndex, LogicalDirection.Backward);
while (runIndex >= 0)
{
var run = _textRuns[runIndex];
var foundCharacterHit =
run.GlyphRun.FindNearestCharacterHit(characterHit.FirstCharacterIndex - 1, out _);
if (foundCharacterHit.FirstCharacterIndex + foundCharacterHit.TrailingLength < characterIndex)
{
previousCharacterHit = foundCharacterHit;
return true;
}
previousCharacterHit = characterHit.TrailingLength != 0 ?
foundCharacterHit :
new CharacterHit(foundCharacterHit.FirstCharacterIndex);
if (previousCharacterHit != characterHit)
{
return true;
}
runIndex--;
}
return false;
}
/// <summary>
/// Gets the run index of the specified codepoint index.
/// </summary>
/// <param name="codepointIndex">The codepoint index.</param>
/// <param name="direction">The logical direction.</param>
/// <returns>The text run index.</returns>
private int GetRunIndexAtCharacterIndex(int codepointIndex, LogicalDirection direction)
{
var runIndex = 0;
ShapedTextCharacters? previousRun = null;
while (runIndex < _textRuns.Count)
{
var currentRun = _textRuns[runIndex];
if (previousRun != null && !previousRun.ShapedBuffer.IsLeftToRight)
{
if (currentRun.ShapedBuffer.IsLeftToRight)
{
if (currentRun.Text.Start >= codepointIndex)
{
return --runIndex;
}
}
else
{
if (codepointIndex > currentRun.Text.Start + currentRun.Text.Length)
{
return --runIndex;
}
}
}
if (direction == LogicalDirection.Forward)
{
if (codepointIndex >= currentRun.Text.Start && codepointIndex <= currentRun.Text.End)
{
return runIndex;
}
}
else
{
if (codepointIndex > currentRun.Text.Start &&
codepointIndex <= currentRun.Text.Start + currentRun.Text.Length)
{
return runIndex;
}
}
if (runIndex + 1 < _textRuns.Count)
{
runIndex++;
previousRun = currentRun;
}
else
{
break;
}
}
return runIndex;
}
private TextLineMetrics CreateLineMetrics()
{
var width = 0d;
var widthIncludingWhitespace = 0d;
var trailingWhitespaceLength = 0;
var newLineLength = 0;
var ascent = 0d;
var descent = 0d;
var lineGap = 0d;
var fontRenderingEmSize = 0d;
for (var index = 0; index < _textRuns.Count; index++)
{
var textRun = _textRuns[index];
var fontMetrics =
new FontMetrics(textRun.Properties.Typeface, textRun.Properties.FontRenderingEmSize);
if (fontRenderingEmSize < textRun.Properties.FontRenderingEmSize)
{
fontRenderingEmSize = textRun.Properties.FontRenderingEmSize;
if (ascent > fontMetrics.Ascent)
{
ascent = fontMetrics.Ascent;
}
if (descent < fontMetrics.Descent)
{
descent = fontMetrics.Descent;
}
if (lineGap < fontMetrics.LineGap)
{
lineGap = fontMetrics.LineGap;
}
}
switch (_paragraphProperties.FlowDirection)
{
case FlowDirection.LeftToRight:
{
if (index == _textRuns.Count - 1)
{
width = widthIncludingWhitespace + textRun.GlyphRun.Metrics.Width;
trailingWhitespaceLength = textRun.GlyphRun.Metrics.TrailingWhitespaceLength;
newLineLength = textRun.GlyphRun.Metrics.NewlineLength;
}
break;
}
case FlowDirection.RightToLeft:
{
if (index == _textRuns.Count - 1)
{
var firstRun = _textRuns[0];
var offset = firstRun.GlyphRun.Metrics.WidthIncludingTrailingWhitespace -
firstRun.GlyphRun.Metrics.Width;
width = widthIncludingWhitespace +
textRun.GlyphRun.Metrics.WidthIncludingTrailingWhitespace - offset;
trailingWhitespaceLength = firstRun.GlyphRun.Metrics.TrailingWhitespaceLength;
newLineLength = firstRun.GlyphRun.Metrics.NewlineLength;
}
break;
}
}
widthIncludingWhitespace += textRun.GlyphRun.Metrics.WidthIncludingTrailingWhitespace;
}
var start = GetParagraphOffsetX(width, widthIncludingWhitespace, _paragraphWidth,
_paragraphProperties.TextAlignment, _paragraphProperties.FlowDirection);
var lineHeight = _paragraphProperties.LineHeight;
var height = double.IsNaN(lineHeight) || MathUtilities.IsZero(lineHeight) ?
descent - ascent + lineGap :
lineHeight;
return new TextLineMetrics(widthIncludingWhitespace > _paragraphWidth, height, newLineLength, start,
-ascent, trailingWhitespaceLength, width, widthIncludingWhitespace);
}
private sealed class OrderedBidiRun
{
public OrderedBidiRun(ShapedTextCharacters run) => Run = run;
public sbyte Level => Run.BidiLevel;
public ShapedTextCharacters Run { get; }
public OrderedBidiRun? Next { get; set; }
public void Reverse() => Run.ShapedBuffer.GlyphInfos.Span.Reverse();
}
private sealed class BidiRange
{
public int Level { get; set; }
public OrderedBidiRun? Left { get; set; }
public OrderedBidiRun? Right { get; set; }
public BidiRange? Previous { get; set; }
public static BidiRange MergeWithPrevious(BidiRange range)
{
var previous = range.Previous;
BidiRange left;
BidiRange right;
if ((previous!.Level & 1) != 0)
{
// Odd, previous goes to the right of range.
left = range;
right = previous;
}
else
{
// Even, previous goes to the left of range.
left = previous;
right = range;
}
// Stitch them
left.Right!.Next = right.Left;
previous.Left = left.Left;
previous.Right = right.Right;
return previous;
}
}
}
}
| 33.709884 | 152 | 0.49722 | [
"MIT"
] | AndrejBunjac/Avalonia | src/Avalonia.Visuals/Media/TextFormatting/TextLineImpl.cs | 26,262 | C# |
namespace AbstractFactory
{
public class Vodka : Alcohol
{
private readonly string madeBy;
public Vodka(int percentage, Flavor flavor, string madeby)
: base(percentage, flavor)
{
this.madeBy = madeby;
}
protected override string Name
{
get
{
return string.Format("Vodka made by {0}", this.madeBy);
}
}
}
}
| 20.636364 | 71 | 0.502203 | [
"MIT"
] | bstaykov/Telerik-High-Quality-Code | CreationalPatterns/AbstractFactory/Vodka.cs | 456 | C# |
/* ****************************************************************************
*
* BRIEF //
*
* In this exercise, you'll create a Student class to replace the student
* Dictionary.
*
* First, fill out Student.cs. Then come back to this file!
*
* ****************************************************************************
*
* There's a new function in Helpers.cs, called `PromptForAttribute (string attribute)`.
* It takes the name of an attribute, which will be displayed to the user, and
* returns what they enter in response.
*
* For example, you can do:
*
* string firstName = PromptForAttribute("first name");
*
* This will write to the console with:
*
* "Please enter the student's first name."
*
* ...And store the user's response in the `firstName` variable.
*
* Do this for every attribute you set on your Student, and use the user's input to
* set their values appropriately.
*
* ****************************************************************************
*
* When you're done, use the script we've provided to compile Program.cs. Just
* run the following command:
*
* bash compile
*
* If you're using Visual Studio, you don't need to do this-just use the IDE.
*
***************************************************************************** */
using System;
using System.Collections.Generic;
namespace Students
{
class Program
{
static void Main (String[] args)
{
while (true) {
Dictionary<string, string> student = new Dictionary<string, string>();
// An example of a good use case for arrays over array lists.
string[] attributes = new string[] { "first name", "last name", "middle name",
"address", "email", "phone number" };
foreach (string attribute in attributes)
{
Helpers.SaveAttribute(attribute, student);
}
Helpers.PrintEntries(student);
if (Helpers.Confirm())
break;
}
}
}
}
| 27.638889 | 89 | 0.537688 | [
"MIT"
] | nickoliasxii/Class-Activities | Week-21/04-Classes-and-Objects/Unsolved/Program.cs | 1,990 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PlaywrightSharp.Helpers
{
/// <summary>
/// Task helper.
/// </summary>
internal static class TaskHelper
{
private static readonly Func<TimeSpan, Exception> _defaultExceptionFactory =
timeout => new TimeoutException($"Timeout of {timeout.TotalMilliseconds}ms exceeded");
// Recipe from https://blogs.msdn.microsoft.com/pfxteam/2012/10/05/how-do-i-cancel-non-cancelable-async-operations/
/// <summary>
/// Cancels the <paramref name="task"/> after <paramref name="milliseconds"/> milliseconds.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="milliseconds">Milliseconds timeout.</param>
/// <param name="exceptionFactory">Optional timeout exception factory.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Task WithTimeout(
this Task task,
int milliseconds = 1_000,
Func<TimeSpan, Exception> exceptionFactory = null,
CancellationToken cancellationToken = default)
=> WithTimeout(task, TimeSpan.FromMilliseconds(milliseconds), exceptionFactory, cancellationToken);
/// <summary>
/// Cancels the <paramref name="task"/> after a given <paramref name="timeout"/> period.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeout">The timeout period.</param>
/// <param name="exceptionFactory">Optional timeout exception factory.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Task WithTimeout(
this Task task,
TimeSpan timeout,
Func<TimeSpan, Exception> exceptionFactory = null,
CancellationToken cancellationToken = default)
=> task.WithTimeout(
() => throw (exceptionFactory ?? _defaultExceptionFactory)(timeout),
timeout,
cancellationToken);
/// <summary>
/// Cancels the <paramref name="task"/> after <paramref name="timeout"/> milliseconds.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeoutAction">Action to be executed on Timeout.</param>
/// <param name="timeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Task WithTimeout(
this Task task,
Func<Task> timeoutAction,
int timeout = 1_000,
CancellationToken cancellationToken = default)
=> WithTimeout(task, timeoutAction, TimeSpan.FromMilliseconds(timeout), cancellationToken);
/// <summary>
/// Cancels the <paramref name="task"/> after a given <paramref name="timeout"/> period.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeoutAction">Action to be executed on Timeout.</param>
/// <param name="timeout">The timeout period.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static async Task WithTimeout(this Task task, Func<Task> timeoutAction, TimeSpan timeout, CancellationToken cancellationToken)
{
if (await TimeoutTask(task, timeout).ConfigureAwait(false) && !cancellationToken.IsCancellationRequested)
{
await timeoutAction().ConfigureAwait(false);
}
await task.ConfigureAwait(false);
}
/// <summary>
/// Cancels the <paramref name="task"/> after <paramref name="timeout"/> milliseconds.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeoutAction">Action to be executed on Timeout.</param>
/// <param name="timeout">Milliseconds timeout.</param>
/// <typeparam name="T">Return type.</typeparam>
public static Task<T> WithTimeout<T>(this Task<T> task, Action timeoutAction, int timeout = 1_000)
=> WithTimeout(task, timeoutAction, TimeSpan.FromMilliseconds(timeout));
/// <summary>
/// Cancels the <paramref name="task"/> after a given <paramref name="timeout"/> period.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeoutAction">Action to be executed on Timeout.</param>
/// <param name="timeout">The timeout period.</param>
/// <typeparam name="T">Return type.</typeparam>
public static async Task<T> WithTimeout<T>(this Task<T> task, Action timeoutAction, TimeSpan timeout)
{
if (await TimeoutTask(task, timeout).ConfigureAwait(false))
{
timeoutAction();
return default;
}
return await task.ConfigureAwait(false);
}
/// <summary>
/// Cancels the <paramref name="task"/> after <paramref name="milliseconds"/> milliseconds.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="milliseconds">Milliseconds timeout.</param>
/// <param name="exceptionFactory">Optional timeout exception factory.</param>
/// <typeparam name="T">Task return type.</typeparam>
public static Task<T> WithTimeout<T>(this Task<T> task, int milliseconds = 1_000, Func<TimeSpan, Exception> exceptionFactory = null)
=> WithTimeout(task, TimeSpan.FromMilliseconds(milliseconds), exceptionFactory);
/// <summary>
/// Cancels the <paramref name="task"/> after a given <paramref name="timeout"/> period.
/// </summary>
/// <returns>The task result.</returns>
/// <param name="task">Task to wait for.</param>
/// <param name="timeout">The timeout period.</param>
/// <param name="exceptionFactory">Optional timeout exception factory.</param>
/// <typeparam name="T">Task return type.</typeparam>
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, Func<TimeSpan, Exception> exceptionFactory = null)
{
if (await TimeoutTask(task, timeout).ConfigureAwait(false))
{
throw (exceptionFactory ?? _defaultExceptionFactory)(timeout);
}
return await task.ConfigureAwait(false);
}
private static async Task<bool> TimeoutTask(Task task, TimeSpan timeout)
{
if (timeout <= TimeSpan.Zero)
{
await task.ConfigureAwait(false);
return false;
}
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using var cancellationToken = new CancellationTokenSource();
cancellationToken.CancelAfter(timeout);
using (cancellationToken.Token.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
return tcs.Task == await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
}
}
}
}
| 47.30625 | 141 | 0.611309 | [
"MIT"
] | Meir017/playwright-sharp | src/PlaywrightSharp/Helpers/TaskHelper.cs | 7,569 | C# |
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Application.Editions;
using Abp.Domain.Entities.Auditing;
using Abp.MultiTenancy;
namespace GSoft.AbpZeroTemplate.MultiTenancy.Payments
{
[Table("AppSubscriptionPayments")]
[MultiTenancySide(MultiTenancySides.Host)]
public class SubscriptionPayment : FullAuditedEntity<long>
{
public SubscriptionPaymentGatewayType Gateway { get; set; }
public decimal Amount { get; set; }
public SubscriptionPaymentStatus Status { get; set; }
public int EditionId { get; set; }
public int TenantId { get; set; }
public int DayCount { get; set; }
public PaymentPeriodType? PaymentPeriodType { get; set; }
public string PaymentId { get; set; }
public Edition Edition { get; set; }
public string InvoiceNo { get; set; }
}
}
| 26.848485 | 67 | 0.67833 | [
"Apache-2.0"
] | NTD98/ASP_ANGULAR | asset-management-api/src/GSoft.AbpZeroTemplate.Core/MultiTenancy/Payments/SubscriptionPayment.cs | 888 | C# |
// <copyright file="ITradeFinishedPlugIn.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameLogic.Views.Trade;
/// <summary>
/// Interface of a view whose implementation informs about a finished trade.
/// </summary>
public interface ITradeFinishedPlugIn : IViewPlugIn
{
/// <summary>
/// The trade process has finished with the specified result.
/// </summary>
/// <param name="tradeResult">The trade result.</param>
void TradeFinished(TradeResult tradeResult);
} | 35.647059 | 101 | 0.727723 | [
"MIT"
] | ADMTec/OpenMU | src/GameLogic/Views/Trade/ITradeFinishedPlugIn.cs | 608 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace FunctionalTests
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Edm;
using System.Linq;
using System.Linq.Expressions;
using FunctionalTests.Model;
using Xunit;
public class AdvancedMappingScenarioTests : TestBase
{
[Fact]
public void Sql_ce_should_get_explicit_max_lengths_for_string_and_binary_properties_by_convention()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<MaxLengthProperties>();
var databaseMapping = BuildCeMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual("nvarchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(false, f => f.IsMaxLengthConstant);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual("nvarchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(false, f => f.IsMaxLengthConstant);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual("varbinary", c => c.TypeName);
}
[Fact]
public void Sql_ce_should_get_explicit_max_lengths_for_fixed_length_string_and_fixed_length_binary_properties_by_convention()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Id).IsFixedLength();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Prop1).IsFixedLength();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Prop2).IsFixedLength();
var databaseMapping = BuildCeMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual("nchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual("nchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(4000, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual("binary", c => c.TypeName);
}
[Fact]
public void Sql_should_get_implicit_max_lengths_for_string_and_binary_properties_by_convention()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<MaxLengthProperties>();
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(128, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual("nvarchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(true, f => f.IsMaxLengthConstant);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual("nvarchar(max)", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(true, f => f.IsMaxLengthConstant);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual("varbinary(max)", c => c.TypeName);
}
[Fact]
public void Sql_should_get_explicit_max_lengths_for_fixed_length_string_and_fixed_length_binary_properties_by_convention()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Id).IsFixedLength();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Prop1).IsFixedLength();
modelBuilder.Entity<MaxLengthProperties>().Property(e => e.Prop2).IsFixedLength();
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(128, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Id).DbEqual("nchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(128, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop1).DbEqual("nchar", c => c.TypeName);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(128, f => f.MaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual(false, f => f.IsMaxLength);
databaseMapping.Assert<MaxLengthProperties>(e => e.Prop2).DbEqual("binary", c => c.TypeName);
}
public class MaxLengthProperties
{
public string Id { get; set; }
public string Prop1 { get; set; }
public byte[] Prop2 { get; set; }
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_column_is_uniquified()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithConfiguredDuplicateColumn>();
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<EntityWithConfiguredDuplicateColumn>(e => e.Description).DbEqual(
"Description1",
c => c.Name);
databaseMapping.Assert<EntityWithConfiguredDuplicateColumn>(e => e.Details).DbEqual(
"Description",
c => c.Name);
}
public class EntityWithConfiguredDuplicateColumn
{
public int Id { get; set; }
public string Description { get; set; }
[Column("Description")]
public string Details { get; set; }
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_columns_are_uniquified_first()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescBase>();
modelBuilder.Entity<EntityWithDescA>().Property(e => e.Description).HasColumnName("Description");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<EntityWithDescA>(e => e.Description).DbEqual("Description", c => c.Name);
databaseMapping.Assert<EntityWithDescB>(e => e.Description).DbEqual("Description1", c => c.Name);
databaseMapping.Assert<EntityWithDescC>(e => e.Description).DbEqual("Description2", c => c.Name);
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_columns_are_uniquified_second()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescBase>();
modelBuilder.Entity<EntityWithDescB>().Property(e => e.Description).HasColumnName("Description");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<EntityWithDescA>(e => e.Description).DbEqual("Description1", c => c.Name);
databaseMapping.Assert<EntityWithDescB>(e => e.Description).DbEqual("Description", c => c.Name);
databaseMapping.Assert<EntityWithDescC>(e => e.Description).DbEqual("Description2", c => c.Name);
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_columns_are_uniquified_third()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescBase>();
modelBuilder.Entity<EntityWithDescC>().Property(e => e.Description).HasColumnName("Description");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<EntityWithDescA>(e => e.Description).DbEqual("Description1", c => c.Name);
databaseMapping.Assert<EntityWithDescB>(e => e.Description).DbEqual("Description2", c => c.Name);
databaseMapping.Assert<EntityWithDescC>(e => e.Description).DbEqual("Description", c => c.Name);
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_columns_are_uniquified_complex()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescA>().Property(e => e.Complex.Description).HasColumnName("Description");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<ComplexWithDesc>(c => c.Description).DbEqual("Description", c => c.Name);
databaseMapping.Assert<ComplexWithDesc>(c => c.Description).DbEqual(false, c => c.Nullable);
databaseMapping.Assert<EntityWithDescA>(e => e.Description).DbEqual("Description1", c => c.Name);
}
[Fact]
public void Can_have_configured_complex_column_override_column_name_clash()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescA>().Property(e => e.Complex.Description).HasColumnName("Description");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<ComplexWithDesc>(c => c.Description).DbEqual(false, c => c.Nullable);
databaseMapping.Assert<ComplexWithDesc>(c => c.Description).DbEqual("Description", c => c.Name);
databaseMapping.Assert<EntityWithDescA>(e => e.Description).DbEqual("Description1", c => c.Name);
}
[Fact]
public void Can_have_configured_duplicate_column_and_by_convention_columns_are_uniquified_conflict()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<EntityWithDescBase>();
modelBuilder.Entity<EntityWithDescB>().Property(e => e.Description).HasColumnName("Description");
modelBuilder.Entity<EntityWithDescB>().Property(e => e.NotDescription).HasColumnName("Description");
Assert.Throws<ModelValidationException>(() => BuildMapping(modelBuilder));
}
public class EntityWithDescBase
{
public int Id { get; set; }
}
public class EntityWithDescA : EntityWithDescBase
{
public string Description { get; set; }
public ComplexWithDesc Complex { get; set; }
}
public class EntityWithDescB : EntityWithDescBase
{
public string Description { get; set; }
public string NotDescription { get; set; }
public ComplexWithDesc Complex { get; set; }
}
public class EntityWithDescC : EntityWithDescBase
{
public string Description { get; set; }
public ComplexWithDesc Complex { get; set; }
}
public class ComplexWithDesc
{
[Required]
public string Description { get; set; }
}
[Fact]
public void Can_table_split_and_conflicting_columns_are_uniquified()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<SplitProduct>()
.ToTable("Product")
.HasAnnotation("A1", "V1")
.HasAnnotation("A2", "V2")
.HasAnnotation("A1", "V1B");
modelBuilder.Entity<SplitProductDetail>()
.HasAnnotation("A1", "V1B")
.HasAnnotation("A3", "V3")
.HasAnnotation("A4", "V4")
.HasAnnotation("A3", null)
.ToTable("Product");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert("Product")
.HasAnnotation("A1", "V1B")
.HasAnnotation("A2", "V2")
.HasAnnotation("A4", "V4")
.HasNoAnnotation("A3");
}
[Fact]
public void Table_splitting_with_conflicting_annotations_to_same_table_throws()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<SplitProduct>()
.ToTable("Product")
.HasAnnotation("A1", "V1")
.HasAnnotation("A2", "V2");
modelBuilder.Entity<SplitProductDetail>()
.HasAnnotation("A1", "V3")
.HasAnnotation("A3", "V4")
.ToTable("Product");
Assert.Throws<InvalidOperationException>(
() => BuildMapping(modelBuilder))
.ValidateMessage("ConflictingTypeAnnotation", "A1", "V3", "V1", "SplitProduct");
}
[Fact]
public void Can_table_split_and_conflicting_columns_can_be_configured()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<SplitProduct>().ToTable("Product");
modelBuilder.Entity<SplitProductDetail>()
.ToTable("Product")
.Property(s => s.Name)
.HasColumnName("Unique")
.HasAnnotation("Fish", "Blub");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<SplitProduct>(s => s.Name).DbEqual("Name", c => c.Name);
databaseMapping.Assert<SplitProductDetail>(s => s.Name).DbEqual("Unique", c => c.Name);
databaseMapping.Assert<SplitProduct>("Product")
.Column("Name")
.HasNoAnnotation("Fish");
databaseMapping.Assert<SplitProductDetail>("Product")
.Column("Unique")
.HasAnnotation("Fish", "Blub");
}
public class SplitProduct
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public SplitProductDetail Detail { get; set; }
}
public class SplitProductDetail
{
[ForeignKey("Product")]
public int Id { get; set; }
public string Name { get; set; }
[Required]
public SplitProduct Product { get; set; }
}
[Fact]
public void Single_abstract_type_with_associations_throws_not_mappable_exception()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<SingleAbstract>();
var exception = Assert.Throws<InvalidOperationException>(() => BuildMapping(modelBuilder));
exception.ValidateMessage("UnmappedAbstractType", typeof(SingleAbstract));
}
[Fact]
public void Configured_decimal_key_gets_correct_facet_defaults()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<DecimalKey>().HasKey(d => d.Id);
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
databaseMapping.Assert<DecimalKey>(d => d.Id).FacetEqual((byte)18, f => f.Precision);
databaseMapping.Assert<DecimalKey>(d => d.Id).FacetEqual((byte)2, f => f.Scale);
}
[Fact]
public void Decimal_key_with_custom_store_type_should_propagate_facets()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<DecimalKey>().Property(p => p.Id).HasColumnType("money");
var databaseMapping = BuildMapping(modelBuilder);
databaseMapping.AssertValid();
}
public class DecimalKey
{
public decimal Id { get; set; }
public ICollection<DecimalDependent> DecimalDependents { get; set; }
}
public class DecimalDependent
{
public int Id { get; set; }
public decimal DecimalKeyId { get; set; }
}
public abstract class SingleAbstract
{
public int Id { get; set; }
public DecimalDependent Nav { get; set; }
}
[Fact]
public void Throw_when_mapping_properties_expression_contains_assignments()
{
var modelBuilder = new DbModelBuilder();
Expression<Func<StockOrder, object>> propertiesExpression = so => new { Foo = so.LocationId };
var exception = Assert.Throws<InvalidOperationException>(
() => modelBuilder.Entity<StockOrder>().Map(emc => emc.Properties(propertiesExpression)));
exception.ValidateMessage("InvalidComplexPropertiesExpression", propertiesExpression);
}
[Fact]
public void Circular_delete_cascade_path_can_be_generated()
{
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<StockOrder>();
var databaseMapping = BuildMapping(modelBuilder);
Assert.Equal(
3,
databaseMapping.Model
.AssociationTypes
.SelectMany(a => a.Members)
.Cast<AssociationEndMember>()
.Count(e => e.DeleteBehavior == OperationAction.Cascade));
}
public class StockOrder
{
public int Id { get; set; }
public int LocationId { get; set; }
public Location Location { get; set; }
public ICollection<Organization> Organizations { get; set; }
}
public class Organization
{
public int Id { get; set; }
public int StockOrderId { get; set; }
public StockOrder StockOrder { get; set; }
public ICollection<Location> Locations { get; set; }
}
public class Location
{
public int Id { get; set; }
public ICollection<StockOrder> StockOrders { get; set; }
public int OrganizationId { get; set; }
public Organization Organization { get; set; }
}
[Fact]
public void Build_model_for_entity_splitting_difference_schemas()
{
var modelBuilder = new AdventureWorksModelBuilder();
modelBuilder.Entity<Vendor>()
.Map(
m =>
{
m.Properties(
v1 => new
{
v1.VendorID,
v1.Name,
v1.PreferredVendorStatus,
v1.AccountNumber,
v1.ActiveFlag,
v1.CreditRating
});
m.ToTable("Vendor", "vendors");
})
.Map(
m =>
{
m.Properties(
v2 => new
{
v2.VendorID,
v2.ModifiedDate,
v2.PurchasingWebServiceURL
});
m.ToTable("VendorDetails", "details");
});
var databaseMapping = BuildMapping(modelBuilder);
Assert.True(databaseMapping.Database.GetEntitySets().Any(s => s.Schema == "vendors"));
Assert.True(databaseMapping.Database.GetEntitySets().Any(s => s.Schema == "details"));
}
[Fact]
public void Build_model_for_mapping_to_duplicate_tables_different_schemas()
{
var modelBuilder = new AdventureWorksModelBuilder();
modelBuilder.Entity<Customer>().ToTable("tbl");
modelBuilder.Entity<Product>().ToTable("tbl", "other");
var databaseMapping = BuildMapping(modelBuilder);
Assert.True(databaseMapping.Database.GetEntitySets().Any(s => s.Schema == "dbo"));
Assert.True(databaseMapping.Database.GetEntitySets().Any(s => s.Schema == "other"));
databaseMapping.Assert<Customer>().DbEqual("tbl", t => t.Table);
databaseMapping.Assert<Product>().DbEqual("tbl", t => t.Table);
}
[Fact]
public void Build_model_after_configuring_entity_set_name()
{
var modelBuilder = new AdventureWorksModelBuilder();
modelBuilder.Entity<TransactionHistoryArchive>().HasEntitySetName("Foos");
var databaseMapping = BuildMapping(modelBuilder);
Assert.True(databaseMapping.Model.Containers.Single().EntitySets.Any(es => es.Name == "Foos"));
}
}
}
| 41.546448 | 133 | 0.600859 | [
"Apache-2.0"
] | mrward/entityframework-sharpdevelop | test/EntityFramework/FunctionalTests.Transitional/CodeFirst/AdvancedMappingScenarioTests.cs | 22,809 | C# |
namespace Computers.Data
{
using System;
using Computers.Models.Abstracts;
using Computers.Models.DellComputers;
using Computers.Models.HpComputers;
using Computers.Models.LenovoComputers;
public class ManufacturerFactory
{
private const string HP = "HP";
private const string Dell = "Dell";
private const string Lenovo = "Lenovo";
private const string InvalidManufacturerMessage = "Invalid manufacturer!";
public Manufacturer Create(string manufacturer)
{
Manufacturer computerFactory;
if (manufacturer == HP)
{
computerFactory = new HpManufacturer();
}
else if (manufacturer == Dell)
{
computerFactory = new DellManufacturer();
}
else if (manufacturer == Lenovo)
{
computerFactory = new LenovoManufacturer();
}
else
{
throw new ArgumentException(InvalidManufacturerMessage);
}
return computerFactory;
}
}
} | 28.325 | 82 | 0.565755 | [
"MIT"
] | NinoSimeonov/Telerik-Academy | Programming with C#/0. Exams/Telerik 2013-2014 - High-Quality Code/C# High-Quality Code - 6 August 2014 - Morning/Computers/Computers.Data/ManufacturerFactory.cs | 1,135 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PoweredSoft.CodeGenerator.Core
{
public interface IHasGeneratableChildren
{
List<IGeneratable> Children { get; }
}
}
| 18 | 44 | 0.726852 | [
"MIT"
] | PoweredSoft/CodeGenerator | PoweredSoft.CodeGenerator/Core/IHasGeneratableInterface.cs | 218 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Wodsoft.ComBoost.Website
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| 23.6 | 62 | 0.595339 | [
"MIT"
] | alexyjian/Core3.0 | Wodsoft.ComBoost.Website/App_Start/WebApiConfig.cs | 474 | C# |
namespace RiotPls.DataDragon.Enums
{
public enum BlockSummonerSpell
{
Empty,
ItemSmiteAoE,
ItemTeleportCancel,
OdinTrinketRevive,
S5SummonerSmiteDuel,
S5SummonerSmiteQuick,
S5SummonerSmitePlayerGanker,
SummonerBoost,
SummonerReturn,
SummonerSiegeChampSelect2,
SummonerSnowUrfSnowballMark,
SummonerSnowball,
SummonerDarkStarChampSelect1,
SummonerDemonBrand,
SummonerOdinPromote,
SummonerPoroRecall,
SummonerPoroThrow,
SummonerSmite,
SummonerTeleport,
TeleportCancel
}
} | 24.653846 | 37 | 0.647426 | [
"MIT"
] | JustNrik/RiotPls | src/RiotPls.DataDragon/Enums/BlockSummonerSpell.cs | 643 | C# |
using System;
using System.Collections.Generic;
using EventStore.Common.Log;
using EventStore.Core.Index;
using NUnit.Framework;
namespace EventStore.Core.Tests.Index.IndexV4 {
public class ptable_midpoint_calculations_should : SpecificationWithDirectory {
protected byte _ptableVersion = PTableVersions.IndexV4;
private static readonly ILogger Log = LogManager.GetLoggerFor<ptable_midpoint_calculations_should>();
private void construct_same_midpoint_indexes_for_any_combination_of_params(int maxIndexEntries) {
for (var numIndexEntries = 0; numIndexEntries < maxIndexEntries; numIndexEntries++) {
for (var depth = 0; depth < 20; depth++) {
var requiredMidpointsCount =
PTable.GetRequiredMidpointCountCached(numIndexEntries, _ptableVersion, depth);
List<long> requiredMidpoints = new List<long>();
for (var k = 0; k < requiredMidpointsCount; k++) {
var index = PTable.GetMidpointIndex(k, numIndexEntries, requiredMidpointsCount);
requiredMidpoints.Add(index);
}
List<long> calculatedMidpoints = new List<long>();
for (var k = 0; k < numIndexEntries; k++) {
if (PTable.IsMidpointIndex(k, numIndexEntries, requiredMidpointsCount)) {
calculatedMidpoints.Add(k);
}
}
if (numIndexEntries == 1 && calculatedMidpoints.Count == 1) {
calculatedMidpoints.Add(calculatedMidpoints[0]);
}
if (requiredMidpoints.Count != calculatedMidpoints.Count) {
Log.Error(
"Midpoint count mismatch for numIndexEntries: {0}, depth:{1} - Expected {2}, Found {3}",
numIndexEntries, depth, requiredMidpoints.Count, calculatedMidpoints.Count);
}
Assert.AreEqual(requiredMidpoints.Count, calculatedMidpoints.Count);
for (var i = 0; i < requiredMidpoints.Count; i++) {
if (requiredMidpoints[i] != calculatedMidpoints[i]) {
Log.Error(
"Midpoint mismatch at index {0} for numIndexEntries: {1}, depth:{2} - Expected {3}, Found {4}",
i, numIndexEntries, depth, requiredMidpoints[i], calculatedMidpoints[i]);
}
Assert.AreEqual(requiredMidpoints[i], calculatedMidpoints[i]);
}
}
}
}
[Test, Category("LongRunning"), Ignore("Long running")]
public void construct_same_midpoint_indexes_for_any_combination_of_params_large() {
construct_same_midpoint_indexes_for_any_combination_of_params(4096);
}
[Test]
public void construct_same_midpoint_indexes_for_any_combination_of_params_small() {
construct_same_midpoint_indexes_for_any_combination_of_params(200);
}
}
}
| 38.590909 | 103 | 0.725952 | [
"Apache-2.0",
"CC0-1.0"
] | JasonKStevens/EventStoreRx | src/EventStore.Core.Tests/Index/IndexV4/ptable_midpoint_calculations_should.cs | 2,547 | C# |
using System.Collections.Generic;
namespace DigitalOcean.API.Models.Responses {
public class AppsCorsPolicy {
public IList<AppsStringMatch> AllowOrigins { get; set; }
public IList<string> AllowMethods { get; set; }
public IList<string> AllowHeaders { get; set; }
public IList<string> ExposeHeaders { get; set; }
public string MaxAge { get; set; }
public bool AllowCredentials { get; set; }
}
}
| 34.692308 | 64 | 0.662971 | [
"MIT"
] | ruslanfirefly/DigitalOcean.API | DigitalOcean.API/Models/Responses/AppsCorsPolicy.cs | 451 | C# |
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour
{
LevelLogic levelLogic;
public void Activated()
{
levelLogic = GameObject.Find("Managers").GetComponent<LevelLogic>();
levelLogic.NexScene();
}
} | 19.384615 | 70 | 0.765873 | [
"MIT"
] | Adri102/2D-Unity-Game | Assets/Scripts/ChangeScene.cs | 254 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(Collider))]
public class BreakableWall : EntityBase
{
[Header("Breakable Wall")]
[SerializeField]
private Transform _wall;
[SerializeField]
private ParticleSystem _crumbleParticles;
[SerializeField]
[Tooltip("Percent damage dealt per second")]
private float _DOTRate = 0.5f;
[SerializeField]
private float _fallDist = 3;
public override void TakeDamage(float value)
{
if (_health <= 0) return;
OnTakeDamage?.Invoke();
StartCoroutine(Crumble(value));
if (_health <= 0)
{
GetComponent<Collider>().enabled = false;
OnDeath?.Invoke();
}
}
private IEnumerator Crumble(float damage)
{
float startingDamage = damage;
while(_health > 0 && damage > 0)
{
if(_crumbleParticles) _crumbleParticles.Play();
float damageDone = Time.deltaTime * _DOTRate * startingDamage;
damage -= damageDone;
_health -= damageDone;
_wall.position -= new Vector3(0, _fallDist * damageDone / _maxHealth, 0);
yield return new WaitForEndOfFrame();
if (_crumbleParticles) _crumbleParticles?.Pause();
}
}
/// <summary>
/// Does nothing
/// </summary>
/// <param name="value"></param>
/// <param name="knockbackForce"></param>
/// <param name="knockbackDir"></param>
/// <returns></returns>
public override IEnumerator TakeDamage(float value, float knockbackForce, Vector3 knockbackDir)
{
yield return null;
}
/// <summary>
/// Does nothing
/// </summary>
/// <param name="force"></param>
/// <param name="direction"></param>
/// <returns></returns>
public override IEnumerator Knockback(float force, Vector3 direction)
{
yield return null;
}
/// <summary>
/// Does nothing
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override float TakeHealing(float value)
{
return _health;
}
}
| 27.160494 | 99 | 0.602727 | [
"MIT"
] | metalac190/GameLab_Drosera | Assets/_Game/Scripts/Mechanics/Entities/BreakableWall.cs | 2,202 | C# |
//----------------------------------------------------------------------------
// This is autogenerated code by CppSharp.
// Do not edit this file or all your changes will be lost after re-generation.
//----------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace LLDB
{
public unsafe partial class LaunchInfo : IDisposable
{
[StructLayout(LayoutKind.Explicit, Size = 8)]
public partial struct Internal
{
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfoC2EPPKc")]
internal static extern void ctor_0(global::System.IntPtr instance, sbyte** argv);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfoC2ERKS0_")]
internal static extern void cctor_1(global::System.IntPtr instance, global::System.IntPtr _0);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfoD2Ev")]
internal static extern void dtor_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo13UserIDIsValidEv")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool UserIDIsValid_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo14GroupIDIsValidEv")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool GroupIDIsValid_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo17GetExecutableFileEv")]
internal static extern void GetExecutableFile_0(global::System.IntPtr @return, global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo17SetExecutableFileENS_10SBFileSpecEb")]
internal static extern void SetExecutableFile_0(global::System.IntPtr instance, LLDB.FileSpec.Internal exe_file, bool add_as_first_arg);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo11GetListenerEv")]
internal static extern void GetListener_0(global::System.IntPtr @return, global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo18GetArgumentAtIndexEj")]
internal static extern global::System.IntPtr GetArgumentAtIndex_0(global::System.IntPtr instance, uint idx);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo12SetArgumentsEPPKcb")]
internal static extern void SetArguments_0(global::System.IntPtr instance, sbyte** argv, bool append);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo26GetEnvironmentEntryAtIndexEj")]
internal static extern global::System.IntPtr GetEnvironmentEntryAtIndex_0(global::System.IntPtr instance, uint idx);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo21SetEnvironmentEntriesEPPKcb")]
internal static extern void SetEnvironmentEntries_0(global::System.IntPtr instance, sbyte** envp, bool append);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo5ClearEv")]
internal static extern void Clear_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo18AddCloseFileActionEi")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool AddCloseFileAction_0(global::System.IntPtr instance, int fd);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo22AddDuplicateFileActionEii")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool AddDuplicateFileAction_0(global::System.IntPtr instance, int fd, int dup_fd);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo17AddOpenFileActionEiPKcbb")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool AddOpenFileAction_0(global::System.IntPtr instance, int fd, global::System.IntPtr path, bool read, bool write);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo21AddSuppressFileActionEibb")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool AddSuppressFileAction_0(global::System.IntPtr instance, int fd, bool read, bool write);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo12GetProcessIDEv")]
internal static extern ulong GetProcessID_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo9GetUserIDEv")]
internal static extern uint GetUserID_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo9SetUserIDEj")]
internal static extern void SetUserID_0(global::System.IntPtr instance, uint uid);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo10GetGroupIDEv")]
internal static extern uint GetGroupID_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo10SetGroupIDEj")]
internal static extern void SetGroupID_0(global::System.IntPtr instance, uint gid);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo11SetListenerERNS_10SBListenerE")]
internal static extern void SetListener_0(global::System.IntPtr instance, global::System.IntPtr listener);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo15GetNumArgumentsEv")]
internal static extern uint GetNumArguments_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo24GetNumEnvironmentEntriesEv")]
internal static extern uint GetNumEnvironmentEntries_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZNK4lldb12SBLaunchInfo19GetWorkingDirectoryEv")]
internal static extern global::System.IntPtr GetWorkingDirectory_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo19SetWorkingDirectoryEPKc")]
internal static extern void SetWorkingDirectory_0(global::System.IntPtr instance, global::System.IntPtr working_dir);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo14GetLaunchFlagsEv")]
internal static extern uint GetLaunchFlags_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo14SetLaunchFlagsEj")]
internal static extern void SetLaunchFlags_0(global::System.IntPtr instance, uint flags);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo20GetProcessPluginNameEv")]
internal static extern global::System.IntPtr GetProcessPluginName_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo20SetProcessPluginNameEPKc")]
internal static extern void SetProcessPluginName_0(global::System.IntPtr instance, global::System.IntPtr plugin_name);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo8GetShellEv")]
internal static extern global::System.IntPtr GetShell_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo8SetShellEPKc")]
internal static extern void SetShell_0(global::System.IntPtr instance, global::System.IntPtr path);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo23GetShellExpandArgumentsEv")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool GetShellExpandArguments_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo23SetShellExpandArgumentsEb")]
internal static extern void SetShellExpandArguments_0(global::System.IntPtr instance, bool glob);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo14GetResumeCountEv")]
internal static extern uint GetResumeCount_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo14SetResumeCountEj")]
internal static extern void SetResumeCount_0(global::System.IntPtr instance, uint c);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZNK4lldb12SBLaunchInfo18GetLaunchEventDataEv")]
internal static extern global::System.IntPtr GetLaunchEventData_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo18SetLaunchEventDataEPKc")]
internal static extern void SetLaunchEventData_0(global::System.IntPtr instance, global::System.IntPtr data);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZNK4lldb12SBLaunchInfo16GetDetachOnErrorEv")]
[return: MarshalAsAttribute(UnmanagedType.I1)]
internal static extern bool GetDetachOnError_0(global::System.IntPtr instance);
[SuppressUnmanagedCodeSecurity]
[DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint="_ZN4lldb12SBLaunchInfo16SetDetachOnErrorEb")]
internal static extern void SetDetachOnError_0(global::System.IntPtr instance, bool enable);
}
public global::System.IntPtr __Instance { get; protected set; }
protected int __PointerAdjustment;
public static readonly System.Collections.Concurrent.ConcurrentDictionary<IntPtr, LaunchInfo> NativeToManagedMap = new System.Collections.Concurrent.ConcurrentDictionary<IntPtr, LaunchInfo>();
protected void*[] __OriginalVTables;
protected bool __ownsNativeInstance;
public static LaunchInfo __CreateInstance(global::System.IntPtr native, bool skipVTables = false)
{
return new LaunchInfo(native.ToPointer(), skipVTables);
}
public static LaunchInfo __CreateInstance(LaunchInfo.Internal native, bool skipVTables = false)
{
return new LaunchInfo(native, skipVTables);
}
private static void* __CopyValue(LaunchInfo.Internal native)
{
var ret = Marshal.AllocHGlobal(8);
LLDB.LaunchInfo.Internal.cctor_1(ret, new global::System.IntPtr(&native));
return ret.ToPointer();
}
private LaunchInfo(LaunchInfo.Internal native, bool skipVTables = false)
: this(__CopyValue(native), skipVTables)
{
__ownsNativeInstance = true;
NativeToManagedMap[__Instance] = this;
}
protected LaunchInfo(void* native, bool skipVTables = false)
{
if (native == null)
return;
__Instance = new global::System.IntPtr(native);
}
public LaunchInfo(sbyte** argv)
{
__Instance = Marshal.AllocHGlobal(8);
__ownsNativeInstance = true;
NativeToManagedMap[__Instance] = this;
var arg0 = argv;
Internal.ctor_0((__Instance + __PointerAdjustment), arg0);
}
public LaunchInfo(LLDB.LaunchInfo _0)
{
__Instance = Marshal.AllocHGlobal(8);
__ownsNativeInstance = true;
NativeToManagedMap[__Instance] = this;
if (ReferenceEquals(_0, null))
throw new global::System.ArgumentNullException("_0", "Cannot be null because it is a C++ reference (&).");
var arg0 = _0.__Instance;
Internal.cctor_1((__Instance + __PointerAdjustment), arg0);
}
public void Dispose()
{
Dispose(disposing: true);
}
protected virtual void Dispose(bool disposing)
{
LLDB.LaunchInfo __dummy;
NativeToManagedMap.TryRemove(__Instance, out __dummy);
Internal.dtor_0((__Instance + __PointerAdjustment));
if (__ownsNativeInstance)
Marshal.FreeHGlobal(__Instance);
}
public bool UserIDIsValid()
{
var __ret = Internal.UserIDIsValid_0((__Instance + __PointerAdjustment));
return __ret;
}
public bool GroupIDIsValid()
{
var __ret = Internal.GroupIDIsValid_0((__Instance + __PointerAdjustment));
return __ret;
}
public LLDB.FileSpec GetExecutableFile()
{
var __ret = new LLDB.FileSpec.Internal();
Internal.GetExecutableFile_0(new IntPtr(&__ret), (__Instance + __PointerAdjustment));
return LLDB.FileSpec.__CreateInstance(__ret);
}
/// <summary>
/// <para>Set the executable file that will be used to launch the process and</para>
/// <para>optionally set it as the first argument in the argument vector.</para>
/// </summary>
/// <remarks>
/// <para>This only needs to be specified if clients wish to carefully control</para>
/// <para>the exact path will be used to launch a binary. If you create a</para>
/// <para>target with a symlink, that symlink will get resolved in the target</para>
/// <para>and the resolved path will get used to launch the process. Calling</para>
/// <para>this function can help you still launch your process using the</para>
/// <para>path of your choice.</para>
/// <para>If this function is not called prior to launching with</para>
/// <para>SBTarget::Launch(...), the target will use the resolved executable</para>
/// <para>path that was used to create the target.</para>
/// </remarks>
/// <param name="exe_file">
/// <para>The override path to use when launching the executable.</para>
/// </param>
/// <param name="add_as_first_arg">
/// <para>If true, then the path will be inserted into the argument vector</para>
/// <para>prior to launching. Otherwise the argument vector will be left</para>
/// <para>alone.</para>
/// </param>
public void SetExecutableFile(LLDB.FileSpec exe_file, bool add_as_first_arg)
{
var arg0 = ReferenceEquals(exe_file, null) ? new LLDB.FileSpec.Internal() : *(LLDB.FileSpec.Internal*) (exe_file.__Instance);
Internal.SetExecutableFile_0((__Instance + __PointerAdjustment), arg0, add_as_first_arg);
}
/// <summary>
/// <para>Get the listener that will be used to receive process events.</para>
/// </summary>
/// <remarks>
/// <para>If no listener has been set via a call to</para>
/// <para>SBLaunchInfo::SetListener(), then an invalid SBListener will be</para>
/// <para>returned (SBListener::IsValid() will return false). If a listener</para>
/// <para>has been set, then the valid listener object will be returned.</para>
/// </remarks>
public LLDB.Listener GetListener()
{
var __ret = new LLDB.Listener.Internal();
Internal.GetListener_0(new IntPtr(&__ret), (__Instance + __PointerAdjustment));
return LLDB.Listener.__CreateInstance(__ret);
}
public string GetArgumentAtIndex(uint idx)
{
var __ret = Internal.GetArgumentAtIndex_0((__Instance + __PointerAdjustment), idx);
return Marshal.PtrToStringAnsi(__ret);
}
public void SetArguments(sbyte** argv, bool append)
{
var arg0 = argv;
Internal.SetArguments_0((__Instance + __PointerAdjustment), arg0, append);
}
public string GetEnvironmentEntryAtIndex(uint idx)
{
var __ret = Internal.GetEnvironmentEntryAtIndex_0((__Instance + __PointerAdjustment), idx);
return Marshal.PtrToStringAnsi(__ret);
}
public void SetEnvironmentEntries(sbyte** envp, bool append)
{
var arg0 = envp;
Internal.SetEnvironmentEntries_0((__Instance + __PointerAdjustment), arg0, append);
}
public void Clear()
{
Internal.Clear_0((__Instance + __PointerAdjustment));
}
public bool AddCloseFileAction(int fd)
{
var __ret = Internal.AddCloseFileAction_0((__Instance + __PointerAdjustment), fd);
return __ret;
}
public bool AddDuplicateFileAction(int fd, int dup_fd)
{
var __ret = Internal.AddDuplicateFileAction_0((__Instance + __PointerAdjustment), fd, dup_fd);
return __ret;
}
public bool AddOpenFileAction(int fd, string path, bool read, bool write)
{
var arg1 = Marshal.StringToHGlobalAnsi(path);
var __ret = Internal.AddOpenFileAction_0((__Instance + __PointerAdjustment), fd, arg1, read, write);
Marshal.FreeHGlobal(arg1);
return __ret;
}
public bool AddSuppressFileAction(int fd, bool read, bool write)
{
var __ret = Internal.AddSuppressFileAction_0((__Instance + __PointerAdjustment), fd, read, write);
return __ret;
}
public ulong ProcessID
{
get
{
var __ret = Internal.GetProcessID_0((__Instance + __PointerAdjustment));
return __ret;
}
}
public uint UserID
{
get
{
var __ret = Internal.GetUserID_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetUserID_0((__Instance + __PointerAdjustment), value);
}
}
public uint GroupID
{
get
{
var __ret = Internal.GetGroupID_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetGroupID_0((__Instance + __PointerAdjustment), value);
}
}
public LLDB.Listener Listener
{
set
{
if (ReferenceEquals(value, null))
throw new global::System.ArgumentNullException("value", "Cannot be null because it is a C++ reference (&).");
var arg0 = value.__Instance;
Internal.SetListener_0((__Instance + __PointerAdjustment), arg0);
}
}
public uint NumArguments
{
get
{
var __ret = Internal.GetNumArguments_0((__Instance + __PointerAdjustment));
return __ret;
}
}
public uint NumEnvironmentEntries
{
get
{
var __ret = Internal.GetNumEnvironmentEntries_0((__Instance + __PointerAdjustment));
return __ret;
}
}
public string WorkingDirectory
{
get
{
var __ret = Internal.GetWorkingDirectory_0((__Instance + __PointerAdjustment));
return Marshal.PtrToStringAnsi(__ret);
}
set
{
var arg0 = Marshal.StringToHGlobalAnsi(value);
Internal.SetWorkingDirectory_0((__Instance + __PointerAdjustment), arg0);
Marshal.FreeHGlobal(arg0);
}
}
public uint LaunchFlags
{
get
{
var __ret = Internal.GetLaunchFlags_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetLaunchFlags_0((__Instance + __PointerAdjustment), value);
}
}
public string ProcessPluginName
{
get
{
var __ret = Internal.GetProcessPluginName_0((__Instance + __PointerAdjustment));
return Marshal.PtrToStringAnsi(__ret);
}
set
{
var arg0 = Marshal.StringToHGlobalAnsi(value);
Internal.SetProcessPluginName_0((__Instance + __PointerAdjustment), arg0);
Marshal.FreeHGlobal(arg0);
}
}
public string Shell
{
get
{
var __ret = Internal.GetShell_0((__Instance + __PointerAdjustment));
return Marshal.PtrToStringAnsi(__ret);
}
set
{
var arg0 = Marshal.StringToHGlobalAnsi(value);
Internal.SetShell_0((__Instance + __PointerAdjustment), arg0);
Marshal.FreeHGlobal(arg0);
}
}
public bool ShellExpandArguments
{
get
{
var __ret = Internal.GetShellExpandArguments_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetShellExpandArguments_0((__Instance + __PointerAdjustment), value);
}
}
public uint ResumeCount
{
get
{
var __ret = Internal.GetResumeCount_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetResumeCount_0((__Instance + __PointerAdjustment), value);
}
}
public string LaunchEventData
{
get
{
var __ret = Internal.GetLaunchEventData_0((__Instance + __PointerAdjustment));
return Marshal.PtrToStringAnsi(__ret);
}
set
{
var arg0 = Marshal.StringToHGlobalAnsi(value);
Internal.SetLaunchEventData_0((__Instance + __PointerAdjustment), arg0);
Marshal.FreeHGlobal(arg0);
}
}
public bool DetachOnError
{
get
{
var __ret = Internal.GetDetachOnError_0((__Instance + __PointerAdjustment));
return __ret;
}
set
{
Internal.SetDetachOnError_0((__Instance + __PointerAdjustment), value);
}
}
}
}
| 45.963875 | 200 | 0.640862 | [
"MIT"
] | tritao/LLDBSharp | LLDBSharp/i686-apple-darwin/SBLaunchInfo.cs | 27,992 | C# |
using BudgetAttempt.Finance.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using AutoMapper;
using BudgetAttempt.API.Models;
namespace BudgetAttempt.API
{
public class Budget : IBudget
{
readonly IFinanceRepository _FinanceRepository;
readonly IPersonRepository _PersonRepository;
public Budget(IFinanceRepository financeRepository, IPersonRepository personRepository)
{
this._FinanceRepository = financeRepository ?? throw new ArgumentNullException("financeRepository");
this._PersonRepository = personRepository ?? throw new ArgumentNullException("personRepository");
}
#region Transactions
public IEnumerable<Models.Transaction> GetLastMonthTransactionsJson()
{
return GetLastMonthTransactions();
}
public IEnumerable<Models.Transaction> GetLastMonthTransactionsXml()
{
return GetLastMonthTransactions();
}
public IEnumerable<Models.Transaction> GetLatestTransactionsJson(int count)
{
return GetLatestTransactions(count);
}
public IEnumerable<Models.Transaction> GetLatestTransactionsXml(int count)
{
return GetLatestTransactions(count);
}
private IEnumerable<Models.Transaction> GetLatestTransactions(int count)
{
return Mapper.Map<IEnumerable<Models.Transaction>>(_FinanceRepository.FetchAll(0, count));
}
private IEnumerable<Models.Transaction> GetLastMonthTransactions()
{
var filter = new BudgetAttempt.Finance.Models.Filter()
{
StartDate = DateTime.Now.AddMonths(-1),
EndDate = DateTime.Now
};
return Mapper.Map<IEnumerable<Models.Transaction>>(_FinanceRepository.FetchFiltered(filter));
}
public Transaction AddTransactionJson(Transaction data)
{
return AddTransaction(data);
}
public Transaction AddTransactionXml(Transaction data)
{
return AddTransaction(data);
}
private Transaction AddTransaction(Transaction data)
{
var t = Mapper.Map<Finance.Models.FinanceEntry>(data);
t = _FinanceRepository.CreateEntry(t);
return Mapper.Map<Transaction>(t);
}
public IEnumerable<Models.Transaction> GetMonthTransactionsJson(string yearmonth)
{
return GetMonthTransactions(yearmonth);
}
public IEnumerable<Models.Transaction> GetMonthTransactionsXml(string yearmonth)
{
return GetMonthTransactions(yearmonth);
}
private IEnumerable<Models.Transaction> GetMonthTransactions(string yearmonth)
{
var d= DateTime.ParseExact(yearmonth + "-01 00:00:00", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
var filter = new BudgetAttempt.Finance.Models.Filter()
{
StartDate = d,
EndDate =d.AddMonths(1).AddSeconds(-1),
};
return Mapper.Map<IEnumerable<Models.Transaction>>(_FinanceRepository.FetchFiltered(filter));
}
#endregion
#region persons
public IEnumerable<Person> GetAllPersonsJson()
{
return GetAllPersons();
}
public IEnumerable<Person> GetAllPersonsXml()
{
return GetAllPersons();
}
public IEnumerable<Person> GetAllPersons()
{
return Mapper.Map<IEnumerable<Models.Person>>(_PersonRepository.FetchAll());
}
public Models.Person MergePersonJson(Models.Person data)
{
return MergePerson(data);
}
public Models.Person MergePersonXml(Models.Person data)
{
return MergePerson(data);
}
public Person MergePerson(Models.Person data)
{
var p = _PersonRepository.FetchOne(data.Id);
if (p != null)
{
p.FirstName = data.FirstName;
p.LastName = data.LastName;
p = _PersonRepository.Update(p);
}
else
{
p = Mapper.Map<Finance.Models.Person>(data);
p = _PersonRepository.Create(p);
}
return Mapper.Map<Models.Person>(p);
}
#endregion
#region categories
public TransactionCategory CreateCategoryJson(TransactionCategory data)
{
return CreateCategory(data);
}
public TransactionCategory CreateCategoryXml(TransactionCategory data)
{
return CreateCategory(data);
}
public TransactionCategory CreateCategory(TransactionCategory data)
{
var c = _FinanceRepository.FetchCategoryByNameAndType(Mapper.Map<Finance.Models.FinanceCategory>(data));
if (c == null)
{
c = Mapper.Map<Finance.Models.FinanceCategory>(data);
c = _FinanceRepository.CreateCategory(c);
}
return Mapper.Map<TransactionCategory>(c);
}
public IEnumerable<TransactionCategory> GetAllCategoriesJson()
{
return GetAllCategories();
}
public IEnumerable<TransactionCategory> GetAllCategoriesXml()
{
return GetAllCategories();
}
public IEnumerable<TransactionCategory> GetAllCategories()
{
return Mapper.Map<IEnumerable<Models.TransactionCategory>>(_FinanceRepository.FetchAllCategories());
}
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
}
#endregion
}
}
| 32.116751 | 183 | 0.623044 | [
"MIT"
] | yiangos/BudgetAttempt | BudgetAttempt.API/Budget.svc.cs | 6,329 | C# |
//-----------------------------------------------------------------------
// <copyright file="WebSsoRequestBase.cs" company="10Duke Software">
// Copyright (c) 10Duke
// </copyright>
// <author>Jarkko Selkäinaho</author>
//-----------------------------------------------------------------------
namespace Tenduke.SsoClient.Request
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// References a method to be called when handling a <see cref="WebSsoRequestBase{T}"/> is completed.
/// </summary>
/// <typeparam name="T">Request type derived from <see cref="WebSsoRequestBase{T}"/>.</typeparam>
/// <param name="webSsoRequest">The completed request.</param>
/// <param name="canceled"><c>true</c> if request handling was canceled, <c>false</c> otherwise.</param>
public delegate void WebSsoRequestCallback<T>(T webSsoRequest, bool canceled) where T : WebSsoRequestBase<T>;
/// <summary>
/// References a method to be called when received response for next step in handling the request.
/// </summary>
/// <param name="nextResponse"><see cref="HttpWebResponse"/> returned by next request, or <c>null</c> if no further requests required.</param>
/// <param name="cancel"><c>true</c> to cancel request handling, <c>false</c> otherwise.</param>
public delegate void NextResponseCallback(HttpWebResponse nextResponse, bool cancel);
/// <summary>
/// Base classes for classes that wrap a <see cref="HttpWebRequest"/> and support authentication in a Web Single Sign-On environment.
/// </summary>
public abstract class WebSsoRequestBase<T> where T : WebSsoRequestBase<T>
{
#region constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSsoRequestBase{T}"/> class.
/// </summary>
protected WebSsoRequestBase()
{
}
#endregion
#region properties
/// <summary>
/// Asynchronous request status object, used during request handling.
/// </summary>
protected IAsyncResult AsyncResult { get; set; }
/// <summary>
/// The HTTP response, set when handling request is ready.
/// </summary>
public HttpWebResponse Response { get; protected set; }
#endregion
#region methods
/// <summary>
/// Gets the <see cref="HttpWebRequest"/> wrapped by this object.
/// </summary>
/// <returns>The <see cref="HttpWebRequest"/>.</returns>
protected abstract HttpWebRequest GetHttpWebRequest();
/// <summary>
/// Executes next request required for getting the final response for the <see cref="WebSsoRequestBase{T}"/>.
/// </summary>
/// <param name="response"><see cref="HttpWebResponse"/> representing current HTTP response.</param>
/// <param name="nextResponseCallback">Callback for receiving <see cref="HttpWebResponse"/> returned by next request, or <c>null</c> if
/// the given <paramref name="response"/> is the final response to the <see cref="WebSsoRequestBase{T}"/>.</param>
protected abstract void GetNextResponse(HttpWebResponse response, NextResponseCallback nextResponseCallback);
/// <summary>
/// Begins getting HTTP response asynchronously.
/// </summary>
/// <param name="responseCallback"><see cref="WebSsoRequestCallback{T}"/> called when handling the request is completed.
/// The callback method is responsible for handling and closing the response (<see cref="WebSsoRequestBase{T}.Response"/>).</param>
/// <returns>Returns this object.</returns>
/// <exception cref="InvalidOperationException">
/// <para><see cref="HttpWebRequest"/> is not initialized, i.e. calling <see cref="GetHttpWebRequest"/> returns <c>null</c>.</para>
/// <para>-or-</para>
/// <para>The stream is already in use by a previous call to <see cref="HttpWebRequest.BeginGetResponse(AsyncCallback, object)"/>.</para>
/// <para>-or-</para>
/// <para>TransferEncoding is set to a value and SendChunked is <c>false</c>.</para>
/// <para>-or-</para>
/// <para>The thread pool is running out of threads.</para>
/// </exception>
/// <exception cref="ProtocolViolationException">
/// <para>Method is GET or HEAD, and either ContentLength is greater than zero or SendChunked is <c>true</c>.</para>
/// <para>-or-</para>
/// <para>KeepAlive is <c>true</c>, AllowWriteStreamBuffering is <c>false</c>, and either ContentLength is -1, SendChunked is <c>false</c> and Method is POST or PUT.</para>
/// <para>-or-</para>
/// <para>The HttpWebRequest has an entity body but the BeginGetResponse method is called without calling the BeginGetRequestStream method.</para>
/// <para>-or-</para>
/// <para>The ContentLength is greater than zero, but the application does not write all of the promised data.</para>
/// </exception>
/// <exception cref="WebException">Abort was previously called.</exception>
public T BeginGetResponse(WebSsoRequestCallback<T> responseCallback)
{
var request = GetHttpWebRequest();
if (request == null)
{
throw new InvalidOperationException("HttpWebRequest must be initialized");
}
var cookieContainer = request.CookieContainer;
if (cookieContainer == null)
{
throw new InvalidOperationException("CookieContainer must not be null");
}
var asyncResult = request.BeginGetResponse(result =>
{
var response = (HttpWebResponse)request.EndGetResponse(result);
HandleResponse(response, responseCallback);
}, this);
AsyncResult = asyncResult;
return (T)this;
}
/// <summary>
/// Gets HTTP response synchronously. After calling this method, caller can access the response in <see cref="WebSsoRequestBase{T}.Response"/>.
/// Caller of this method is responsible for handling and closing the response.
/// </summary>
/// <param name="timeout">The request timeout, or a <see cref="TimeSpan"/> that represents -1 milliseconds to wait indefinitely.</param>
/// <returns>Returns this object.</returns>
/// <exception cref="TimeoutException">Thrown if timeout occurs.</exception>
/// <exception cref="OperationCanceledException">Thrown if handling the <see cref="WebSsoRequestBase{T}"/> was canceled.</exception>
/// <exception cref="InvalidOperationException">
/// <para><see cref="HttpWebRequest"/> is not initialized, i.e. calling <see cref="GetHttpWebRequest"/> returns <c>null</c>.</para>
/// <para>-or-</para>
/// <para>The stream is already in use by a previous call to <see cref="HttpWebRequest.BeginGetResponse(AsyncCallback, object)"/>.</para>
/// <para>-or-</para>
/// <para>TransferEncoding is set to a value and SendChunked is <c>false</c>.</para>
/// <para>-or-</para>
/// <para>The thread pool is running out of threads.</para>
/// </exception>
/// <exception cref="ProtocolViolationException">
/// <para>Method is GET or HEAD, and either ContentLength is greater than zero or SendChunked is <c>true</c>.</para>
/// <para>-or-</para>
/// <para>KeepAlive is <c>true</c>, AllowWriteStreamBuffering is <c>false</c>, and either ContentLength is -1, SendChunked is <c>false</c> and Method is POST or PUT.</para>
/// <para>-or-</para>
/// <para>The HttpWebRequest has an entity body but the BeginGetResponse method is called without calling the BeginGetRequestStream method.</para>
/// <para>-or-</para>
/// <para>The ContentLength is greater than zero, but the application does not write all of the promised data.</para>
/// </exception>
/// <exception cref="WebException">Abort was previously called.</exception>
public T GetResponse(TimeSpan timeout)
{
var doneEvent = new ManualResetEvent(false);
var done = false;
var webSsoRequestCanceled = false;
BeginGetResponse((webSsoRequest, canceled) =>
{
webSsoRequestCanceled = canceled;
done = true;
doneEvent.Set();
}
);
doneEvent.WaitOne(timeout);
if (webSsoRequestCanceled)
{
throw new OperationCanceledException("Request handling canceled");
}
if (!done)
{
throw new TimeoutException("Request timeout");
}
return (T)this;
}
#endregion
#region private methods
/// <summary>
/// Handles HTTP response.
/// </summary>
/// <param name="response"><see cref="HttpWebResponse"/> representing HTTP response.</param>
/// <param name="responseCallback"><see cref="WebSsoRequestCallback{T}"/> called when handling the request is completed.
/// The callback method is responsible for handling and closing the response (<see cref="WebSsoRequestBase{T}.Response"/>).</param>
private void HandleResponse(HttpWebResponse response, WebSsoRequestCallback<T> responseCallback)
{
GetNextResponse(response, (nextResponse, cancel) =>
{
if (cancel)
{
response?.Dispose();
responseCallback((T) this, true);
}
else if (nextResponse == null)
{
Response = response;
responseCallback((T)this, false);
}
else
{
response?.Dispose();
HandleResponse(nextResponse, responseCallback);
}
}
);
}
#endregion
}
}
| 48.541284 | 181 | 0.584672 | [
"MIT"
] | 10Duke/desktop-web-sso-example | Tenduke.SsoClient/Request/WebSsoRequestBase.cs | 10,585 | C# |
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using System;
using Tensorflow.Keras.Engine;
using static Tensorflow.Binding;
namespace Tensorflow
{
public class LayerRnnCell : RnnCell
{
protected InputSpec inputSpec;
protected bool built;
protected Graph _graph;
protected VariableScope _scope;
protected VariableScope _current_scope;
protected bool? _reuse;
protected bool _use_resource_variables;
protected bool _keras_style;
public LayerRnnCell(bool trainable = true,
string name = null,
TF_DataType dtype = TF_DataType.DtInvalid,
bool? _reuse = null) : base(_reuse: _reuse,
name: name,
dtype: dtype)
{
// For backwards compatibility, legacy layers do not use `ResourceVariable`
// by default.
this._use_resource_variables = false;
this._reuse = _reuse;
// Avoid an incorrect lint error
this.built = false;
_keras_style = false;
}
protected virtual void build(TensorShape inputs_shape)
{
}
public virtual (Tensor, Tensor) apply(Tensor inputs, Tensor training = null)
{
var results = __call__(inputs, training: training);
return (results[0], results[1]);
}
public Tensors __call__(Tensors inputs,
Tensor state = null,
Tensor training = null,
VariableScope scope = null)
{
_set_scope(scope);
_graph = ops._get_graph_from_inputs(inputs, graph: _graph);
variable_scope scope_context_manager = null;
if (built)
{
scope_context_manager = tf.variable_scope(_scope,
reuse: true,
auxiliary_name_scope: false);
}
else
{
scope_context_manager = tf.variable_scope(_scope,
reuse: _reuse,
auxiliary_name_scope: false);
}
Tensors outputs = null;
tf_with(scope_context_manager, scope2 =>
{
_current_scope = scope2;
// Actually call layer
});
// Update global default collections.
return outputs;
}
protected virtual void _add_elements_to_collection(Operation[] elements, string[] collection_list)
{
foreach (var name in collection_list)
{
var collection = ops.get_collection_ref<Operation>(name);
foreach (var element in elements)
if (!collection.Contains(element))
collection.Add(element);
}
}
/// <summary>
/// Adds a new variable to the layer, or gets an existing one; returns it.
/// </summary>
/// <param name="name"></param>
/// <param name="shape"></param>
/// <param name="dtype"></param>
/// <param name="initializer"></param>
/// <param name="trainable"></param>
/// <param name="synchronization"></param>
/// <param name="aggregation"></param>
/// <returns></returns>
protected virtual IVariableV1 add_weight(string name,
int[] shape,
TF_DataType dtype = TF_DataType.DtInvalid,
IInitializer initializer = null,
bool trainable = true,
VariableSynchronization synchronization = VariableSynchronization.Auto,
VariableAggregation aggregation = VariableAggregation.None)
{
var default_graph = ops.get_default_graph();
Graph init_graph = null;
IVariableV1[] existing_variables = null;
if (synchronization == VariableSynchronization.OnRead)
trainable = false;
if (default_graph.building_function)
{
throw new NotImplementedException("add_weight");
}
else
{
init_graph = default_graph;
existing_variables = variables.global_variables().ToArray();
}
if (dtype == TF_DataType.DtInvalid)
dtype = TF_DataType.TF_FLOAT;
_set_scope();
var reuse = built || (_reuse != null && _reuse.Value);
return tf.Variable(0);
}
protected string _name_scope()
{
return _current_scope.original_name_scope;
}
protected void _set_scope(VariableScope scope = null)
{
if (_scope == null)
{
if (_reuse.HasValue && _reuse.Value)
{
throw new NotImplementedException("_set_scope _reuse.HasValue");
/*with(tf.variable_scope(scope == null ? _base_name : scope),
captured_scope => _scope = captured_scope);*/
}
else
{
}
}
}
}
}
| 33.185393 | 106 | 0.539191 | [
"Apache-2.0"
] | Aangbaeck/TensorFlow.NET | src/TensorFlowNET.Core/Operations/NnOps/LayerRNNCell.cs | 5,909 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Application.Dto;
using Application.Dto.Email;
using Application.Dto.QueryParams;
using Application.Services.Interfaces;
using AutoMapper;
using Domain.RDBMS;
using Domain.RDBMS.Entities;
using Domain.RDBMS.Enums;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using MimeKit;
namespace Application.Services.Implementation
{
public class RequestService : IRequestService
{
private readonly IRepository<Request> _requestRepository;
private readonly IRepository<Book> _bookRepository;
private readonly IMapper _mapper;
private readonly IEmailSenderService _emailSenderService;
private readonly IRepository<User> _userRepository;
private readonly IPaginationService _paginationService;
private readonly IHangfireJobScheduleService _hangfireJobScheduleService;
private readonly IWishListService _wishListService;
private readonly INotificationsService _notificationsService;
public RequestService(
IRepository<Request> requestRepository,
IRepository<Book> bookRepository,
IMapper mapper,
IEmailSenderService emailSenderService,
IRepository<User> userRepository,
IPaginationService paginationService,
IHangfireJobScheduleService hangfireJobScheduleService,
IWishListService wishListService,
INotificationsService notificationsService)
{
_requestRepository = requestRepository;
_bookRepository = bookRepository;
_mapper = mapper;
_emailSenderService = emailSenderService;
_userRepository = userRepository;
_paginationService = paginationService;
_hangfireJobScheduleService = hangfireJobScheduleService;
_wishListService = wishListService;
_notificationsService = notificationsService;
}
/// <inheritdoc />
public async Task<RequestDto> MakeAsync(int userId, int bookId)
{
var book = await _bookRepository.GetAll().Include(x => x.User).FirstOrDefaultAsync(x => x.Id == bookId);
var isNotAvailableForRequest = book == null || book.State != BookState.Available;
if (isNotAvailableForRequest)
{
return null;
}
if (userId == book.UserId)
{
throw new InvalidOperationException("You cannot request your book");
}
var user = await _userRepository.FindByIdAsync(userId);
if (user.IsDeleted)
{
throw new InvalidOperationException("As deleted user you cannot request books");
}
var request = new Request()
{
BookId = book.Id,
OwnerId = book.UserId,
UserId = userId,
RequestDate = DateTime.UtcNow
};
_requestRepository.Add(request);
await _requestRepository.SaveChangesAsync();
book.State = BookState.Requested;
await _bookRepository.SaveChangesAsync();
if (book.User.IsEmailAllowed)
{
var emailMessageForRequest = new RequestMessage()
{
OwnerName = book.User.FirstName + " " + book.User.LastName,
BookName = book.Name,
RequestDate = request.RequestDate,
RequestId = request.Id,
OwnerAddress = new MailboxAddress($"{book.User.Email}"),
UserName = user.FirstName + " " + user.LastName
};
await _emailSenderService.SendForRequestAsync(emailMessageForRequest);
}
await _notificationsService.NotifyAsync(
book.User.Id,
$"Your book '{book.Name}' was requested by {user.FirstName} {user.LastName}",
$"Надійшов запит щодо вашої книги '{book.Name}' від {user.FirstName} {user.LastName}",
book.Id,
NotificationActions.Open);
await _notificationsService.NotifyAsync(
user.Id,
$"The book '{book.Name}' successfully requested.",
$"Запит щодо книги '{book.Name}' успішно подано",
book.Id,
NotificationActions.Open);
var emailMessageForReceiveConfirmation = new RequestMessage()
{
UserName = user.FirstName + " " + user.LastName,
BookName = book.Name,
BookId = book.Id,
RequestId = request.Id,
UserAddress = new MailboxAddress($"{user.Email}"),
User = user
};
await _hangfireJobScheduleService.ScheduleRequestJob(emailMessageForReceiveConfirmation);
return _mapper.Map<RequestDto>(request);
}
/// <inheritdoc />
public async Task<RequestDto> GetByBookAsync(Expression<Func<Request, bool>> predicate, RequestsQueryParams query)
{
Request request = null;
if (query.First)
{
request = await _requestRepository.GetAll()
.Include(i => i.Book).ThenInclude(i => i.BookAuthor).ThenInclude(i => i.Author)
.Include(i => i.Book).ThenInclude(i => i.BookGenre).ThenInclude(i => i.Genre)
.Include(i => i.Book).ThenInclude(i => i.Language)
.Include(i => i.Owner).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Include(i => i.User).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.FirstOrDefaultAsync(predicate);
}
else if (query.Last)
{
request = _requestRepository.GetAll()
.Include(i => i.Book).ThenInclude(i => i.BookAuthor).ThenInclude(i => i.Author)
.Include(i => i.Book).ThenInclude(i => i.BookGenre).ThenInclude(i => i.Genre)
.Include(i => i.Book).ThenInclude(i => i.Language)
.Include(i => i.Owner).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Include(i => i.User).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location).Where(predicate).AsEnumerable()
.Last();
}
if (request == null)
{
return null;
}
return _mapper.Map<RequestDto>(request);
}
/// <inheritdoc />
public async Task<IEnumerable<RequestDto>> GetAllByBookAsync(Expression<Func<Request, bool>> predicate)
{
var requests = _requestRepository.GetAll()
.Include(i => i.Book).ThenInclude(i => i.BookAuthor).ThenInclude(i => i.Author)
.Include(i => i.Book).ThenInclude(i => i.BookGenre).ThenInclude(i => i.Genre)
.Include(i => i.Book).ThenInclude(i => i.Language)
.Include(i => i.Owner).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Include(i => i.User).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Where(predicate);
if (requests == null)
{
return null;
}
return _mapper.Map<List<RequestDto>>(requests);
}
/// <inheritdoc />
public async Task<PaginationDto<RequestDto>> GetAsync(Expression<Func<Request, bool>> predicate, BookQueryParams parameters)
{
var query = _requestRepository.GetAll()
.Include(i => i.Book).ThenInclude(i => i.BookAuthor).ThenInclude(i => i.Author)
.Include(i => i.Book).ThenInclude(i => i.BookGenre).ThenInclude(i => i.Genre)
.Include(i => i.Book).ThenInclude(i => i.Language)
.Include(i => i.Owner).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Include(i => i.User).ThenInclude(i => i.UserRoom).ThenInclude(i => i.Location)
.Where(predicate);
if (parameters.BookStates != null)
{
var wherePredicate = PredicateBuilder.New<Request>();
foreach (var state in parameters.BookStates)
{
wherePredicate = wherePredicate.Or(g => g.Book.State == state);
}
query = query.Where(wherePredicate);
}
if (parameters.SearchTerm != null)
{
var term = parameters.SearchTerm.Split(" ");
if (term.Length == 1)
{
query = query.Where(
x =>
(x.Book.ISBN != null && x.Book.ISBN.Contains(parameters.SearchTerm)) ||
x.Book.Name.Contains(parameters.SearchTerm) ||
x.Book.BookAuthor.Any(
a =>
a.Author.LastName.Contains(term[term.Length - 1]) ||
a.Author.FirstName.Contains(term[0])
)
);
}
else
{
query = query.Where(
x =>
(x.Book.ISBN != null && x.Book.ISBN.Contains(parameters.SearchTerm)) ||
x.Book.Name.Contains(parameters.SearchTerm) ||
x.Book.BookAuthor.Any(
a =>
a.Author.LastName.Contains(term[term.Length - 1]) &&
a.Author.FirstName.Contains(term[0])
)
);
}
}
if (parameters.Languages != null)
{
var wherePredicate = PredicateBuilder.New<Request>();
foreach (var id in parameters.Languages)
{
wherePredicate = wherePredicate.Or(g => g.Book.Language.Id == id);
}
query = query.Where(wherePredicate);
}
if (parameters.Genres != null)
{
var wherePredicate = PredicateBuilder.New<Request>();
foreach (var id in parameters.Genres)
{
var tempId = id;
wherePredicate = wherePredicate.Or(g => g.Book.BookGenre.Any(g => g.Genre.Id == tempId));
}
query = query.Where(wherePredicate);
}
if (parameters.SortableParams != null)
{
query = SortRequests(query, parameters.SortableParams);
}
return await _paginationService.GetPageAsync<RequestDto, Request>(query, parameters);
}
public IQueryable<Request> SortRequests(IQueryable<Request> requests, SortableParams sortableParams)
{
switch (sortableParams.OrderByField)
{
case "Rating":
requests = sortableParams.OrderByAscending ?
requests.OrderBy(r => r.Book.Rating):
requests.OrderByDescending(r => r.Book.Rating);
break;
case "DateAdded":
requests = sortableParams.OrderByAscending ?
requests.OrderBy(r => r.Book.DateAdded) :
requests.OrderByDescending(r => r.Book.DateAdded);
break;
case "Name":
requests = sortableParams.OrderByAscending ?
requests.OrderBy(r => r.Book.Name) :
requests.OrderByDescending(r => r.Book.Name);
break;
case "PredictedRating":
requests = sortableParams.OrderByAscending ?
requests.OrderBy(r => r.Book.PredictedRating) :
requests.OrderByDescending(r => r.Book.PredictedRating);
break;
case "WishCount":
requests = sortableParams.OrderByAscending ?
requests.OrderBy(r => r.Book.WishCount) :
requests.OrderByDescending(r => r.Book.WishCount);
break;
}
return requests;
}
/// <inheritdoc />
public async Task<bool> ApproveReceiveAsync(int id)
{
var request = await _requestRepository.GetAll()
.Include(x => x.Book)
.Include(x => x.User)
.Include(x => x.Owner)
.FirstOrDefaultAsync(x => x.Id == id);
if (request == null)
{
return false;
}
var book = await _bookRepository.FindByIdAsync(request.BookId);
book.User = request.User;
book.State = BookState.Reading;
_bookRepository.Update(book);
await _bookRepository.SaveChangesAsync();
request.ReceiveDate = DateTime.UtcNow;
_requestRepository.Update(request);
var affectedRows = await _requestRepository.SaveChangesAsync();
if (request.Owner.IsEmailAllowed)
{
var emailMessage = new RequestMessage()
{
OwnerName = request.Owner.FirstName + " " + request.Owner.LastName,
BookName = request.Book.Name,
RequestId = request.Id,
UserName = request.User.FirstName + " " + request.User.LastName,
OwnerAddress = new MailboxAddress($"{request.Owner.Email}")
};
await _emailSenderService.SendThatBookWasReceivedToPreviousOwnerAsync(emailMessage);
}
if (request.User.IsEmailAllowed)
{
var emailMessage = new RequestMessage()
{
OwnerName = request.User.FirstName + " " + request.User.LastName,
BookName = request.Book.Name,
RequestId = request.Id,
OwnerAddress = new MailboxAddress($"{request.User.Email}")
};
await _emailSenderService.SendThatBookWasReceivedToNewOwnerAsync(emailMessage);
}
await _notificationsService.NotifyAsync(
request.Owner.Id,
$"{request.User.FirstName} {request.User.LastName} has successfully received and started reading '{book.Name}'.",
$"Користувач {request.User.FirstName} {request.User.LastName} успішно отримав '{book.Name} та розпочав процес читання",
book.Id,
NotificationActions.Open);
await _notificationsService.NotifyAsync(
request.User.Id,
$"You became a current owner of the book '{book.Name}'",
$"Ви стали поточним власником книги '{book.Name}'",
book.Id,
NotificationActions.Open);
await _hangfireJobScheduleService.DeleteRequestScheduleJob(id);
return affectedRows > 0;
}
/// <inheritdoc />
public async Task<bool> RemoveAsync(int requestId)
{
var request = await _requestRepository.GetAll()
.Include(x => x.Book)
.Include(x => x.Owner)
.Include(x => x.User)
.FirstOrDefaultAsync(x => x.Id == requestId);
if (request == null)
{
return false;
}
await _hangfireJobScheduleService.DeleteRequestScheduleJob(requestId);
if (request.Owner.IsEmailAllowed)
{
var emailMessage = new RequestMessage()
{
UserName = request.User.FirstName + " " + request.User.LastName,
OwnerName = request.Owner.FirstName + " " + request.Owner.LastName,
BookName = request.Book.Name,
RequestId = request.Id,
OwnerAddress = new MailboxAddress($"{request.Owner.Email}")
};
await _emailSenderService.SendForCanceledRequestAsync(emailMessage);
}
await _notificationsService.NotifyAsync(
request.Owner.Id,
$"Your book '{request.Book.Name}' request was canceled.",
$"Ваш запит щодо книги '{request.Book.Name}' скасовано",
request.BookId,
NotificationActions.Open);
await _notificationsService.NotifyAsync(
request.User.Id,
$"Your request for book '{request.Book.Name}' was canceled.",
$"Ваш запит щодо книги '{request.Book.Name}' скасовано",
request.BookId,
NotificationActions.Open);
var book = await _bookRepository.FindByIdAsync(request.BookId);
book.State = BookState.Available;
var isBookUpdated = await _bookRepository.SaveChangesAsync() > 0;
if (isBookUpdated)
{
await _wishListService.NotifyAboutAvailableBookAsync(book.Id);
}
_requestRepository.Remove(request);
var affectedRows = await _requestRepository.SaveChangesAsync();
return affectedRows > 0;
}
public async Task<int> GetNumberOfRequestedBooksAsync(int userId)
{
return await _requestRepository.GetAll().Where(r => r.UserId == userId && r.ReceiveDate == null).CountAsync();
}
}
}
| 42.638955 | 136 | 0.535458 | [
"MIT"
] | ita-social-projects/Bookcrossing-Back-End | src/Application/Services/Implementation/RequestService.cs | 18,138 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Registry.Services {
using Microsoft.Azure.IIoT.OpcUa.Registry.Models;
using Microsoft.Azure.IIoT.Exceptions;
using Microsoft.Azure.IIoT.Hub;
using Microsoft.Azure.IIoT.Hub.Mock;
using Microsoft.Azure.IIoT.Hub.Models;
using Microsoft.Azure.IIoT.Serializers.NewtonSoft;
using Microsoft.Azure.IIoT.Serializers;
using Autofac.Extras.Moq;
using AutoFixture;
using AutoFixture.Kernel;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Autofac;
public class DiscovererRegistryTests {
[Fact]
public void GetDiscovererThatDoesNotExist() {
CreateDiscovererFixtures(out _, out _, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var t = service.GetDiscovererAsync("test");
// Assert
Assert.NotNull(t.Exception);
Assert.IsType<AggregateException>(t.Exception);
Assert.IsType<ResourceNotFoundException>(t.Exception.InnerException);
}
}
[Fact]
public void GetDiscovererThatExists() {
CreateDiscovererFixtures(out _, out var discoverers, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var result = service.GetDiscovererAsync(discoverers.First().Id).Result;
// Assert
Assert.True(result.IsSameAs(discoverers.First()));
}
}
[Fact]
public void ListAllDiscoverers() {
CreateDiscovererFixtures(out _, out var discoverers, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var records = service.ListDiscoverersAsync(null, null).Result;
// Assert
Assert.True(discoverers.IsSameAs(records.Items));
}
}
[Fact]
public void ListAllDiscoverersUsingQuery() {
CreateDiscovererFixtures(out _, out var discoverers, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var records = service.QueryDiscoverersAsync(null, null).Result;
// Assert
Assert.True(discoverers.IsSameAs(records.Items));
}
}
[Fact]
public void QueryDiscoverersByDiscoveryMode() {
CreateDiscovererFixtures(out var site, out var discoverers, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var records = service.QueryDiscoverersAsync(new DiscovererQueryModel {
Discovery = DiscoveryMode.Network
}, null).Result;
// Assert
Assert.True(records.Items.Count == discoverers.Count(x => x.RequestedMode == DiscoveryMode.Network));
}
}
[Fact]
public void QueryDiscoverersBySiteId() {
CreateDiscovererFixtures(out var site, out var discoverers, out var modules);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var records = service.QueryDiscoverersAsync(new DiscovererQueryModel {
SiteId = site
}, null).Result;
// Assert
Assert.True(discoverers.IsSameAs(records.Items));
}
}
[Fact]
public void QueryDiscoverersByNoneExistantSiteId() {
CreateDiscovererFixtures(out _, out _, out var modules, true);
using (var mock = AutoMock.GetLoose(builder => {
var hub = IoTHubServices.Create(modules);
builder.RegisterType<NewtonSoftJsonConverters>().As<IJsonSerializerConverterProvider>();
builder.RegisterType<NewtonSoftJsonSerializer>().As<IJsonSerializer>();
builder.RegisterInstance(hub).As<IIoTHubTwinServices>();
})) {
IDiscovererRegistry service = mock.Create<DiscovererRegistry>();
// Run
var records = service.QueryDiscoverersAsync(new DiscovererQueryModel {
SiteId = "test"
}, null).Result;
// Assert
Assert.True(records.Items.Count == 0);
}
}
/// <summary>
/// Helper to create app fixtures
/// </summary>
/// <param name="site"></param>
/// <param name="discoverers"></param>
/// <param name="modules"></param>
private void CreateDiscovererFixtures(out string site,
out List<DiscovererModel> discoverers, out List<(DeviceTwinModel, DeviceModel)> modules,
bool noSite = false) {
var fix = new Fixture();
fix.Customizations.Add(new TypeRelay(typeof(VariantValue), typeof(VariantValue)));
fix.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
.ForEach(b => fix.Behaviors.Remove(b));
fix.Behaviors.Add(new OmitOnRecursionBehavior());
var sitex = site = noSite ? null : fix.Create<string>();
discoverers = fix
.Build<DiscovererModel>()
.With(x => x.SiteId, sitex)
.Without(x => x.Id)
.Do(x => x.Id = DiscovererModelEx.CreateDiscovererId(
fix.Create<string>(), fix.Create<string>()))
.CreateMany(10)
.ToList();
modules = discoverers
.Select(a => {
var r = a.ToDiscovererRegistration();
r._desired = r;
return r;
})
.Select(a => a.ToDeviceTwin(_serializer))
.Select(t => {
t.Properties.Reported = new Dictionary<string, VariantValue> {
[TwinProperty.Type] = IdentityType.Discoverer
};
return t;
})
.Select(t => (t, new DeviceModel { Id = t.Id, ModuleId = t.ModuleId }))
.ToList();
}
private readonly IJsonSerializer _serializer = new NewtonSoftJsonSerializer();
}
}
| 42.382488 | 117 | 0.572904 | [
"MIT"
] | GBBBAS/Industrial-IoT | components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa.Registry/tests/Services/DiscovererRegistryTests.cs | 9,197 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Query.Library;
using System.Diagnostics;
using System.Collections;
namespace Query.Tests
{
[TestClass]
public class BuilderTests
{
private Builder _builder;
#region Range
public BuilderTests()
{
//Arrange
_builder = new Builder();
}
[TestMethod]
public void BuildInegerSequence()
{
//Act
var list = _builder.BuildIntegerSequence();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void BuildArithmenticInegerSequence()
{
//Act
var list = _builder.BuildArithemticIntegerSequence();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void BuildStringInegerSequence()
{
//Act
var list = _builder.BuildStringSequence();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void BuildRandomInegerSequence()
{
//Act
var list = _builder.BuildRandomSequence();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
#endregion
#region Repeat
[TestMethod]
public void BuildRepeatedInegerSequence()
{
//Act
var list = _builder.BuildIntegerSequence(true);
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void BuildRepeatedStringSequence()
{
//Act
var list = _builder.BuildStringSequence(true);
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
#endregion
#region Compare
[TestMethod]
public void Intersect()
{
//Act
var list = _builder.IntersectSequences();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void Concat()
{
//Act
var list = _builder.ConcatSequences();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
[TestMethod]
public void ConcatUnique()
{
//Act
var list = _builder.ConcatUniqueSequences();
//Analyze
foreach (var item in list)
{
Debug.WriteLine(item);
}
//Assert
Assert.IsNotNull(list);
}
#endregion
}
}
| 22.02439 | 65 | 0.453488 | [
"MIT"
] | patrickCode/C-Sharp | LinqProgramming/Query.Tests/BuilderTests.cs | 3,614 | C# |
using MathNet.Numerics.LinearAlgebra;
using MathNet.Spatial.Euclidean;
using NUnit.Framework;
namespace MathNet.Spatial.UnitTests
{
public static class AssertGeometry
{
public static void AreEqual(CoordinateSystem coordinateSystem, Point3D origin, Vector3D xAxis, Vector3D yAxis, Vector3D zAxis, double tolerance = 1e-6)
{
AreEqual(xAxis, coordinateSystem.XAxis, tolerance);
AreEqual(yAxis, coordinateSystem.YAxis, tolerance);
AreEqual(zAxis, coordinateSystem.ZAxis, tolerance);
AreEqual(origin, coordinateSystem.Origin, tolerance);
AreEqual(new double[] { xAxis.X, xAxis.Y, xAxis.Z, 0 }, coordinateSystem.Column(0).ToArray(), tolerance);
AreEqual(new double[] { yAxis.X, yAxis.Y, yAxis.Z, 0 }, coordinateSystem.Column(1).ToArray(), tolerance);
AreEqual(new double[] { zAxis.X, zAxis.Y, zAxis.Z, 0 }, coordinateSystem.Column(2).ToArray(), tolerance);
AreEqual(new double[] { origin.X, origin.Y, origin.Z, 1 }, coordinateSystem.Column(3).ToArray(), tolerance);
}
public static void AreEqual(UnitVector3D expected, UnitVector3D actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
Assert.AreEqual(expected.X, actual.X, tolerance, message);
Assert.AreEqual(expected.Y, actual.Y, tolerance, message);
Assert.AreEqual(expected.Z, actual.Z, tolerance, message);
}
public static void AreEqual(Vector3D expected, Vector3D actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
Assert.AreEqual(expected.X, actual.X, tolerance, message);
Assert.AreEqual(expected.Y, actual.Y, tolerance, message);
Assert.AreEqual(expected.Z, actual.Z, tolerance, message);
}
public static void AreEqual(UnitVector3D expected, Vector3D actual, double tolerance = 1e-6, string message = "")
{
AreEqual(expected.ToVector3D(), actual, tolerance, message);
}
public static void AreEqual(Vector3D expected, UnitVector3D actual, double tolerance = 1e-6, string message = "")
{
AreEqual(expected, actual.ToVector3D(), tolerance, message);
}
public static void AreEqual(Vector2D expected, Vector2D actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
Assert.AreEqual(expected.X, actual.X, tolerance, message);
Assert.AreEqual(expected.Y, actual.Y, tolerance, message);
}
public static void AreEqual(Point3D expected, Point3D actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
Assert.AreEqual(expected.X, actual.X, tolerance, message);
Assert.AreEqual(expected.Y, actual.Y, tolerance, message);
Assert.AreEqual(expected.Z, actual.Z, tolerance, message);
}
public static void AreEqual(CoordinateSystem expected, CoordinateSystem actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
if (expected.Values.Length != actual.Values.Length)
{
Assert.Fail();
}
for (var i = 0; i < expected.Values.Length; i++)
{
Assert.AreEqual(expected.Values[i], actual.Values[i], tolerance);
}
}
public static void AreEqual(double[] expected, double[] actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", "{" + string.Join(",", expected) + "}", "{" + string.Join(",", actual) + "}");
}
if (expected.Length != actual.Length)
{
Assert.Fail();
}
for (var i = 0; i < expected.Length; i++)
{
Assert.AreEqual(expected[i], actual[i], tolerance);
}
}
public static void AreEqual(Line3D expected, Line3D actual, double tolerance = 1e-6)
{
AreEqual(expected.StartPoint, actual.StartPoint, tolerance);
AreEqual(expected.EndPoint, actual.EndPoint, tolerance);
}
public static void AreEqual(LineSegment3D expected, LineSegment3D actual, double tolerance = 1e-6)
{
AreEqual(expected.StartPoint, actual.StartPoint, tolerance);
AreEqual(expected.EndPoint, actual.EndPoint, tolerance);
}
public static void AreEqual(Ray3D expected, Ray3D actual, double tolerance = 1e-6, string message = "")
{
AreEqual(expected.ThroughPoint, actual.ThroughPoint, tolerance, message);
AreEqual(expected.Direction, actual.Direction, tolerance, message);
}
public static void AreEqual(Plane expected, Plane actual, double tolerance = 1e-6, string message = "")
{
AreEqual(expected.Normal, actual.Normal, tolerance, message);
AreEqual(expected.RootPoint, actual.RootPoint, tolerance, message);
Assert.AreEqual(expected.D, actual.D, tolerance, message);
}
public static void AreEqual(Matrix<double> expected, Matrix<double> actual, double tolerance = 1e-6)
{
Assert.AreEqual(expected.RowCount, actual.RowCount);
Assert.AreEqual(expected.ColumnCount, actual.ColumnCount);
var expectedRowWiseArray = expected.ToRowMajorArray();
var actualRowWiseArray = actual.ToRowMajorArray();
for (var i = 0; i < expectedRowWiseArray.Length; i++)
{
Assert.AreEqual(expectedRowWiseArray[i], actualRowWiseArray[i], tolerance);
}
}
public static void AreEqual(Point2D expected, Point2D actual, double tolerance = 1e-6, string message = "")
{
if (string.IsNullOrEmpty(message))
{
message = string.Format("Expected {0} but was {1}", expected, actual);
}
Assert.AreEqual(expected.X, actual.X, tolerance, message);
Assert.AreEqual(expected.Y, actual.Y, tolerance, message);
}
}
}
| 42.493902 | 159 | 0.596212 | [
"MIT"
] | 3dsoft/mathnet-spatial | src/Spatial.Tests/Helpers/AssertGeometry.cs | 6,969 | C# |
using System;
using System.Linq;
class Program
{
static void Main()
{
var input = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(long.Parse)
.ToList();
bool hasSummed = true;
while (hasSummed)
{
hasSummed = false;
int index = 0;
long sum = 0;
for (int i = 1; i < input.Count; i++)
{
if (input[i] == input[i - 1])
{
index = i - 1;
sum = input[i] + input[i - 1];
hasSummed = true;
break;
}
}
if (hasSummed)
{
input.RemoveRange(index, 2);
input.Insert(index, sum);
}
}
Console.WriteLine(string.Join(" ", input));
}
}
| 22.575 | 120 | 0.404208 | [
"MIT"
] | karaivanska/Programming-Fundamentals | Ext-Lists-Lab/sumAdjacentEqualNumbers/Program.cs | 905 | C# |
using System;
using System.CodeDom.Compiler;
using System.Dynamic;
using System.Collections.Generic;
using TobascoTest.TestEnums;
namespace TobascoTest.GeneratedEntity
{
[GeneratedCode("Tobasco", "1.0.0.0")]
[Serializable]
public partial class CPK8 : DifferentBase
{
private string _training;
public string Training
{
get { return _training; }
set { SetField(ref _training, value, nameof(Training)); }
}
private string _duur;
public string Duur
{
get { return _duur; }
set { SetField(ref _duur, value, nameof(Duur)); }
}
private string _kosten;
public string Kosten
{
get { return _kosten; }
set { SetField(ref _kosten, value, nameof(Kosten)); }
}
public override ExpandoObject ToAnonymous()
{
dynamic anymonous = base.ToAnonymous();
anymonous.Training = Training;
anymonous.Duur = Duur;
anymonous.Kosten = Kosten;
return anymonous;
}
public override IEnumerable<EntityBase> GetChildren()
{
foreach (var item in base.GetChildren())
{
yield return item;
}
}
}
} | 20.77551 | 58 | 0.717092 | [
"Apache-2.0"
] | VictordeBaare/Tobasco | TobascoTest/GeneratedEntity/CPK8_Generated.cs | 1,020 | C# |
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.ComponentModel;
namespace ResourceTypes.Wwise.Helpers
{
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Layer
{
public uint ID { get; set; }
public List<RTPC> rtpc { get; set; } //0x00 = Exclusive, 0x01 = Additive
public uint rtpcID { get; set; }
public byte rtpcType { get; set; }
public List<Assoc> Associates { get; set; }
public Layer(BinaryReader br)
{
ID = br.ReadUInt32();
int rtpcCount = br.ReadUInt16();
rtpc = new List<RTPC>();
for (int i = 0; i < rtpcCount; i++)
{
rtpc.Add(new RTPC(br));
}
rtpcID = br.ReadUInt32();
rtpcType = br.ReadByte();
Associates = new List<Assoc>();
uint numAssoc = br.ReadUInt32();
for (int i = 0; i < numAssoc; i++)
{
Associates.Add(new Assoc(br));
}
}
public Layer()
{
ID = 0;
rtpc = new List<RTPC>();
rtpcID = 0;
rtpcType = 0;
Associates = new List<Assoc>();
}
public static void WriteLayer(BinaryWriter bw, Layer layer)
{
bw.Write(layer.ID);
bw.Write((short)layer.rtpc.Count);
foreach (RTPC value in layer.rtpc)
{
value.WriteToFile(bw);
}
bw.Write(layer.rtpcID);
bw.Write(layer.rtpcType);
bw.Write(layer.Associates.Count);
foreach (Assoc assoc in layer.Associates)
{
Assoc.WriteAssoc(bw, assoc);
}
}
public int GetLength()
{
int Length = 15;
foreach (RTPC value in rtpc)
{
Length += value.GetLength();
}
foreach (Assoc value in Associates)
{
Length += value.GetLength();
}
return Length;
}
}
}
| 25.149425 | 80 | 0.474863 | [
"MIT"
] | Greavesy1899/Mafia2Toolk | Mafia2Libs/ResourceTypes/FileTypes/Wwise/HIRC/Helpers/HIRC_Layer.cs | 2,190 | C# |
using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Jobs()
{
return View(JobManager.AllSchedules);
}
public async Task<IActionResult> Users()
{
var soldiers_with_access =
await db
.Soldiers
.Include(soldier => soldier.Unit)
.Where(soldier => soldier.CanLogin)
.Where(soldier => !String.IsNullOrWhiteSpace(soldier.CivilianEmail))
.Select(soldier => new
{
Uri = Url.RouteUrl("Soldier.Details", new { soldier.Id }, Request.Scheme),
Unit = soldier.Unit.Name,
soldier.FirstName,
soldier.LastName,
soldier.CivilianEmail
})
.ToListAsync();
return Json(soldiers_with_access);
}
}
}
| 26.532258 | 94 | 0.545289 | [
"MIT"
] | mattgwagner/Battery-Commander | Battery-Commander.Web/Controllers/AdminController.cs | 1,647 | 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.Collections.Generic;
using System.Reflection;
using Microsoft.AspNet.Mvc.ModelBinding;
namespace Microsoft.AspNet.Mvc.ApplicationModels
{
public class ParameterModel
{
public ParameterModel([NotNull] ParameterInfo parameterInfo,
[NotNull] IReadOnlyList<object> attributes)
{
ParameterInfo = parameterInfo;
Attributes = new List<object>(attributes);
}
public ParameterModel([NotNull] ParameterModel other)
{
Action = other.Action;
Attributes = new List<object>(other.Attributes);
BinderMetadata = other.BinderMetadata;
IsOptional = other.IsOptional;
ParameterInfo = other.ParameterInfo;
ParameterName = other.ParameterName;
}
public ActionModel Action { get; set; }
public IReadOnlyList<object> Attributes { get; }
public IBinderMetadata BinderMetadata { get; set; }
public bool IsOptional { get; set; }
public ParameterInfo ParameterInfo { get; private set; }
public string ParameterName { get; set; }
}
} | 32.071429 | 111 | 0.650334 | [
"Apache-2.0"
] | moljac/Mvc | src/Microsoft.AspNet.Mvc.Core/ApplicationModels/ParameterModel.cs | 1,349 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// ChargeItems Data Structure.
/// </summary>
[Serializable]
public class ChargeItems : AopObject
{
/// <summary>
/// 缴费项是否必选 如果缴费项是多选模式,此参数生效。 “Y”表示必填,“N”或空表示非必填。
/// </summary>
[XmlElement("item_mandatory")]
public string ItemMandatory { get; set; }
/// <summary>
/// 缴费项最大可选数 如果缴费项是多选模式,此参数生效,范围是1-9,如果为空,则最大项默认为9
/// </summary>
[XmlElement("item_maximum")]
public long ItemMaximum { get; set; }
/// <summary>
/// 缴费项名称
/// </summary>
[XmlElement("item_name")]
public string ItemName { get; set; }
/// <summary>
/// 缴费项金额
/// </summary>
[XmlElement("item_price")]
public string ItemPrice { get; set; }
/// <summary>
/// 缴费项序号,如果缴费项是多选模式,此项为必填,建议从1开始的连续数字, 用户支付成功后,通过passback_params参数带回已选择的缴费项。例如:orderNo=uoo234234&isvOrderNo=24werwe&items=1-2|2-1|3-5 1-2|2-1|3-5 表示:缴费项序列号-缴费项数|缴费项序列号-缴费项数
/// </summary>
[XmlElement("item_serial_number")]
public long ItemSerialNumber { get; set; }
}
}
| 29.232558 | 184 | 0.549722 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/ChargeItems.cs | 1,603 | C# |
using System.Web;
using System.Web.Mvc;
namespace ProductManagerMVC
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.285714 | 80 | 0.662963 | [
"MIT"
] | CriticalPathTraining/CBD365 | Modules/03_MvcWebApps/Lab/Solution/ProductManagerMVC/ProductManagerMVC/App_Start/FilterConfig.cs | 272 | C# |
//-----------------------------------------------------------------------
// <copyright file="DeviceOrientationInit.cs" company="Google LLC">
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A class for storing the initial device orientation state.
/// </summary>
public class DeviceOrientationInit : MonoBehaviour
{
/// <summary>
/// Instance of the initial device orientation state.
/// </summary>
public static DeviceOrientation DeviceOrientationInstance;
/// <summary>
/// Flag to enable UI rotation at app initialization.
/// </summary>
public bool EnableRotation = false;
// Start is called before the first frame update
private void Start()
{
if (EnableRotation)
{
DeviceOrientationInstance = Input.deviceOrientation;
}
else
{
DeviceOrientationInstance = DeviceOrientation.Portrait;
}
}
}
| 31.132075 | 75 | 0.629091 | [
"Apache-2.0"
] | AgrMayank/ARCore-Raw-Depth-API | Assets/ARRealismDemos/DemoCarousel/Scripts/DeviceOrientationInit.cs | 1,650 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Toolkit.Win32.UI.Controls.Test.WebView.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Should;
namespace Microsoft.Toolkit.Win32.UI.Controls.Test.WinForms.WebView.FunctionalTests.Navigation
{
[TestClass]
[TestCategory(TestConstants.Categories.Nav)]
public class HTTP_GET : HostFormWebViewContextSpecification
{
private bool _success;
protected override void Given()
{
base.Given();
WebView.NavigationCompleted += (o, e) =>
{
_success = e.IsSuccess;
Form.Close();
};
}
protected override void When()
{
NavigateAndWaitForFormClose(TestConstants.Uris.ExampleCom, HttpMethod.Get);
}
[TestMethod]
[Timeout(TestConstants.Timeouts.Longest)]
public void NavigationShouldComplete()
{
_success.ShouldBeTrue();
}
}
[TestClass]
[TestCategory(TestConstants.Categories.Nav)]
public class HTTP_POST : HostFormWebViewContextSpecification
{
private bool _success;
private Uri _uri = new Uri(TestConstants.Uris.HttpBin, "/post");
protected override void Given()
{
base.Given();
WebView.NavigationCompleted += (o, e) =>
{
_success = e.IsSuccess;
Form.Close();
};
}
protected override void When()
{
NavigateAndWaitForFormClose(
_uri,
HttpMethod.Post,
"{\"prop\":\"content\"}",
new []{new KeyValuePair<string, string>("accept", "application/json"), });
}
[TestMethod]
[Timeout(TestConstants.Timeouts.Longest)]
public void NavigationShouldComplete()
{
_success.ShouldBeTrue();
}
}
[TestClass]
[TestCategory(TestConstants.Categories.Nav)]
public class HTTP_POST_CONTENT : HostFormWebViewContextSpecification
{
private bool _success;
private Uri _uri = new Uri(TestConstants.Uris.HttpBin, "/post");
protected override void Given()
{
base.Given();
WebView.NavigationCompleted += (o, e) =>
{
_success = e.IsSuccess;
Form.Close();
};
}
protected override void When()
{
NavigateAndWaitForFormClose(
_uri,
HttpMethod.Post,
"say=Hello&to=World",
new[] { new KeyValuePair<string, string>("Content-Type", "application/x-www-form-urlencoded"), });
}
[TestMethod]
[Timeout(TestConstants.Timeouts.Longest)]
public void NavigationShouldComplete()
{
_success.ShouldBeTrue();
}
}
}
| 28.097345 | 114 | 0.573228 | [
"MIT"
] | devsko/Microsoft.Toolkit.Win32 | Tests/UnitTests.WebView.WinForms/FunctionalTests/Navigation/NavigateWithHttpMessageTests.cs | 3,175 | C# |
// THIS FILE IS A PART OF EMZI0767'S BOT EXAMPLES
//
// --------
//
// Copyright 2019 Emzi0767
//
// 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.
//
// --------
//
// This is a WinForms example. It shows how to use WinForms without deadlocks.
using System.Diagnostics;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.EventArgs;
using Microsoft.Extensions.Logging;
namespace DSPlus.Examples
{
// this class holds the bot itself
// this is simply used as a sort of container to keep the code organized
// and partially separated from the form
public class Bot
{
// the client instance, this is initialized with the class
public DiscordClient Client { get; }
// this instantiates the container class and the client
public Bot(string token)
{
// create config from the supplied token
var cfg = new DiscordConfiguration
{
Token = token, // use the supplied token
TokenType = TokenType.Bot, // log in as a bot
AutoReconnect = true, // reconnect automatically
MinimumLogLevel = LogLevel.Debug
};
// initialize the client
this.Client = new DiscordClient(cfg);
}
// this method logs in and starts the client
public Task StartAsync()
=> this.Client.ConnectAsync();
// this method logs out and stops the client
public Task StopAsync()
=> this.Client.DisconnectAsync();
}
}
| 32.2 | 78 | 0.636885 | [
"Apache-2.0"
] | Kiritsu/DSharpPlus-Examples-4.0 | DSPlus.Examples.CSharp.Ex05/Bot.cs | 2,095 | C# |
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Core.Psi.Modules;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api;
using JetBrains.ReSharper.Plugins.Unity.Yaml;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AnimatorUsages;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Analysis
{
[ElementProblemAnalyzer(typeof(IInvocationExpression),
HighlightingTypes = new[] {typeof(UnknownAnimatorStateNameWarning)})]
public class PlayAnimatorStateAnalyzer : UnityElementProblemAnalyzer<IInvocationExpression>
{
private readonly AssetIndexingSupport myAssetIndexingSupport;
private readonly AssetSerializationMode myAssetSerializationMode;
public PlayAnimatorStateAnalyzer(UnityApi unityApi,
AssetIndexingSupport assetIndexingSupport,
AssetSerializationMode assetSerializationMode)
: base(unityApi)
{
myAssetIndexingSupport = assetIndexingSupport;
myAssetSerializationMode = assetSerializationMode;
}
protected override void Analyze([NotNull] IInvocationExpression invocation,
ElementProblemAnalyzerData data,
[NotNull] IHighlightingConsumer consumer)
{
if (!myAssetSerializationMode.IsForceText || !myAssetIndexingSupport.IsEnabled.Value) return;
var argument = GetStateNameArgumentFrom(invocation);
if (!(argument?.Value is ICSharpLiteralExpression literal) ||
!invocation.InvocationExpressionReference.IsAnimatorPlayMethod()) return;
var container = invocation.GetSolution().TryGetComponent<AnimatorScriptUsagesElementContainer>();
if (container == null ||
!(literal.ConstantValue.Value is string stateName) ||
container.ContainsStateName(stateName)) return;
consumer.AddHighlighting(new UnknownAnimatorStateNameWarning(argument));
}
[CanBeNull]
private static ICSharpArgument GetStateNameArgumentFrom([NotNull] IInvocationExpression invocationExpression)
{
return invocationExpression
.ArgumentList?
.Arguments
.FirstOrDefault(t =>
t != null &&
(t.IsNamedArgument && t.ArgumentName?.Equals("stateName") == true || !t.IsNamedArgument));
}
}
} | 48.666667 | 117 | 0.682048 | [
"Apache-2.0"
] | SirDuke/resharper-unity | resharper/resharper-unity/src/Unity/CSharp/Daemon/Stages/Analysis/PlayAnimatorStateAnalyzer.cs | 2,774 | C# |
using System;
namespace Maple.Core
{
/// <summary>
/// Messenger hub responsible for taking subscriptions/publications and delivering of messages.
/// </summary>
public interface IMessenger
{
/// <summary>
/// Subscribe to a message type with the given destination and delivery action.
/// All references are held with WeakReferences
///
/// All messages of this type will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action.
/// Messages will be delivered via the specified proxy.
/// All references (apart from the proxy) are held with WeakReferences
///
/// All messages of this type will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="proxy">Proxy to use when delivering the messages</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, IMapleMessageProxy proxy) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action.
///
/// All messages of this type will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="useStrongReferences">Use strong references to destination and deliveryAction </param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, bool useStrongReferences) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action.
/// Messages will be delivered via the specified proxy.
///
/// All messages of this type will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="useStrongReferences">Use strong references to destination and deliveryAction </param>
/// <param name="proxy">Proxy to use when delivering the messages</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, bool useStrongReferences, IMapleMessageProxy proxy) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action with the given filter.
/// All references are held with WeakReferences
///
/// Only messages that "pass" the filter will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, Func<TMessage, bool> messageFilter) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action with the given filter.
/// Messages will be delivered via the specified proxy.
/// All references (apart from the proxy) are held with WeakReferences
///
/// Only messages that "pass" the filter will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="proxy">Proxy to use when delivering the messages</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, Func<TMessage, bool> messageFilter, IMapleMessageProxy proxy) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action with the given filter.
/// All references are held with WeakReferences
///
/// Only messages that "pass" the filter will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="useStrongReferences">Use strong references to destination and deliveryAction </param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, Func<TMessage, bool> messageFilter, bool useStrongReferences) where TMessage : class, IMapleMessage;
/// <summary>
/// Subscribe to a message type with the given destination and delivery action with the given filter.
/// Messages will be delivered via the specified proxy.
/// All references are held with WeakReferences
///
/// Only messages that "pass" the filter will be delivered.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="deliveryAction">Action to invoke when message is delivered</param>
/// <param name="useStrongReferences">Use strong references to destination and deliveryAction </param>
/// <param name="proxy">Proxy to use when delivering the messages</param>
/// <returns>TinyMessageSubscription used to unsubscribing</returns>
SubscriptionToken Subscribe<TMessage>(Action<TMessage> deliveryAction, Func<TMessage, bool> messageFilter, bool useStrongReferences, IMapleMessageProxy proxy) where TMessage : class, IMapleMessage;
/// <summary>
/// Unsubscribe from a particular message type.
///
/// Does not throw an exception if the subscription is not found.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="subscriptionToken">Subscription token received from Subscribe</param>
void Unsubscribe<TMessage>(SubscriptionToken subscriptionToken) where TMessage : class, IMapleMessage;
/// <summary>
/// Publish a message to any subscribers
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="message">Message to deliver</param>
void Publish<TMessage>(TMessage message) where TMessage : class, IMapleMessage;
/// <summary>
/// Publish a message to any subscribers asynchronously
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="message">Message to deliver</param>
void PublishAsync<TMessage>(TMessage message) where TMessage : class, IMapleMessage;
/// <summary>
/// Publish a message to any subscribers asynchronously
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <param name="message">Message to deliver</param>
/// <param name="callback">AsyncCallback called on completion</param>
void PublishAsync<TMessage>(TMessage message, AsyncCallback callback) where TMessage : class, IMapleMessage;
}
}
| 57.907143 | 205 | 0.674109 | [
"MIT"
] | Insire/InsireBot-V2 | src/Maple.Core/EventAggregator/Interfaces/IMessenger.cs | 8,109 | C# |
// Copyright (c) 2020 stakx
// License available at https://github.com/stakx/DynamicProxy.AsyncInterceptor/blob/master/LICENSE.md.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Castle.DynamicProxy
{
partial class AsyncInterceptor
{
private sealed class AsyncStateMachine : IAsyncStateMachine
{
private readonly IAsyncInvocation asyncInvocation;
private readonly object builder;
private readonly ValueTask task;
public AsyncStateMachine(IAsyncInvocation asyncInvocation, object builder, ValueTask task)
{
this.asyncInvocation = asyncInvocation;
this.builder = builder;
this.task = task;
}
public void MoveNext()
{
try
{
var awaiter = this.task.GetAwaiter();
if (awaiter.IsCompleted)
{
awaiter.GetResult();
// TODO: validate `asyncInvocation.Result` against `asyncInvocation.Method.ReturnType`!
this.builder.SetResult(asyncInvocation.Result);
}
else
{
this.builder.AwaitOnCompleted(awaiter, this);
}
}
catch (TargetInvocationException ex)
{
this.builder.SetException(ex.InnerException);
}
catch (Exception exception)
{
this.builder.SetException(exception);
}
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}
} | 31.982759 | 111 | 0.521833 | [
"MIT"
] | yuzd/Autofac.Annotation | src/Intercepter/AsyncInterceptor+AsyncStateMachine.cs | 1,855 | C# |
using System;
namespace VidDownloader
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault( false );
System.Windows.Forms.Application.Run( new Form1() );
}
}
}
| 24.631579 | 88 | 0.589744 | [
"Apache-2.0"
] | MeowthK/Youtube-DL-GUI | VidDownloader/Program.cs | 470 | 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 acm-pca-2017-08-22.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.ACMPCA.Model;
namespace Amazon.ACMPCA
{
/// <summary>
/// Interface for accessing ACMPCA
///
/// This is the <i>ACM Private CA API Reference</i>. It provides descriptions, syntax,
/// and usage examples for each of the actions and data types involved in creating and
/// managing private certificate authorities (CA) for your organization.
///
///
/// <para>
/// The documentation for each action shows the Query API request parameters and the XML
/// response. Alternatively, you can use one of the AWS SDKs to access an API that's tailored
/// to the programming language or platform that you're using. For more information, see
/// <a href="https://aws.amazon.com/tools/#SDKs">AWS SDKs</a>.
/// </para>
///
/// <para>
/// Each ACM Private CA API operation has a quota that determines the number of times
/// the operation can be called per second. ACM Private CA throttles API requests at different
/// rates depending on the operation. Throttling means that ACM Private CA rejects an
/// otherwise valid request because the request exceeds the operation's quota for the
/// number of requests per second. When a request is throttled, ACM Private CA returns
/// a <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/CommonErrors.html">ThrottlingException</a>
/// error. ACM Private CA does not guarantee a minimum request rate for APIs.
/// </para>
///
/// <para>
/// To see an up-to-date list of your ACM Private CA quotas, or to request a quota increase,
/// log into your AWS account and visit the <a href="https://console.aws.amazon.com/servicequotas/">Service
/// Quotas</a> console.
/// </para>
/// </summary>
public partial interface IAmazonACMPCA : IAmazonService, IDisposable
{
#if AWS_ASYNC_ENUMERABLES_API
/// <summary>
/// Paginators for the service
/// </summary>
IACMPCAPaginatorFactory Paginators { get; }
#endif
#region CreateCertificateAuthority
/// <summary>
/// Creates a root or subordinate private certificate authority (CA). You must specify
/// the CA configuration, an optional configuration for Online Certificate Status Protocol
/// (OCSP) and/or a certificate revocation list (CRL), the CA type, and an optional idempotency
/// token to avoid accidental creation of multiple CAs. The CA configuration specifies
/// the name of the algorithm and key size to be used to create the CA private key, the
/// type of signing algorithm that the CA uses, and X.500 subject information. The OCSP
/// configuration can optionally specify a custom URL for the OCSP responder. The CRL
/// configuration specifies the CRL expiration period in days (the validity period of
/// the CRL), the Amazon S3 bucket that will contain the CRL, and a CNAME alias for the
/// S3 bucket that is included in certificates issued by the CA. If successful, this action
/// returns the Amazon Resource Name (ARN) of the CA.
///
///
/// <para>
/// ACM Private CA assets that are stored in Amazon S3 can be protected with encryption.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaCreateCa.html#crl-encryption">Encrypting
/// Your CRLs</a>.
/// </para>
/// <note>
/// <para>
/// Both PCA and the IAM principal must have permission to write to the S3 bucket that
/// you specify. If the IAM principal making the call does not have permission to write
/// to the bucket, then an exception is thrown. For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaAuthAccess.html">Configure
/// Access to ACM Private CA</a>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthority 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 CreateCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException">
/// One or more of the specified arguments was not valid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidPolicyException">
/// The resource policy is invalid or is missing a required statement. For general information
/// about IAM policy and statement structure, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json">Overview
/// of JSON Policies</a>.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidTagException">
/// The tag associated with the CA is not valid. The invalid argument is contained in
/// the message field.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LimitExceededException">
/// An ACM Private CA quota has been exceeded. See the exception message returned to determine
/// the quota that was exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthority">REST API Reference for CreateCertificateAuthority Operation</seealso>
Task<CreateCertificateAuthorityResponse> CreateCertificateAuthorityAsync(CreateCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateCertificateAuthorityAuditReport
/// <summary>
/// Creates an audit report that lists every time that your CA private key is used. The
/// report is saved in the Amazon S3 bucket that you specify on input. The <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_IssueCertificate.html">IssueCertificate</a>
/// and <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_RevokeCertificate.html">RevokeCertificate</a>
/// actions use the private key.
///
/// <note>
/// <para>
/// Both PCA and the IAM principal must have permission to write to the S3 bucket that
/// you specify. If the IAM principal making the call does not have permission to write
/// to the bucket, then an exception is thrown. For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaAuthAccess.html">Configure
/// Access to ACM Private CA</a>.
/// </para>
/// </note>
/// <para>
/// ACM Private CA assets that are stored in Amazon S3 can be protected with encryption.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaAuditReport.html#audit-report-encryption">Encrypting
/// Your Audit Reports</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthorityAuditReport 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 CreateCertificateAuthorityAuditReport service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException">
/// One or more of the specified arguments was not valid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException">
/// Your request is already in progress.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReport">REST API Reference for CreateCertificateAuthorityAuditReport Operation</seealso>
Task<CreateCertificateAuthorityAuditReportResponse> CreateCertificateAuthorityAuditReportAsync(CreateCertificateAuthorityAuditReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreatePermission
/// <summary>
/// Grants one or more permissions on a private CA to the AWS Certificate Manager (ACM)
/// service principal (<code>acm.amazonaws.com</code>). These permissions allow ACM to
/// issue and renew ACM certificates that reside in the same AWS account as the CA.
///
///
/// <para>
/// You can list current permissions with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListPermissions.html">ListPermissions</a>
/// action and revoke them with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeletePermission.html">DeletePermission</a>
/// action.
/// </para>
/// <p class="title"> <b>About Permissions</b>
/// </para>
/// <ul> <li>
/// <para>
/// If the private CA and the certificates it issues reside in the same account, you can
/// use <code>CreatePermission</code> to grant permissions for ACM to carry out automatic
/// certificate renewals.
/// </para>
/// </li> <li>
/// <para>
/// For automatic certificate renewal to succeed, the ACM service principal needs permissions
/// to create, retrieve, and list certificates.
/// </para>
/// </li> <li>
/// <para>
/// If the private CA and the ACM certificates reside in different accounts, then permissions
/// cannot be used to enable automatic renewals. Instead, the ACM certificate owner must
/// set up a resource-based policy to enable cross-account issuance and renewals. For
/// more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePermission 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 CreatePermission service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LimitExceededException">
/// An ACM Private CA quota has been exceeded. See the exception message returned to determine
/// the quota that was exceeded.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.PermissionAlreadyExistsException">
/// The designated permission has already been given to the user.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreatePermission">REST API Reference for CreatePermission Operation</seealso>
Task<CreatePermissionResponse> CreatePermissionAsync(CreatePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteCertificateAuthority
/// <summary>
/// Deletes a private certificate authority (CA). You must provide the Amazon Resource
/// Name (ARN) of the private CA that you want to delete. You can find the ARN by calling
/// the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a>
/// action.
///
/// <note>
/// <para>
/// Deleting a CA will invalidate other CAs and certificates below it in your CA hierarchy.
/// </para>
/// </note>
/// <para>
/// Before you can delete a CA that you have created and activated, you must disable it.
/// To do this, call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_UpdateCertificateAuthority.html">UpdateCertificateAuthority</a>
/// action and set the <b>CertificateAuthorityStatus</b> parameter to <code>DISABLED</code>.
///
/// </para>
///
/// <para>
/// Additionally, you can delete a CA if you are waiting for it to be created (that is,
/// the status of the CA is <code>CREATING</code>). You can also delete it if the CA has
/// been created but you haven't yet imported the signed certificate into ACM Private
/// CA (that is, the status of the CA is <code>PENDING_CERTIFICATE</code>).
/// </para>
///
/// <para>
/// When you successfully call <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeleteCertificateAuthority.html">DeleteCertificateAuthority</a>,
/// the CA's status changes to <code>DELETED</code>. However, the CA won't be permanently
/// deleted until the restoration period has passed. By default, if you do not set the
/// <code>PermanentDeletionTimeInDays</code> parameter, the CA remains restorable for
/// 30 days. You can set the parameter from 7 to 30 days. The <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DescribeCertificateAuthority.html">DescribeCertificateAuthority</a>
/// action returns the time remaining in the restoration window of a private CA in the
/// <code>DELETED</code> state. To restore an eligible CA, call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_RestoreCertificateAuthority.html">RestoreCertificateAuthority</a>
/// action.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteCertificateAuthority 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 DeleteCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthority">REST API Reference for DeleteCertificateAuthority Operation</seealso>
Task<DeleteCertificateAuthorityResponse> DeleteCertificateAuthorityAsync(DeleteCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeletePermission
/// <summary>
/// Revokes permissions on a private CA granted to the AWS Certificate Manager (ACM) service
/// principal (acm.amazonaws.com).
///
///
/// <para>
/// These permissions allow ACM to issue and renew ACM certificates that reside in the
/// same AWS account as the CA. If you revoke these permissions, ACM will no longer renew
/// the affected certificates automatically.
/// </para>
///
/// <para>
/// Permissions can be granted with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreatePermission.html">CreatePermission</a>
/// action and listed with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListPermissions.html">ListPermissions</a>
/// action.
/// </para>
/// <p class="title"> <b>About Permissions</b>
/// </para>
/// <ul> <li>
/// <para>
/// If the private CA and the certificates it issues reside in the same account, you can
/// use <code>CreatePermission</code> to grant permissions for ACM to carry out automatic
/// certificate renewals.
/// </para>
/// </li> <li>
/// <para>
/// For automatic certificate renewal to succeed, the ACM service principal needs permissions
/// to create, retrieve, and list certificates.
/// </para>
/// </li> <li>
/// <para>
/// If the private CA and the ACM certificates reside in different accounts, then permissions
/// cannot be used to enable automatic renewals. Instead, the ACM certificate owner must
/// set up a resource-based policy to enable cross-account issuance and renewals. For
/// more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePermission 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 DeletePermission service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeletePermission">REST API Reference for DeletePermission Operation</seealso>
Task<DeletePermissionResponse> DeletePermissionAsync(DeletePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeletePolicy
/// <summary>
/// Deletes the resource-based policy attached to a private CA. Deletion will remove any
/// access that the policy has granted. If there is no policy attached to the private
/// CA, this action will return successful.
///
///
/// <para>
/// If you delete a policy that was applied through AWS Resource Access Manager (RAM),
/// the CA will be removed from all shares in which it was included.
/// </para>
///
/// <para>
/// The AWS Certificate Manager Service Linked Role that the policy supports is not affected
/// when you delete the policy.
/// </para>
///
/// <para>
/// The current policy can be shown with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetPolicy.html">GetPolicy</a>
/// and updated with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_PutPolicy.html">PutPolicy</a>.
/// </para>
/// <p class="title"> <b>About Policies</b>
/// </para>
/// <ul> <li>
/// <para>
/// A policy grants access on a private CA to an AWS customer account, to AWS Organizations,
/// or to an AWS Organizations unit. Policies are under the control of a CA administrator.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> <li>
/// <para>
/// A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates
/// signed by a CA in another account.
/// </para>
/// </li> <li>
/// <para>
/// For ACM to manage automatic renewal of these certificates, the ACM user must configure
/// a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity
/// of the user, subject to confirmation against the ACM Private CA policy. For more information,
/// see <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-slr.html">Using
/// a Service Linked Role with ACM</a>.
/// </para>
/// </li> <li>
/// <para>
/// Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-ram.html">Attach
/// a Policy for Cross-Account Access</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePolicy 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 DeletePolicy service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LockoutPreventedException">
/// The current action was prevented because it would lock the caller out from performing
/// subsequent actions. Verify that the specified parameters would not result in the caller
/// being denied access to the resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeletePolicy">REST API Reference for DeletePolicy Operation</seealso>
Task<DeletePolicyResponse> DeletePolicyAsync(DeletePolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeCertificateAuthority
/// <summary>
/// Lists information about your private certificate authority (CA) or one that has been
/// shared with you. You specify the private CA on input by its ARN (Amazon Resource Name).
/// The output contains the status of your CA. This can be any of the following:
///
/// <ul> <li>
/// <para>
/// <code>CREATING</code> - ACM Private CA is creating your private certificate authority.
/// </para>
/// </li> <li>
/// <para>
/// <code>PENDING_CERTIFICATE</code> - The certificate is pending. You must use your
/// ACM Private CA-hosted or on-premises root or subordinate CA to sign your private CA
/// CSR and then import it into PCA.
/// </para>
/// </li> <li>
/// <para>
/// <code>ACTIVE</code> - Your private CA is active.
/// </para>
/// </li> <li>
/// <para>
/// <code>DISABLED</code> - Your private CA has been disabled.
/// </para>
/// </li> <li>
/// <para>
/// <code>EXPIRED</code> - Your private CA certificate has expired.
/// </para>
/// </li> <li>
/// <para>
/// <code>FAILED</code> - Your private CA has failed. Your CA can fail because of problems
/// such a network outage or back-end AWS failure or other errors. A failed CA can never
/// return to the pending state. You must create a new CA.
/// </para>
/// </li> <li>
/// <para>
/// <code>DELETED</code> - Your private CA is within the restoration period, after which
/// it is permanently deleted. The length of time remaining in the CA's restoration period
/// is also included in this action's output.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthority 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 DescribeCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthority">REST API Reference for DescribeCertificateAuthority Operation</seealso>
Task<DescribeCertificateAuthorityResponse> DescribeCertificateAuthorityAsync(DescribeCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeCertificateAuthorityAuditReport
/// <summary>
/// Lists information about a specific audit report created by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthorityAuditReport.html">CreateCertificateAuthorityAuditReport</a>
/// action. Audit information is created every time the certificate authority (CA) private
/// key is used. The private key is used when you call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_IssueCertificate.html">IssueCertificate</a>
/// action or the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_RevokeCertificate.html">RevokeCertificate</a>
/// action.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthorityAuditReport 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 DescribeCertificateAuthorityAuditReport service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException">
/// One or more of the specified arguments was not valid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReport">REST API Reference for DescribeCertificateAuthorityAuditReport Operation</seealso>
Task<DescribeCertificateAuthorityAuditReportResponse> DescribeCertificateAuthorityAuditReportAsync(DescribeCertificateAuthorityAuditReportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetCertificate
/// <summary>
/// Retrieves a certificate from your private CA or one that has been shared with you.
/// The ARN of the certificate is returned when you call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_IssueCertificate.html">IssueCertificate</a>
/// action. You must specify both the ARN of your private CA and the ARN of the issued
/// certificate when calling the <b>GetCertificate</b> action. You can retrieve the certificate
/// if it is in the <b>ISSUED</b> state. You can call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthorityAuditReport.html">CreateCertificateAuthorityAuditReport</a>
/// action to create a report that contains information about all of the certificates
/// issued and revoked by your private CA.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetCertificate 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 GetCertificate service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException">
/// Your request is already in progress.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificate">REST API Reference for GetCertificate Operation</seealso>
Task<GetCertificateResponse> GetCertificateAsync(GetCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetCertificateAuthorityCertificate
/// <summary>
/// Retrieves the certificate and certificate chain for your private certificate authority
/// (CA) or one that has been shared with you. Both the certificate and the chain are
/// base64 PEM-encoded. The chain does not include the CA certificate. Each certificate
/// in the chain signs the one before it.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCertificate 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 GetCertificateAuthorityCertificate service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificate">REST API Reference for GetCertificateAuthorityCertificate Operation</seealso>
Task<GetCertificateAuthorityCertificateResponse> GetCertificateAuthorityCertificateAsync(GetCertificateAuthorityCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetCertificateAuthorityCsr
/// <summary>
/// Retrieves the certificate signing request (CSR) for your private certificate authority
/// (CA). The CSR is created when you call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>
/// action. Sign the CSR with your ACM Private CA-hosted or on-premises root or subordinate
/// CA. Then import the signed certificate back into ACM Private CA by calling the <a
/// href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ImportCertificateAuthorityCertificate.html">ImportCertificateAuthorityCertificate</a>
/// action. The CSR is returned as a base64 PEM-encoded string.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCsr 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 GetCertificateAuthorityCsr service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException">
/// Your request is already in progress.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsr">REST API Reference for GetCertificateAuthorityCsr Operation</seealso>
Task<GetCertificateAuthorityCsrResponse> GetCertificateAuthorityCsrAsync(GetCertificateAuthorityCsrRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetPolicy
/// <summary>
/// Retrieves the resource-based policy attached to a private CA. If either the private
/// CA resource or the policy cannot be found, this action returns a <code>ResourceNotFoundException</code>.
///
///
///
/// <para>
/// The policy can be attached or updated with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_PutPolicy.html">PutPolicy</a>
/// and removed with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeletePolicy.html">DeletePolicy</a>.
/// </para>
/// <p class="title"> <b>About Policies</b>
/// </para>
/// <ul> <li>
/// <para>
/// A policy grants access on a private CA to an AWS customer account, to AWS Organizations,
/// or to an AWS Organizations unit. Policies are under the control of a CA administrator.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> <li>
/// <para>
/// A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates
/// signed by a CA in another account.
/// </para>
/// </li> <li>
/// <para>
/// For ACM to manage automatic renewal of these certificates, the ACM user must configure
/// a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity
/// of the user, subject to confirmation against the ACM Private CA policy. For more information,
/// see <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-slr.html">Using
/// a Service Linked Role with ACM</a>.
/// </para>
/// </li> <li>
/// <para>
/// Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-ram.html">Attach
/// a Policy for Cross-Account Access</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPolicy 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 GetPolicy service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetPolicy">REST API Reference for GetPolicy Operation</seealso>
Task<GetPolicyResponse> GetPolicyAsync(GetPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ImportCertificateAuthorityCertificate
/// <summary>
/// Imports a signed private CA certificate into ACM Private CA. This action is used when
/// you are using a chain of trust whose root is located outside ACM Private CA. Before
/// you can call this action, the following preparations must in place:
///
/// <ol> <li>
/// <para>
/// In ACM Private CA, call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>
/// action to create the private CA that you plan to back with the imported certificate.
/// </para>
/// </li> <li>
/// <para>
/// Call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetCertificateAuthorityCsr.html">GetCertificateAuthorityCsr</a>
/// action to generate a certificate signing request (CSR).
/// </para>
/// </li> <li>
/// <para>
/// Sign the CSR using a root or intermediate CA hosted by either an on-premises PKI hierarchy
/// or by a commercial CA.
/// </para>
/// </li> <li>
/// <para>
/// Create a certificate chain and copy the signed certificate and the certificate chain
/// to your working directory.
/// </para>
/// </li> </ol>
/// <para>
/// ACM Private CA supports three scenarios for installing a CA certificate:
/// </para>
/// <ul> <li>
/// <para>
/// Installing a certificate for a root CA hosted by ACM Private CA.
/// </para>
/// </li> <li>
/// <para>
/// Installing a subordinate CA certificate whose parent authority is hosted by ACM Private
/// CA.
/// </para>
/// </li> <li>
/// <para>
/// Installing a subordinate CA certificate whose parent authority is externally hosted.
/// </para>
/// </li> </ul>
/// <para>
/// The following additional requirements apply when you import a CA certificate.
/// </para>
/// <ul> <li>
/// <para>
/// Only a self-signed certificate can be imported as a root CA.
/// </para>
/// </li> <li>
/// <para>
/// A self-signed certificate cannot be imported as a subordinate CA.
/// </para>
/// </li> <li>
/// <para>
/// Your certificate chain must not include the private CA certificate that you are importing.
/// </para>
/// </li> <li>
/// <para>
/// Your root CA must be the last certificate in your chain. The subordinate certificate,
/// if any, that your root CA signed must be next to last. The subordinate certificate
/// signed by the preceding subordinate CA must come next, and so on until your chain
/// is built.
/// </para>
/// </li> <li>
/// <para>
/// The chain must be PEM-encoded.
/// </para>
/// </li> <li>
/// <para>
/// The maximum allowed size of a certificate is 32 KB.
/// </para>
/// </li> <li>
/// <para>
/// The maximum allowed size of a certificate chain is 2 MB.
/// </para>
/// </li> </ul>
/// <para>
/// <i>Enforcement of Critical Constraints</i>
/// </para>
///
/// <para>
/// ACM Private CA allows the following extensions to be marked critical in the imported
/// CA certificate or chain.
/// </para>
/// <ul> <li>
/// <para>
/// Basic constraints (<i>must</i> be marked critical)
/// </para>
/// </li> <li>
/// <para>
/// Subject alternative names
/// </para>
/// </li> <li>
/// <para>
/// Key usage
/// </para>
/// </li> <li>
/// <para>
/// Extended key usage
/// </para>
/// </li> <li>
/// <para>
/// Authority key identifier
/// </para>
/// </li> <li>
/// <para>
/// Subject key identifier
/// </para>
/// </li> <li>
/// <para>
/// Issuer alternative name
/// </para>
/// </li> <li>
/// <para>
/// Subject directory attributes
/// </para>
/// </li> <li>
/// <para>
/// Subject information access
/// </para>
/// </li> <li>
/// <para>
/// Certificate policies
/// </para>
/// </li> <li>
/// <para>
/// Policy mappings
/// </para>
/// </li> <li>
/// <para>
/// Inhibit anyPolicy
/// </para>
/// </li> </ul>
/// <para>
/// ACM Private CA rejects the following extensions when they are marked critical in an
/// imported CA certificate or chain.
/// </para>
/// <ul> <li>
/// <para>
/// Name constraints
/// </para>
/// </li> <li>
/// <para>
/// Policy constraints
/// </para>
/// </li> <li>
/// <para>
/// CRL distribution points
/// </para>
/// </li> <li>
/// <para>
/// Authority information access
/// </para>
/// </li> <li>
/// <para>
/// Freshest CRL
/// </para>
/// </li> <li>
/// <para>
/// Any other extension
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ImportCertificateAuthorityCertificate 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 ImportCertificateAuthorityCertificate service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.CertificateMismatchException">
/// The certificate authority certificate you are importing does not comply with conditions
/// specified in the certificate that signed it.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidRequestException">
/// The request action cannot be performed or is prohibited.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.MalformedCertificateException">
/// One or more fields in the certificate are invalid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException">
/// Your request is already in progress.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificate">REST API Reference for ImportCertificateAuthorityCertificate Operation</seealso>
Task<ImportCertificateAuthorityCertificateResponse> ImportCertificateAuthorityCertificateAsync(ImportCertificateAuthorityCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region IssueCertificate
/// <summary>
/// Uses your private certificate authority (CA), or one that has been shared with you,
/// to issue a client certificate. This action returns the Amazon Resource Name (ARN)
/// of the certificate. You can retrieve the certificate by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetCertificate.html">GetCertificate</a>
/// action and specifying the ARN.
///
/// <note>
/// <para>
/// You cannot use the ACM <b>ListCertificateAuthorities</b> action to retrieve the ARNs
/// of the certificates that you issue by using ACM Private CA.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the IssueCertificate 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 IssueCertificate service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException">
/// One or more of the specified arguments was not valid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LimitExceededException">
/// An ACM Private CA quota has been exceeded. See the exception message returned to determine
/// the quota that was exceeded.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.MalformedCSRException">
/// The certificate signing request is invalid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificate">REST API Reference for IssueCertificate Operation</seealso>
Task<IssueCertificateResponse> IssueCertificateAsync(IssueCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListCertificateAuthorities
/// <summary>
/// Lists the private certificate authorities that you created by using the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>
/// action.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListCertificateAuthorities 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 ListCertificateAuthorities service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidNextTokenException">
/// The token specified in the <code>NextToken</code> argument is not valid. Use the token
/// returned from your previous call to <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a>.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthorities">REST API Reference for ListCertificateAuthorities Operation</seealso>
Task<ListCertificateAuthoritiesResponse> ListCertificateAuthoritiesAsync(ListCertificateAuthoritiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPermissions
/// <summary>
/// List all permissions on a private CA, if any, granted to the AWS Certificate Manager
/// (ACM) service principal (acm.amazonaws.com).
///
///
/// <para>
/// These permissions allow ACM to issue and renew ACM certificates that reside in the
/// same AWS account as the CA.
/// </para>
///
/// <para>
/// Permissions can be granted with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreatePermission.html">CreatePermission</a>
/// action and revoked with the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeletePermission.html">DeletePermission</a>
/// action.
/// </para>
/// <p class="title"> <b>About Permissions</b>
/// </para>
/// <ul> <li>
/// <para>
/// If the private CA and the certificates it issues reside in the same account, you can
/// use <code>CreatePermission</code> to grant permissions for ACM to carry out automatic
/// certificate renewals.
/// </para>
/// </li> <li>
/// <para>
/// For automatic certificate renewal to succeed, the ACM service principal needs permissions
/// to create, retrieve, and list certificates.
/// </para>
/// </li> <li>
/// <para>
/// If the private CA and the ACM certificates reside in different accounts, then permissions
/// cannot be used to enable automatic renewals. Instead, the ACM certificate owner must
/// set up a resource-based policy to enable cross-account issuance and renewals. For
/// more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPermissions 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 ListPermissions service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidNextTokenException">
/// The token specified in the <code>NextToken</code> argument is not valid. Use the token
/// returned from your previous call to <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a>.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListPermissions">REST API Reference for ListPermissions Operation</seealso>
Task<ListPermissionsResponse> ListPermissionsAsync(ListPermissionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTags
/// <summary>
/// Lists the tags, if any, that are associated with your private CA or one that has been
/// shared with you. Tags are labels that you can use to identify and organize your CAs.
/// Each tag consists of a key and an optional value. Call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_TagCertificateAuthority.html">TagCertificateAuthority</a>
/// action to add one or more tags to your CA. Call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_UntagCertificateAuthority.html">UntagCertificateAuthority</a>
/// action to remove tags.
/// </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 ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTags">REST API Reference for ListTags Operation</seealso>
Task<ListTagsResponse> ListTagsAsync(ListTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutPolicy
/// <summary>
/// Attaches a resource-based policy to a private CA.
///
///
/// <para>
/// A policy can also be applied by sharing a private CA through AWS Resource Access Manager
/// (RAM). For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-ram.html">Attach
/// a Policy for Cross-Account Access</a>.
/// </para>
///
/// <para>
/// The policy can be displayed with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetPolicy.html">GetPolicy</a>
/// and removed with <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeletePolicy.html">DeletePolicy</a>.
/// </para>
/// <p class="title"> <b>About Policies</b>
/// </para>
/// <ul> <li>
/// <para>
/// A policy grants access on a private CA to an AWS customer account, to AWS Organizations,
/// or to an AWS Organizations unit. Policies are under the control of a CA administrator.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-rbp.html">Using
/// a Resource Based Policy with ACM Private CA</a>.
/// </para>
/// </li> <li>
/// <para>
/// A policy permits a user of AWS Certificate Manager (ACM) to issue ACM certificates
/// signed by a CA in another account.
/// </para>
/// </li> <li>
/// <para>
/// For ACM to manage automatic renewal of these certificates, the ACM user must configure
/// a Service Linked Role (SLR). The SLR allows the ACM service to assume the identity
/// of the user, subject to confirmation against the ACM Private CA policy. For more information,
/// see <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-slr.html">Using
/// a Service Linked Role with ACM</a>.
/// </para>
/// </li> <li>
/// <para>
/// Updates made in AWS Resource Manager (RAM) are reflected in policies. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/pca-ram.html">Attach
/// a Policy for Cross-Account Access</a>.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutPolicy 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 PutPolicy service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidPolicyException">
/// The resource policy is invalid or is missing a required statement. For general information
/// about IAM policy and statement structure, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json">Overview
/// of JSON Policies</a>.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LockoutPreventedException">
/// The current action was prevented because it would lock the caller out from performing
/// subsequent actions. Verify that the specified parameters would not result in the caller
/// being denied access to the resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/PutPolicy">REST API Reference for PutPolicy Operation</seealso>
Task<PutPolicyResponse> PutPolicyAsync(PutPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RestoreCertificateAuthority
/// <summary>
/// Restores a certificate authority (CA) that is in the <code>DELETED</code> state. You
/// can restore a CA during the period that you defined in the <b>PermanentDeletionTimeInDays</b>
/// parameter of the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DeleteCertificateAuthority.html">DeleteCertificateAuthority</a>
/// action. Currently, you can specify 7 to 30 days. If you did not specify a <b>PermanentDeletionTimeInDays</b>
/// value, by default you can restore the CA at any time in a 30 day period. You can check
/// the time remaining in the restoration period of a private CA in the <code>DELETED</code>
/// state by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_DescribeCertificateAuthority.html">DescribeCertificateAuthority</a>
/// or <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a>
/// actions. The status of a restored CA is set to its pre-deletion status when the <b>RestoreCertificateAuthority</b>
/// action returns. To change its status to <code>ACTIVE</code>, call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_UpdateCertificateAuthority.html">UpdateCertificateAuthority</a>
/// action. If the private CA was in the <code>PENDING_CERTIFICATE</code> state at deletion,
/// you must use the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ImportCertificateAuthorityCertificate.html">ImportCertificateAuthorityCertificate</a>
/// action to import a certificate authority into the private CA before it can be activated.
/// You cannot restore a CA after the restoration period has ended.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RestoreCertificateAuthority 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 RestoreCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthority">REST API Reference for RestoreCertificateAuthority Operation</seealso>
Task<RestoreCertificateAuthorityResponse> RestoreCertificateAuthorityAsync(RestoreCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RevokeCertificate
/// <summary>
/// Revokes a certificate that was issued inside ACM Private CA. If you enable a certificate
/// revocation list (CRL) when you create or update your private CA, information about
/// the revoked certificates will be included in the CRL. ACM Private CA writes the CRL
/// to an S3 bucket that you specify. A CRL is typically updated approximately 30 minutes
/// after a certificate is revoked. If for any reason the CRL update fails, ACM Private
/// CA attempts makes further attempts every 15 minutes. With Amazon CloudWatch, you can
/// create alarms for the metrics <code>CRLGenerated</code> and <code>MisconfiguredCRLBucket</code>.
/// For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaCloudWatch.html">Supported
/// CloudWatch Metrics</a>.
///
/// <note>
/// <para>
/// Both PCA and the IAM principal must have permission to write to the S3 bucket that
/// you specify. If the IAM principal making the call does not have permission to write
/// to the bucket, then an exception is thrown. For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaAuthAccess.html">Configure
/// Access to ACM Private CA</a>.
/// </para>
/// </note>
/// <para>
/// ACM Private CA also writes revocation information to the audit report. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthorityAuditReport.html">CreateCertificateAuthorityAuditReport</a>.
/// </para>
/// <note>
/// <para>
/// You cannot revoke a root CA self-signed certificate.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RevokeCertificate 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 RevokeCertificate service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidRequestException">
/// The request action cannot be performed or is prohibited.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.LimitExceededException">
/// An ACM Private CA quota has been exceeded. See the exception message returned to determine
/// the quota that was exceeded.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestAlreadyProcessedException">
/// Your request has already been completed.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestFailedException">
/// The request has failed for an unspecified reason.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException">
/// Your request is already in progress.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificate">REST API Reference for RevokeCertificate Operation</seealso>
Task<RevokeCertificateResponse> RevokeCertificateAsync(RevokeCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region TagCertificateAuthority
/// <summary>
/// Adds one or more tags to your private CA. Tags are labels that you can use to identify
/// and organize your AWS resources. Each tag consists of a key and an optional value.
/// You specify the private CA on input by its Amazon Resource Name (ARN). You specify
/// the tag by using a key-value pair. You can apply a tag to just one private CA if you
/// want to identify a specific characteristic of that CA, or you can apply the same tag
/// to multiple private CAs if you want to filter for a common relationship among those
/// CAs. To remove one or more tags, use the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_UntagCertificateAuthority.html">UntagCertificateAuthority</a>
/// action. Call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListTags.html">ListTags</a>
/// action to see what tags are associated with your CA.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagCertificateAuthority 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 TagCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidTagException">
/// The tag associated with the CA is not valid. The invalid argument is contained in
/// the message field.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.TooManyTagsException">
/// You can associate up to 50 tags with a private CA. Exception information is contained
/// in the exception message field.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthority">REST API Reference for TagCertificateAuthority Operation</seealso>
Task<TagCertificateAuthorityResponse> TagCertificateAuthorityAsync(TagCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UntagCertificateAuthority
/// <summary>
/// Remove one or more tags from your private CA. A tag consists of a key-value pair.
/// If you do not specify the value portion of the tag when calling this action, the tag
/// will be removed regardless of value. If you specify a value, the tag is removed only
/// if it is associated with the specified value. To add tags to a private CA, use the
/// <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_TagCertificateAuthority.html">TagCertificateAuthority</a>.
/// Call the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListTags.html">ListTags</a>
/// action to see what tags are associated with your CA.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagCertificateAuthority 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 UntagCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidTagException">
/// The tag associated with the CA is not valid. The invalid argument is contained in
/// the message field.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthority">REST API Reference for UntagCertificateAuthority Operation</seealso>
Task<UntagCertificateAuthorityResponse> UntagCertificateAuthorityAsync(UntagCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateCertificateAuthority
/// <summary>
/// Updates the status or configuration of a private certificate authority (CA). Your
/// private CA must be in the <code>ACTIVE</code> or <code>DISABLED</code> state before
/// you can update it. You can disable a private CA that is in the <code>ACTIVE</code>
/// state or make a CA that is in the <code>DISABLED</code> state active again.
///
/// <note>
/// <para>
/// Both PCA and the IAM principal must have permission to write to the S3 bucket that
/// you specify. If the IAM principal making the call does not have permission to write
/// to the bucket, then an exception is thrown. For more information, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaAuthAccess.html">Configure
/// Access to ACM Private CA</a>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateCertificateAuthority 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 UpdateCertificateAuthority service method, as returned by ACMPCA.</returns>
/// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException">
/// A previous update to your private CA is still ongoing.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException">
/// One or more of the specified arguments was not valid.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidArnException">
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidPolicyException">
/// The resource policy is invalid or is missing a required statement. For general information
/// about IAM policy and statement structure, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json">Overview
/// of JSON Policies</a>.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.InvalidStateException">
/// The state of the private CA does not allow this action to occur.
/// </exception>
/// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException">
/// A resource such as a private CA, S3 bucket, certificate, audit report, or policy cannot
/// be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthority">REST API Reference for UpdateCertificateAuthority Operation</seealso>
Task<UpdateCertificateAuthorityResponse> UpdateCertificateAuthorityAsync(UpdateCertificateAuthorityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
} | 56.844307 | 246 | 0.644627 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/ACMPCA/Generated/_netstandard/IAmazonACMPCA.cs | 82,879 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Stride.Shaders.Parser.Analysis;
using Stride.Core.Shaders.Ast.Stride;
using Stride.Shaders.Parser.Utility;
using Stride.Core.Shaders.Ast;
using Stride.Core.Shaders.Ast.Hlsl;
using Stride.Core.Shaders.Utility;
using Stride.Core.Shaders.Visitor;
namespace Stride.Shaders.Parser.Mixins
{
internal class StrideStreamAnalyzer : ShaderWalker
{
#region Private members
/// <summary>
/// Current stream usage
/// </summary>
private StreamUsage currentStreamUsage = StreamUsage.Read;
/// <summary>
/// List of stream usage
/// </summary>
private List<StreamUsageInfo> currentStreamUsageList = null;
/// <summary>
/// List of already added methods.
/// </summary>
private List<MethodDeclaration> alreadyAddedMethodsList = null;
/// <summary>
/// Status of the assignment
/// </summary>
private AssignmentOperatorStatus currentAssignmentOperatorStatus = AssignmentOperatorStatus.Read;
/// <summary>
/// Log of all the warnings and errors
/// </summary>
private LoggerResult errorWarningLog;
/// <summary>
/// Name of the shader
/// </summary>
private string shaderName = "Mix";
#endregion
#region Public members
/// <summary>
/// List of assignations in the form of "streams = ...;"
/// </summary>
public Dictionary<AssignmentExpression, StatementList> StreamAssignations = new Dictionary<AssignmentExpression, StatementList>();
/// <summary>
/// List of assignations in the form of "... = streams;"
/// </summary>
public Dictionary<AssignmentExpression, StatementList> AssignationsToStream = new Dictionary<AssignmentExpression, StatementList>();
/// <summary>
/// List of assignations in the form of "StreamType backup = streams;"
/// </summary>
public Dictionary<Variable, StatementList> VariableStreamsAssignment = new Dictionary<Variable, StatementList>();
/// <summary>
/// streams usage by method
/// </summary>
public Dictionary<MethodDeclaration, List<StreamUsageInfo>> StreamsUsageByMethodDefinition = new Dictionary<MethodDeclaration, List<StreamUsageInfo>>();
/// <summary>
/// A list containing all the "streams" Variable references
/// </summary>
public HashSet<MethodInvocationExpression> AppendMethodCalls = new HashSet<MethodInvocationExpression>();
#endregion
#region Constructor
public StrideStreamAnalyzer(LoggerResult errorLog)
: base(false, true)
{
errorWarningLog = errorLog ?? new LoggerResult();
}
#endregion
public void Run(ShaderClassType shaderClassType)
{
shaderName = shaderClassType.Name.Text;
Visit(shaderClassType);
}
#region Private methods
/// <summary>
/// Analyse the method definition and store it in the correct lists (based on storage and stream usage)
/// </summary>
/// <param name="methodDefinition">the MethodDefinition</param>
public override void Visit(MethodDefinition methodDefinition)
{
currentStreamUsageList = new List<StreamUsageInfo>();
alreadyAddedMethodsList = new List<MethodDeclaration>();
base.Visit(methodDefinition);
if (currentStreamUsageList.Count > 0)
StreamsUsageByMethodDefinition.Add(methodDefinition, currentStreamUsageList);
}
/// <summary>
/// Calls the base method but modify the stream usage beforehand
/// </summary>
/// <param name="expression">the method expression</param>
public override void Visit(MethodInvocationExpression expression)
{
base.Visit(expression);
var methodDecl = expression.Target.TypeInference.Declaration as MethodDeclaration;
if (methodDecl != null)
{
// Stream analysis
if (methodDecl.ContainsTag(StrideTags.ShaderScope)) // this will prevent built-in function to appear in the list
{
// test if the method was previously added
if (!alreadyAddedMethodsList.Contains(methodDecl))
{
currentStreamUsageList.Add(new StreamUsageInfo { CallType = StreamCallType.Method, MethodDeclaration = methodDecl, Expression = expression });
alreadyAddedMethodsList.Add(methodDecl);
}
}
for (int i = 0; i < expression.Arguments.Count; ++i)
{
var arg = expression.Arguments[i] as MemberReferenceExpression; // TODO:
if (arg != null && IsStreamMember(arg))
{
var isOut = methodDecl.Parameters[i].Qualifiers.Contains(Stride.Core.Shaders.Ast.ParameterQualifier.Out);
//if (methodDecl.Parameters[i].Qualifiers.Contains(Ast.ParameterQualifier.InOut))
// Error(MessageCode.ErrorInOutStream, expression.Span, arg, methodDecl, contextModuleMixin.MixinName);
var usage = methodDecl.Parameters[i].Qualifiers.Contains(Stride.Core.Shaders.Ast.ParameterQualifier.Out) ? StreamUsage.Write : StreamUsage.Read;
AddStreamUsage(arg.TypeInference.Declaration as Variable, arg, usage);
}
}
}
// TODO: <shaderclasstype>.Append should be avoided
if (expression.Target is MemberReferenceExpression && (expression.Target as MemberReferenceExpression).Target.TypeInference.TargetType is ClassType && (expression.Target as MemberReferenceExpression).Member.Text == "Append")
AppendMethodCalls.Add(expression);
}
private static bool IsStreamMember(MemberReferenceExpression expression)
{
if (expression.TypeInference.Declaration is Variable)
{
return (expression.TypeInference.Declaration as Variable).Qualifiers.Contains(StrideStorageQualifier.Stream);
}
return false;
}
/// <summary>
/// Analyse the VariableReferenceExpression, detects streams, propagate type inference, get stored in the correct list for later analysis
/// </summary>
/// <param name="variableReferenceExpression">the VariableReferenceExpression</param>
public override void Visit(VariableReferenceExpression variableReferenceExpression)
{
base.Visit(variableReferenceExpression);
// HACK: force types on base, this and stream keyword to eliminate errors in the log an use the standard type inference
if (variableReferenceExpression.Name == StreamsType.ThisStreams.Name)
{
if (!(ParentNode is MemberReferenceExpression)) // streams is alone
currentStreamUsageList.Add(new StreamUsageInfo { CallType = StreamCallType.Direct, Variable = StreamsType.ThisStreams, Expression = variableReferenceExpression, Usage = currentStreamUsage });
}
}
public override void Visit(MemberReferenceExpression memberReferenceExpression)
{
var usageCopy = currentStreamUsage;
currentStreamUsage |= StreamUsage.Partial;
base.Visit(memberReferenceExpression);
currentStreamUsage = usageCopy;
// check if it is a stream
if (IsStreamMember(memberReferenceExpression))
AddStreamUsage(memberReferenceExpression.TypeInference.Declaration as Variable, memberReferenceExpression, currentStreamUsage);
}
public override void Visit(BinaryExpression expression)
{
var prevStreamUsage = currentStreamUsage;
currentStreamUsage = StreamUsage.Read;
base.Visit(expression);
currentStreamUsage = prevStreamUsage;
}
public override void Visit(UnaryExpression expression)
{
var prevStreamUsage = currentStreamUsage;
currentStreamUsage = StreamUsage.Read;
base.Visit(expression);
currentStreamUsage = prevStreamUsage;
}
/// <summary>
/// Analyse the AssignmentExpression to correctly infer the potential stream usage
/// </summary>
/// <param name="assignmentExpression">the AssignmentExpression</param>
public override void Visit(AssignmentExpression assignmentExpression)
{
if (currentAssignmentOperatorStatus != AssignmentOperatorStatus.Read)
errorWarningLog.Error(StrideMessageCode.ErrorNestedAssignment, assignmentExpression.Span, assignmentExpression, shaderName);
var prevStreamUsage = currentStreamUsage;
currentStreamUsage = StreamUsage.Read;
assignmentExpression.Value = (Expression)VisitDynamic(assignmentExpression.Value);
currentAssignmentOperatorStatus = (assignmentExpression.Operator != AssignmentOperator.Default) ? AssignmentOperatorStatus.ReadWrite : AssignmentOperatorStatus.Write;
currentStreamUsage = StreamUsage.Write;
assignmentExpression.Target = (Expression)VisitDynamic(assignmentExpression.Target);
currentAssignmentOperatorStatus = AssignmentOperatorStatus.Read;
currentStreamUsage = prevStreamUsage;
var parentBlock = this.NodeStack.OfType<StatementList>().LastOrDefault();
if (assignmentExpression.Operator == AssignmentOperator.Default && parentBlock != null)
{
if (assignmentExpression.Target is VariableReferenceExpression && (assignmentExpression.Target as VariableReferenceExpression).Name == StreamsType.ThisStreams.Name) // "streams = ...;"
StreamAssignations.Add(assignmentExpression, parentBlock);
else if (assignmentExpression.Value is VariableReferenceExpression && (assignmentExpression.Value as VariableReferenceExpression).Name == StreamsType.ThisStreams.Name) // "... = streams;"
AssignationsToStream.Add(assignmentExpression, parentBlock);
}
}
public override void Visit(Variable variableStatement)
{
base.Visit(variableStatement);
var parentBlock = this.NodeStack.OfType<StatementList>().LastOrDefault();
if (parentBlock != null && variableStatement.Type == StreamsType.Streams && variableStatement.InitialValue is VariableReferenceExpression && ((VariableReferenceExpression)(variableStatement.InitialValue)).TypeInference.TargetType.IsStreamsType())
{
VariableStreamsAssignment.Add(variableStatement, parentBlock);
}
}
/// <summary>
/// Adds a stream usage to the current method
/// </summary>
/// <param name="variable">the stream Variable</param>
/// <param name="expression">the calling expression</param>
/// <param name="usage">the encountered usage</param>
private void AddStreamUsage(Variable variable, Stride.Core.Shaders.Ast.Expression expression, StreamUsage usage)
{
currentStreamUsageList.Add(new StreamUsageInfo { CallType = StreamCallType.Member, Variable = variable, Expression = expression, Usage = usage });
}
#endregion
}
[Flags]
internal enum StreamUsage
{
Unknown = 0,
Read = 1,
Write = 2,
/// <summary>
/// Not all the components of the variable have been read/written
/// </summary>
Partial = 4,
}
internal static class StreamUsageExtensions
{
public static bool IsRead(this StreamUsage usage) { return (usage & StreamUsage.Read) != 0; }
public static bool IsWrite(this StreamUsage usage) { return (usage & StreamUsage.Write) != 0; }
public static bool IsPartial(this StreamUsage usage) { return (usage & StreamUsage.Partial) != 0; }
}
internal enum StreamCallType
{
Unknown = 0,
Member = 1,
Method = 2,
Direct = 3
}
internal class StreamUsageInfo
{
public StreamUsage Usage = StreamUsage.Unknown;
public StreamCallType CallType = StreamCallType.Unknown;
public Variable Variable = null;
public MethodDeclaration MethodDeclaration = null;
public Expression Expression;
}
}
| 42.703583 | 258 | 0.64508 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Shaders.Parser/Mixins/StrideStreamAnalyzer.cs | 13,110 | C# |
using System.Text.Json.Serialization;
namespace RestWithASPNETUdemy.Data.VO
{
public class PersonVO
{
//[JsonPropertyName("code")]
public long Id { get; set; }
//[JsonPropertyName("Nome")]
public string FirstName { get; set; }
//[JsonPropertyName("Sobrenome")]
public string LastName { get; set; }
//[JsonPropertyName("Endereco")]
public string Address { get; set; }
//[JsonIgnore] //EXCLUI DA VISUALIZACAO
public string Gender { get; set; }
}
}
| 28.631579 | 47 | 0.595588 | [
"Apache-2.0"
] | anderson-alpha/RestWithASP-NET5Umedy | 10_RestWithASPNETUdemy_ContentNegociation/RestWithASPNETUdemy/RestWithASPNETUdemy/Data/VO/PersonVO.cs | 546 | C# |
using System;
namespace Miffy
{
/// <summary>
/// Exception to throw if configuration is invalid
/// </summary>
public class BusConfigurationException : Exception
{
/// <summary>
/// Create a simple exception instance
/// </summary>
public BusConfigurationException() { }
/// <summary>
/// Create an exception instance with a message
/// </summary>
/// <param name="message">Message to highlight</param>
public BusConfigurationException(string message) : base(message) { }
/// <summary>
/// Create a busconfigurationexception with an inner exception
/// </summary>
/// <param name="message">Message to highlight</param>
/// <param name="innerException">InnerException</param>
public BusConfigurationException(string message, Exception innerException) : base(message, innerException) { }
}
}
| 32.37931 | 118 | 0.620873 | [
"MIT"
] | survivorbat/rabbiitmq-miffy-wrapper | Miffy.Core/BusConfigurationException.cs | 941 | C# |
using System;
using System.Collections.Generic;
using BizHawk.Common;
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Cores.Nintendo.SNES
{
public partial class LibsnesCore
{
private readonly List<MemoryDomain> _memoryDomainList = new List<MemoryDomain>();
private IMemoryDomains _memoryDomains;
private LibsnesApi.SNES_MAPPER? _mapper = null;
// works for WRAM, garbage for anything else
private static int? FakeBusMap(int addr)
{
addr &= 0xffffff;
int bank = addr >> 16;
if (bank == 0x7e || bank == 0x7f)
{
return addr & 0x1ffff;
}
bank &= 0x7f;
int low = addr & 0xffff;
if (bank < 0x40 && low < 0x2000)
{
return low;
}
return null;
}
private void SetupMemoryDomains(byte[] romData, byte[] sgbRomData)
{
MakeMemoryDomain("WRAM", LibsnesApi.SNES_MEMORY.WRAM, MemoryDomain.Endian.Little);
MakeMemoryDomain("CARTROM", LibsnesApi.SNES_MEMORY.CARTRIDGE_ROM, MemoryDomain.Endian.Little, byteSize: 2); //there are signs this doesnt work on SGB?
MakeMemoryDomain("CARTRAM", LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("VRAM", LibsnesApi.SNES_MEMORY.VRAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("OAM", LibsnesApi.SNES_MEMORY.OAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("CGRAM", LibsnesApi.SNES_MEMORY.CGRAM, MemoryDomain.Endian.Little, byteSize: 2);
MakeMemoryDomain("APURAM", LibsnesApi.SNES_MEMORY.APURAM, MemoryDomain.Endian.Little, byteSize: 2);
if (!DeterministicEmulation)
{
_memoryDomainList.Add(new MemoryDomainDelegate(
"System Bus",
0x1000000,
MemoryDomain.Endian.Little,
addr => Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr),
(addr, val) => Api.QUERY_poke(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr, val), wordSize: 2));
}
else
{
// limited function bus
MakeFakeBus();
}
if (IsSGB)
{
// NOTE: CGB has 32K of wram, and DMG has 8KB of wram. Not sure how to control this right now.. bsnes might not have any ready way of doign that? I couldnt spot it.
// You wouldnt expect a DMG game to access excess wram, but what if it tried to? maybe an oversight in bsnes?
MakeMemoryDomain("SGB WRAM", LibsnesApi.SNES_MEMORY.SGB_WRAM, MemoryDomain.Endian.Little);
//uhhh why can't this be done with MakeMemoryDomain? improve that.
var romDomain = new MemoryDomainByteArray("SGB CARTROM", MemoryDomain.Endian.Little, romData, true, 1);
_memoryDomainList.Add(romDomain);
// the last 1 byte of this is special.. its an interrupt enable register, instead of ram. weird. maybe its actually ram and just getting specially used?
MakeMemoryDomain("SGB HRAM", LibsnesApi.SNES_MEMORY.SGB_HRAM, MemoryDomain.Endian.Little);
MakeMemoryDomain("SGB CARTRAM", LibsnesApi.SNES_MEMORY.SGB_CARTRAM, MemoryDomain.Endian.Little);
MakeMemoryDomain("WRAM", LibsnesApi.SNES_MEMORY.WRAM, MemoryDomain.Endian.Little);
}
_memoryDomains = new MemoryDomainList(_memoryDomainList);
(ServiceProvider as BasicServiceProvider).Register<IMemoryDomains>(_memoryDomains);
}
private unsafe void MakeMemoryDomain(string name, LibsnesApi.SNES_MEMORY id, MemoryDomain.Endian endian, int byteSize = 1)
{
int size = Api.QUERY_get_memory_size(id);
int mask = size - 1;
bool pow2 = Util.IsPowerOfTwo(size);
// if this type of memory isnt available, dont make the memory domain (most commonly save ram)
if (size == 0)
{
return;
}
byte* blockptr = Api.QUERY_get_memory_data(id);
MemoryDomain md;
if (id == LibsnesApi.SNES_MEMORY.OAM)
{
// OAM is actually two differently sized banks of memory which arent truly considered adjacent.
// maybe a better way to visualize it is with an empty bus and adjacent banks
// so, we just throw away everything above its size of 544 bytes
if (size != 544)
{
throw new InvalidOperationException("oam size isnt 544 bytes.. wtf?");
}
md = new MemoryDomainDelegate(
name,
size,
endian,
addr => addr < 544 ? blockptr[addr] : (byte)0x00,
(addr, value) => { if (addr < 544) { blockptr[addr] = value; } },
byteSize);
}
else if (pow2)
{
md = new MemoryDomainDelegate(
name,
size,
endian,
addr => blockptr[addr & mask],
(addr, value) => blockptr[addr & mask] = value,
byteSize);
}
else
{
md = new MemoryDomainDelegate(
name,
size,
endian,
addr => blockptr[addr % size],
(addr, value) => blockptr[addr % size] = value,
byteSize);
}
_memoryDomainList.Add(md);
}
private unsafe void MakeFakeBus()
{
int size = Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.WRAM);
if (size != 0x20000)
{
throw new InvalidOperationException();
}
byte* blockptr = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.WRAM);
var md = new MemoryDomainDelegate("System Bus", 0x1000000, MemoryDomain.Endian.Little,
addr =>
{
var a = FakeBusMap((int)addr);
if (a.HasValue)
{
return blockptr[a.Value];
}
return FakeBusRead((int)addr);
},
(addr, val) =>
{
var a = FakeBusMap((int)addr);
if (a.HasValue)
blockptr[a.Value] = val;
}, wordSize: 2);
_memoryDomainList.Add(md);
}
// works for ROM, garbage for anything else
private byte FakeBusRead(int addr)
{
addr &= 0xffffff;
int bank = addr >> 16;
int low = addr & 0xffff;
if (!_mapper.HasValue)
{
return 0;
}
switch (_mapper)
{
case LibsnesApi.SNES_MAPPER.LOROM:
if (low >= 0x8000)
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.EXLOROM:
if ((bank >= 0x40 && bank <= 0x7f) || low >= 0x8000)
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.HIROM:
case LibsnesApi.SNES_MAPPER.EXHIROM:
if ((bank >= 0x40 && bank <= 0x7f) || bank >= 0xc0 || low >= 0x8000)
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.SUPERFXROM:
if ((bank >= 0x40 && bank <= 0x5f) || (bank >= 0xc0 && bank <= 0xdf) ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.SA1ROM:
if (bank >= 0xc0 || (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSCLOROM:
if (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf)))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSCHIROM:
if ((bank >= 0x40 && bank <= 0x5f) || (bank >= 0xc0 && bank <= 0xdf) ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x1f) || (bank >= 0x80 && bank <= 0x9f))))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.BSXROM:
if ((bank >= 0x40 && bank <= 0x7f) || bank >= 0xc0 ||
(low >= 0x8000 && ((bank >= 0x00 && bank <= 0x3f) || (bank >= 0x80 && bank <= 0xbf))) ||
(low >= 0x6000 && low <= 0x7fff && (bank >= 0x20 && bank <= 0x3f)))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
case LibsnesApi.SNES_MAPPER.STROM:
if (low >= 0x8000 && ((bank >= 0x00 && bank <= 0x5f) || (bank >= 0x80 && bank <= 0xdf)))
{
return Api.QUERY_peek(LibsnesApi.SNES_MEMORY.SYSBUS, (uint)addr);
}
break;
default:
throw new InvalidOperationException($"Unknown mapper: {_mapper}");
}
return 0;
}
}
}
| 30.641221 | 169 | 0.64711 | [
"MIT"
] | ircluzar/BizhawkLegacy-Vanguard | BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IMemoryDomains.cs | 8,030 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace akarnokd.reactive_extensions
{
internal sealed class ObservableSourceAll<T> : IObservableSource<bool>
{
readonly IObservableSource<T> source;
readonly Func<T, bool> predicate;
public ObservableSourceAll(IObservableSource<T> source, Func<T, bool> predicate)
{
this.source = source;
this.predicate = predicate;
}
public void Subscribe(ISignalObserver<bool> observer)
{
source.Subscribe(new AllObserver(observer, predicate));
}
sealed class AllObserver : DeferredScalarDisposable<bool>, ISignalObserver<T>
{
readonly Func<T, bool> predicate;
IDisposable upstream;
internal AllObserver(ISignalObserver<bool> downstream, Func<T, bool> predicate) : base(downstream)
{
this.predicate = predicate;
}
public void OnCompleted()
{
Complete(true);
}
public void OnError(Exception ex)
{
Error(ex);
}
public void OnNext(T item)
{
var result = false;
try
{
result = predicate(item);
}
catch (Exception ex)
{
upstream.Dispose();
Error(ex);
return;
}
if (!result)
{
upstream.Dispose();
Complete(false);
}
}
public void OnSubscribe(IDisposable d)
{
upstream = d;
downstream.OnSubscribe(this);
}
public override void Dispose()
{
base.Dispose();
upstream.Dispose();
}
}
}
}
| 25.1625 | 110 | 0.467958 | [
"Apache-2.0"
] | akarnokd/reactive-extensions | reactive-extensions/observablesource/ObservableSourceAll.cs | 2,015 | C# |
//Viewer.cs
//Created by Aaron C Gaudette on 07.07.16
//Rewrite of TrackedHeadset.cs, completed on 02.07.16
using UnityEngine;
using Holojam.Network;
namespace Holojam.Tools{
[ExecuteInEditMode]
public class Viewer : MonoBehaviour{
public enum TrackingType{LEGACY,OPTICAL,IMU};
public TrackingType trackingType = TrackingType.IMU;
//Get tracking data from actor (recommended coupling), or directly from the view?
public Actor actor = null;
[HideInInspector] public HolojamView view = null;
public Motive.Tag trackingTag = Motive.Tag.HEADSET1;
public bool localSpace = false;
const float correctionThreshold = 0.98f; //Lower values allow greater deviation without correction
Quaternion correction = Quaternion.identity;
const float differenceThreshold = 0.9995f; //Lower values allow correction at greater angular speeds
float difference = 1;
const float timestep = 0.01f;
float lastTime = 0;
Quaternion lastRotation = Quaternion.identity;
//Update late to catch local space updates
void LateUpdate(){
//Flush extra components if necessary
HolojamView[] views = GetComponents<HolojamView>();
if((view==null && views.Length>0) || (view!=null && (views.Length>1 || views.Length==0))){
foreach(HolojamView hv in views)DestroyImmediate(hv);
view=null; //In case the view has been set to a prefab value
}
//Automatically add a HolojamView component if not using a reference actor
if(actor==view)view=gameObject.AddComponent<HolojamView>() as HolojamView;
else if(actor!=null && view!=null)DestroyImmediate(view);
if(view!=null)view.Label=Motive.GetName(trackingTag);
if(!Application.isPlaying)return;
Vector3 sourcePosition = GetPosition();
Quaternion sourceRotation = GetRotation();
bool sourceTracked = GetTracked();
//Don't use Camera.main (reference to Oculus' instantiated camera at runtime)
//in the editor or standalone, reference the child camera instead
Vector3 cameraPosition = Utility.IsMasterPC()?
GetComponentInChildren<Camera>().transform.position:Camera.main.transform.position;
//Negate Oculus' automatic head offset (variable reliant on orientation) independent of recenters
transform.position+=sourcePosition-cameraPosition;
if(sourceTracked){
Quaternion imu = UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.CenterEye);
Quaternion optical = sourceRotation*Quaternion.Inverse(imu);
//Calculate rotation difference since last timestep
if(Time.time>lastTime+timestep){
difference=Quaternion.Dot(imu,lastRotation);
lastRotation=imu; lastTime=Time.time;
}
//Ignore local space rotation in the IMU calculations
Quaternion localRotation = transform.rotation;
if(actor!=null && actor.localSpace && actor.transform.parent!=null)
localRotation=Quaternion.Inverse(actor.transform.parent.rotation)*transform.rotation;
else if(actor==null && localSpace && transform.parent!=null)
localRotation=Quaternion.Inverse(transform.parent.rotation)*transform.rotation;
//Recalculate IMU correction if stale (generally on init/recenter)
if(Quaternion.Dot(localRotation*imu,sourceRotation)<=correctionThreshold
&& difference>=differenceThreshold) //But not if the headset is moving quickly
correction=optical;
//IMU orientation (applied automatically by Oculus) is assumed below as a precondition
switch(trackingType){
case TrackingType.IMU: //IMU, absolutely oriented by optical tracking intermittently
if(Utility.IsMasterPC())
goto case TrackingType.OPTICAL; //Don't use IMU tracking in the editor or standalone
transform.rotation=correction;
break;
case TrackingType.OPTICAL: //Purely optical tracking, no IMU
transform.rotation=optical;
break;
case TrackingType.LEGACY:
transform.rotation=Quaternion.Slerp(transform.rotation,optical,Time.deltaTime);
break;
}
} else transform.rotation=correction; //Transition seamlessly to IMU when untracked
//Apply local rotation if necessary
if(actor!=null && actor.localSpace && actor.transform.parent!=null)
transform.rotation=actor.transform.parent.rotation*transform.rotation;
else if(actor==null && localSpace && transform.parent!=null)
transform.rotation=transform.parent.rotation*transform.rotation;
//Prints tracking status to VR debugger
VRDebug.Println(actor!=null? actor.trackingTag.ToString():trackingTag.ToString());
}
//Get tracking data from desired source
Vector3 GetPosition(){
return actor!=null? actor.eyes:
localSpace && transform.parent!=null?
transform.parent.TransformPoint(view.RawPosition) : view.RawPosition;
}
Quaternion GetRotation(){return actor!=null?actor.rawOrientation:view.RawRotation;}
bool GetTracked(){return actor!=null?actor.view.IsTracked:view.IsTracked;}
}
}
| 47.947368 | 108 | 0.669594 | [
"BSD-3-Clause"
] | leo92613/holojam-holodeck | Holojam/Assets/Holojam/Tools/Viewer.cs | 5,468 | C# |
using System;
using System.Collections.Generic;
namespace Natasha
{
/// <summary>
/// 委托构建器,动态构建Func和Action委托
/// </summary>
public class DelegateBuilder
{
public readonly static Type[] FuncMaker;
public readonly static Type[] ActionMaker;
static DelegateBuilder()
{
FuncMaker = new Type[9];
FuncMaker[0] = typeof(Func<>);
FuncMaker[1] = typeof(Func<,>);
FuncMaker[2] = typeof(Func<,,>);
FuncMaker[3] = typeof(Func<,,,>);
FuncMaker[4] = typeof(Func<,,,,>);
FuncMaker[5] = typeof(Func<,,,,,>);
FuncMaker[6] = typeof(Func<,,,,,,>);
FuncMaker[7] = typeof(Func<,,,,,,,>);
FuncMaker[8] = typeof(Func<,,,,,,,,>);
ActionMaker = new Type[9];
ActionMaker[0] = typeof(Action);
ActionMaker[1] = typeof(Action<>);
ActionMaker[2] = typeof(Action<,>);
ActionMaker[3] = typeof(Action<,,>);
ActionMaker[4] = typeof(Action<,,,>);
ActionMaker[5] = typeof(Action<,,,,>);
ActionMaker[6] = typeof(Action<,,,,,>);
ActionMaker[7] = typeof(Action<,,,,,,>);
ActionMaker[8] = typeof(Action<,,,,,,,>);
}
/// <summary>
/// 获取函数委托
/// </summary>
/// <param name="parametersTypes">泛型参数</param>
/// <param name="returnType">返回类型</param>
/// <returns>函数委托</returns>
public static Type GetDelegate(Type[] parametersTypes = null, Type returnType = null)
{
if (returnType == null || returnType == typeof(void))
{
return GetAction(parametersTypes);
}
else
{
return GetFunc(returnType, parametersTypes);
}
}
/// <summary>
/// 根据类型动态生成Func委托
/// </summary>
/// <param name="returnType">返回类型</param>
/// <param name="parametersTypes">泛型类型</param>
/// <returns>Func委托类型</returns>
public static Type GetFunc(Type returnType, Type[] parametersTypes = null)
{
if (parametersTypes == null)
{
return FuncMaker[0].MakeGenericType(returnType);
}
List<Type> list = new List<Type>();
list.AddRange(parametersTypes);
list.Add(returnType);
return FuncMaker[parametersTypes.Length].MakeGenericType(list.ToArray());
}
/// <summary>
/// 根据类型动态生成Action委托
/// </summary>
/// <param name="parametersTypes">泛型参数类型</param>
/// <returns>Action委托类型</returns>
public static Type GetAction(Type[] parametersTypes = null)
{
if (parametersTypes == null || parametersTypes.Length == 0)
{
return ActionMaker[0];
}
return ActionMaker[parametersTypes.Length].MakeGenericType(parametersTypes);
}
}
}
| 27.963303 | 93 | 0.505906 | [
"MIT"
] | csuffyy/Natasha | Natasha/Builder/DelegateBuilder.cs | 3,196 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using Microsoft.Templates.UI.Extensions;
namespace Microsoft.Templates.UI.Services
{
public partial class DragAndDropService<T>
{
private Func<T, T, bool> _canDrop;
private bool _canInitiateDrag;
private bool _showDragAdornerLayer;
private int _indexToSelect;
private double _dragAdornerLayerOpacity;
private T _itemUnderDragCursor;
private ListView _listView;
private Point _mouseDownPosition;
private DragAdornerLayer _dragAdornerLayer;
public event EventHandler<DragAndDropEventArgs<T>> ProcessDrop;
private bool CanStartDragOperation
{
get
{
if (Mouse.LeftButton != MouseButtonState.Pressed
|| !_canInitiateDrag
|| _indexToSelect == -1
|| !HasCursorLeftDragThreshold)
{
return false;
}
return true;
}
}
private bool HasCursorLeftDragThreshold
{
get
{
if (_indexToSelect < 0)
{
return false;
}
var listViewItem = _listView.GetListViewItem(_indexToSelect);
if (listViewItem == null)
{
return false;
}
var bounds = VisualTreeHelper.GetDescendantBounds(listViewItem);
var ptInItem = _listView.TranslatePoint(_mouseDownPosition, listViewItem);
int distanceScale = 3;
double topOffset = Math.Abs(ptInItem.Y);
double btmOffset = Math.Abs(bounds.Height - ptInItem.Y);
double vertOffset = Math.Min(topOffset, btmOffset);
double width = SystemParameters.MinimumHorizontalDragDistance * distanceScale;
double height = Math.Min(SystemParameters.MinimumVerticalDragDistance, vertOffset) * distanceScale;
Size szThreshold = new Size(width, height);
Rect rect = new Rect(_mouseDownPosition, szThreshold);
rect.Offset(szThreshold.Width / -2, szThreshold.Height / -2);
Point ptInListView = MouseUtilities.GetMousePosition(_listView);
return !rect.Contains(ptInListView);
}
}
private bool IsMouseOverScrollbar
{
get
{
var mousePosition = MouseUtilities.GetMousePosition(_listView);
var result = VisualTreeHelper.HitTest(_listView, mousePosition);
if (result == null)
{
return false;
}
var dependencyObject = result.VisualHit;
while (dependencyObject != null)
{
if (dependencyObject is ScrollBar)
{
return true;
}
if (dependencyObject is Visual || dependencyObject is Visual3D)
{
dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
}
else
{
dependencyObject = LogicalTreeHelper.GetParent(dependencyObject);
}
}
return false;
}
}
private T ItemUnderDragCursor
{
get => _itemUnderDragCursor;
set
{
if (_itemUnderDragCursor == value)
{
return;
}
// 1º Previous item under the cursor.
// 2º the new one.
for (int step = 0; step < 2; ++step)
{
if (step == 1)
{
_itemUnderDragCursor = value;
}
if (_itemUnderDragCursor != null)
{
var listViewItem = GetListViewItem(_itemUnderDragCursor);
if (listViewItem != null)
{
ListViewItemDragState.SetIsUnderDragCursor(listViewItem, step == 1);
}
}
}
}
}
private bool ShowDragAdornerLayerResolved => _showDragAdornerLayer && _dragAdornerLayerOpacity > 0.0;
}
}
| 33.196078 | 116 | 0.498523 | [
"MIT"
] | Acidburn0zzz/WindowsTemplateStudio | code/src/UI/Services/DragAndDropService/DragAndDropService.Members.cs | 4,931 | C# |
#Thu Jan 06 20:33:17 EET 2022
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.client.3.2_1.0.59.jar=7025464c3b295d3b83cfb5834677d714
lib/com.ibm.ws.org.apache.cxf.cxf.tools.common.3.2_1.0.59.jar=c84ca09acda07a55b34eaf84fcef3266
lib/com.ibm.ws.jaxrs.2.1.common_1.0.59.jar=15465f3418838d198c561ede4a37b3a0
lib/com.ibm.ws.jaxrs.2.0.tools_1.0.59.jar=40a565e188f87ccdc0de2987817816b3
lib/com.ibm.ws.security.authorization.util_1.0.59.jar=df2e870b4ddd3e16dca984ff84414e35
bin/jaxrs/wadl2java.bat=6876bbb49c8a6e92bed8182973f380b6
bin/jaxrs/tools/wadl2java.jar=d54441b8b34efc24c86e4b22b896bdf3
dev/api/ibm/com.ibm.websphere.appserver.api.jaxrs20_1.1.59.jar=7a64fc9616278502b553041f039a1810
bin/jaxrs/wadl2java=f221daec79188ab703cadeba0f941db0
lib/com.ibm.ws.org.apache.cxf.cxf.tools.wadlto.jaxrs.3.2_1.0.59.jar=d7a49de3df9ce1d3ecb998992b2173e2
lib/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2_1.0.59.jar=526e06d42b969f01110860891b065869
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.service.description.3.2_1.0.59.jar=1ff0bd547d504c393569bbe9eebc96e2
lib/com.ibm.ws.jaxrs.2.0.server_1.0.59.jar=3da1f4f86f1a0187d86cb7e227b70ec8
lib/com.ibm.ws.jaxrs.2.0.client_1.0.59.jar=4bb411303b38b83d3f7176aa43470f8b
lib/com.ibm.ws.jaxrs.2.0.web_1.0.59.jar=199b75213daf25eac89996ed828e3468
lib/com.ibm.ws.jaxrs.2.x.config_1.0.59.jar=93ee5796b235eedf7bae23827556e5dc
lib/features/com.ibm.websphere.appserver.internal.jaxrs-2.1.mf=2feac9a0a93efdd0015b231032cbf0d0
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.sse.3.2_1.0.59.jar=d97a590f6fd3f4249ceaa0cd56158329
| 76.25 | 107 | 0.846557 | [
"MIT"
] | Amihaeseisergiu/Java-Technologies | lab11/service-a/target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.internal.jaxrs-2.1.cs | 1,525 | C# |
using Common.LogicObject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class MasterConfig : System.Web.UI.MasterPage
{
protected BackendPageCommon c;
#region Public properties
public string FlagValue
{
get { return txtFlag.Value; }
set { txtFlag.Value = value; }
}
/// <summary>
/// 啟用小日曆的中文模式
/// </summary>
public bool EnableDatepickerTW
{
get { return ltrDatepickerJsTW.Visible; }
set { ltrDatepickerJsTW.Visible = value; }
}
#endregion
protected void Page_Init(object sender, EventArgs e)
{
c = new BackendPageCommon(this.Context, this.ViewState);
c.InitialLoggerOfUI(this.GetType());
Page.MaintainScrollPositionOnPostBack = true;
}
protected void Page_Load(object sender, EventArgs e)
{
}
#region Public Methods
/// <summary>
/// 顯示錯誤訊息
/// </summary>
public void ShowErrorMsg(string value)
{
ltrErrMsg.Text = value;
ErrorMsgArea.Visible = (value != "");
if (ErrorMsgArea.Visible)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowErrorMsg", "smoothUp();", true);
}
}
#endregion
}
| 21.375 | 105 | 0.634503 | [
"MIT"
] | lozenlin/SampleCMS | Source/Management/MasterConfig.master.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository
{
public class CountyModel
{
public int CountyID { get; set; }
public string CountyName { get; set; }
public string StateCode { get; set; }
}
}
| 19.9375 | 46 | 0.670846 | [
"MIT"
] | ashokbalusu/homeworkhotline-1 | Repository/CountyModel.cs | 321 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.MobileBlazorBindings;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace CatTrackerDemo
{
public class App : Application
{
public App(IFileProvider fileProvider = null)
{
var hostBuilder = MobileBlazorBindingsHost.CreateDefaultBuilder()
.ConfigureServices((hostContext, services) =>
{
// Adds web-specific services such as NavigationManager
services.AddBlazorHybrid();
// Register app-specific services
services.AddSingleton<TrackerState>();
})
.UseWebRoot("wwwroot");
if (fileProvider != null)
{
hostBuilder.UseStaticFiles(fileProvider);
}
else
{
hostBuilder.UseStaticFiles();
}
var host = hostBuilder.Build();
MainPage = new ContentPage { Title = "My Application" };
host.AddComponent<Main>(parent: MainPage);
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
| 26.54717 | 77 | 0.558635 | [
"MIT"
] | Eilon/CatTrackerDemo | CatTrackerDemo/App.cs | 1,409 | C# |
using Common;
using GrainInterfaces;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Streams;
namespace Grains;
public class ProducerGrain : Grain, IProducerGrain
{
private readonly ILogger<IProducerGrain> _logger;
private IAsyncStream<int>? _stream;
private IDisposable? _timer;
private int _counter = 0;
public ProducerGrain(ILogger<IProducerGrain> logger)
{
_logger = logger;
}
public Task StartProducing(string ns, Guid key)
{
if (_timer is not null)
throw new Exception("This grain is already producing events");
// Get the stream
_stream = GetStreamProvider(Constants.StreamProvider)
.GetStream<int>(key, ns);
// Register a timer that produce an event every second
var period = TimeSpan.FromSeconds(1);
_timer = RegisterTimer(TimerTick, null, period, period);
_logger.LogInformation("I will produce a new event every {Period}", period);
return Task.CompletedTask;
}
private async Task TimerTick(object _)
{
var value = _counter++;
_logger.LogInformation("Sending event {EventNumber}", value);
if (_stream is not null)
{
await _stream.OnNextAsync(value);
}
}
public Task StopProducing()
{
if (_timer is not null)
{
_timer.Dispose();
_timer = null;
}
if (_stream is not null)
{
_stream = null;
}
return Task.CompletedTask;
}
}
| 23.373134 | 84 | 0.614943 | [
"MIT"
] | BearerPipelineTest/orleans | samples/Streaming/Simple/Grains/ProducerGrain.cs | 1,566 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Uno.Extensions;
using Uno.Logging;
using Uno.UI.Extensions;
using Uno.Disposables;
using Uno.UI.DataBinding;
using Uno.UI;
namespace Windows.UI.Xaml.Controls.Primitives
{
public partial class FlyoutBase
{
partial void InitializePopupPanelPartial()
{
_popup.PopupPanel = new FlyoutBasePopupPanel(this)
{
Visibility = Visibility.Collapsed,
Background = SolidColorBrushHelper.Transparent,
};
}
partial void SetPopupPositionPartial(UIElement placementTarget)
{
_popup.Anchor = placementTarget;
}
}
}
| 20.233333 | 65 | 0.762768 | [
"Apache-2.0"
] | ATHULBABYKURIAN/uno | src/Uno.UI/UI/Xaml/Controls/Flyout/FlyoutBase.net.cs | 609 | C# |
using NUnit.Framework;
using System;
using Taskter.Core.Entities;
using FluentAssertions;
namespace Taskter.Tests.Core
{
[TestFixture]
public class ProjectTaskEntryEntityTests
{
ProjectTaskEntry _entry = new ProjectTaskEntry(1, 1, 20, DateTime.Now, "Notee");
[TestCase(0)]
[TestCase(-1)]
public void DurationInMinSetter_NegativeOrZeroValue_ThrowArgumentException(int durationInMin)
{
Action act = () => _entry.DurationInMin = durationInMin;
act.Should().Throw<ArgumentException>().WithMessage("Duration can not be <=0!");
}
[TestCase(0)]
[TestCase(-1)]
public void Constructor_NegativeOrZeroDurationInMin_ThrowArgumentException(int durationInMin)
{
ProjectTaskEntry _entry1;
Action act = () => _entry1 = new ProjectTaskEntry(1, 1, durationInMin, DateTime.Now, "Notee");
act.Should().Throw<ArgumentException>().WithMessage("Duration can not be <=0!");
}
[Test]
public void Constructor_OverOneDayDurationInMin_ThrowArgumentException()
{
ProjectTaskEntry _entry1;
Action act = () => _entry1 = new ProjectTaskEntry(1, 1, 2000, DateTime.Now, "Notee");
act.Should().Throw<ArgumentException>();
}
[Test]
public void DurationInMinSetter_OverOneDayMinutes_ThrowArgumentException()
{
Action act = () => _entry.DurationInMin = 2000;
act.Should().Throw<ArgumentException>();
}
[TestCase(-10)]
[TestCase(0)]
public void Constructor_NegativeOrZeroUserId_ThrowArgumentException(int userId)
{
ProjectTaskEntry _entry1;
Action act = () => _entry1 = new ProjectTaskEntry(userId, 1, 20, DateTime.Now, "Notee");
act.Should().Throw<ArgumentException>();
}
[TestCase(-10)]
[TestCase(0)]
public void Constructor_ZeroOrNegativeProjectTaskId_ThrowArgumentException(int projectTaksId)
{
ProjectTaskEntry _entry1;
Action act = () => _entry1 = new ProjectTaskEntry(1, projectTaksId, 20, DateTime.Now, "Notee");
act.Should().Throw<ArgumentException>().WithMessage("Id field can not be set to negative value or zero!");
}
[TestCase(-10)]
[TestCase(0)]
public void ProjectTaskSetter_NegativeOrZeroValue_ThrowArgumentException(int projectTaskId)
{
Action act = () => _entry.ProjectTaskId = projectTaskId;
act.Should().Throw<ArgumentException>().WithMessage("Id field can not be set to negative value or zero!");
}
}
}
| 34.679487 | 118 | 0.629205 | [
"MIT"
] | javalanguagezone/Taskter-Backend | tests/Taskter.Tests/Core/ProjectTaskEntryEntityTests.cs | 2,707 | C# |
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts;
using FakeItEasy;
using Newtonsoft.Json.Linq;
using Xunit;
namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Parts.AliasPartGraphSyncerTests
{
public class AliasPartGraphSyncerValidateSyncComponentTestsBase : PartGraphSyncer_ValidateSyncComponentTestsBase
{
const string ContentKey = "Alias";
const string NodeTitlePropertyName = "alias_alias";
public AliasPartGraphSyncerValidateSyncComponentTestsBase()
{
ContentPartGraphSyncer = new AliasPartGraphSyncer();
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public async Task ValidateSyncComponentTests(bool expected, bool stringContentPropertyMatchesNodePropertyReturns)
{
A.CallTo(() => GraphValidationHelper.StringContentPropertyMatchesNodeProperty(
ContentKey,
A<JObject>._,
NodeTitlePropertyName,
SourceNode)).Returns((stringContentPropertyMatchesNodePropertyReturns, ""));
(bool validated, _) = await CallValidateSyncComponent();
Assert.Equal(expected, validated);
}
//todo: test that verifies that failure reason is returned
//todo: test to check nothing added to ExpectedRelationshipCounts
}
}
| 35.923077 | 121 | 0.6995 | [
"MIT"
] | SkillsFundingAgency/dfc-servicetaxonomy-editor | DFC.ServiceTaxonomy.UnitTests/GraphSync/GraphSyncers/Parts/AliasPartGraphSyncerTests/AliasPartGraphSyncerValidateSyncComponentTestsBase.cs | 1,403 | 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 codepipeline-2015-07-09.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.CodePipeline.Model
{
/// <summary>
/// This is the response object from the PutThirdPartyJobFailureResult operation.
/// </summary>
public partial class PutThirdPartyJobFailureResultResponse : AmazonWebServiceResponse
{
}
} | 30.289474 | 110 | 0.741964 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodePipeline/Generated/Model/PutThirdPartyJobFailureResultResponse.cs | 1,151 | 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("SqlSugar4")]
[assembly: AssemblyDescription("author sunkaixuan Apache Licence 2.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SqlSugar 4")]
[assembly: AssemblyCopyright("Copyright © 2016")]
// 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("c7c121b9-80c6-4caf-aadd-d85118ad1cf2")]
// 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("5.0.0.14")]
[assembly: AssemblyFileVersion("5.0.0.14")]
| 37.944444 | 84 | 0.746706 | [
"Apache-2.0"
] | jiaotashidixwh/SqlSugar | Src/Asp.Net/SqlSugar/Properties/AssemblyInfo.cs | 1,369 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
namespace SharpVectors.Renderers.Wpf
{
/// <summary>
/// This provides the options for the drawing/rendering engine of the WPF.
/// </summary>
public sealed class WpfDrawingSettings : DependencyObject, ICloneable
{
#region Private Fields
private bool _textAsGeometry;
private bool _includeRuntime;
private bool _optimizePath;
private CultureInfo _culture;
private CultureInfo _neutralCulture;
private string _defaultFontName;
private static FontFamily _defaultFontFamily;
private static FontFamily _genericSerif;
private static FontFamily _genericSansSerif;
private static FontFamily _genericMonospace;
#endregion
#region Constructor and Destructor
/// <overloads>
/// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class.
/// </overloads>
/// <summary>
/// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class
/// with the default parameters and settings.
/// </summary>
public WpfDrawingSettings()
{
_defaultFontName = "Arial Unicode MS";
_textAsGeometry = false;
_optimizePath = true;
_includeRuntime = true;
_neutralCulture = CultureInfo.GetCultureInfo("en-us");
_culture = CultureInfo.GetCultureInfo("en-us");
}
/// <summary>
/// Initializes a new instance of the <see cref="WpfDrawingSettings"/> class
/// with the specified initial drawing or rendering settings, a copy constructor.
/// </summary>
/// <param name="settings">
/// This specifies the initial options for the rendering or drawing engine.
/// </param>
public WpfDrawingSettings(WpfDrawingSettings settings)
{
_defaultFontName = settings._defaultFontName;
_textAsGeometry = settings._textAsGeometry;
_optimizePath = settings._optimizePath;
_includeRuntime = settings._includeRuntime;
_neutralCulture = settings._neutralCulture;
_culture = settings._culture;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether the path geometry is
/// optimized using the <see cref="StreamGeometry"/>.
/// </summary>
/// <value>
/// This is <see langword="true"/> if the path geometry is optimized
/// using the <see cref="StreamGeometry"/>; otherwise, it is
/// <see langword="false"/>. The default is <see langword="true"/>.
/// </value>
public bool OptimizePath
{
get
{
return _optimizePath;
}
set
{
_optimizePath = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the texts are rendered as
/// path geometry.
/// </summary>
/// <value>
/// This is <see langword="true"/> if texts are rendered as path
/// geometries; otherwise, this is <see langword="false"/>. The default
/// is <see langword="false"/>.
/// </value>
public bool TextAsGeometry
{
get
{
return _textAsGeometry;
}
set
{
_textAsGeometry = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the <c>SharpVectors.Runtime.dll</c>
/// classes are used in the generated output.
/// </summary>
/// <value>
/// This is <see langword="true"/> if the <c>SharpVectors.Runtime.dll</c>
/// classes and types are used in the generated output; otherwise, it is
/// <see langword="false"/>. The default is <see langword="true"/>.
/// </value>
/// <remarks>
/// The use of the <c>SharpVectors.Runtime.dll</c> prevents the hard-coded
/// font path generated by the <see cref="FormattedText"/> class, support
/// for embedded images etc.
/// </remarks>
public bool IncludeRuntime
{
get
{
return _includeRuntime;
}
set
{
_includeRuntime = value;
}
}
/// <summary>
/// Gets or sets the main culture information used for rendering texts.
/// </summary>
/// <value>
/// An instance of the <see cref="CultureInfo"/> specifying the main
/// culture information for texts. The default is the English culture.
/// </value>
/// <remarks>
/// <para>
/// This is the culture information passed to the <see cref="FormattedText"/>
/// class instance for the text rendering.
/// </para>
/// <para>
/// The library does not currently provide any means of splitting texts
/// into its multi-language parts.
/// </para>
/// </remarks>
public CultureInfo CultureInfo
{
get
{
return _culture;
}
set
{
if (value != null)
{
_culture = value;
}
}
}
/// <summary>
/// Gets the neutral language for text rendering.
/// </summary>
/// <value>
/// An instance of the <see cref="CultureInfo"/> specifying the neutral
/// culture information for texts. The default is the English culture.
/// </value>
/// <remarks>
/// For vertical text rendering, there is a basic text splitting into
/// Western and other languages. This culture information is used to
/// render the Western language part, and the mains culture information
/// for the other languages.
/// </remarks>
public CultureInfo NeutralCultureInfo
{
get
{
return _neutralCulture;
}
}
/// <summary>
/// Gets or sets the default font family name, which is used when a text
/// node does not specify a font family name.
/// </summary>
/// <value>
/// A string containing the default font family name. The default is
/// the <c>Arial Unicode MS</c> font, for its support of Unicode texts.
/// This value cannot be <see langword="null"/> or empty.
/// </value>
public string DefaultFontName
{
get
{
return _defaultFontName;
}
set
{
if (value != null)
{
value = value.Trim();
}
if (!String.IsNullOrEmpty(value))
{
_defaultFontName = value;
_defaultFontFamily = new FontFamily(value);
}
}
}
/// <summary>
/// Gets or sets the globally available default font family.
/// </summary>
/// <value>
/// An instance of the <see cref="FontFamily"/> specifying the globally
/// available font family. The default is a <c>Arial Unicode MS</c> font
/// family.
/// </value>
public static FontFamily DefaultFontFamily
{
get
{
if (_defaultFontFamily == null)
{
_defaultFontFamily = new FontFamily("Arial Unicode MS");
}
return _defaultFontFamily;
}
set
{
if (value != null)
{
_defaultFontFamily = value;
}
}
}
/// <summary>
/// Gets or set the globally available generic serif font family.
/// </summary>
/// <value>
/// An instance of <see cref="FontFamily"/> specifying the generic serif
/// font family. The default is <c>Times New Roman</c> font family.
/// </value>
public static FontFamily GenericSerif
{
get
{
if (_genericSerif == null)
{
_genericSerif = new FontFamily("Times New Roman");
}
return _genericSerif;
}
set
{
if (value != null)
{
_genericSerif = value;
}
}
}
/// <summary>
/// Gets or set the globally available generic sans serif font family.
/// </summary>
/// <value>
/// An instance of <see cref="FontFamily"/> specifying the generic sans
/// serif font family. The default is <c>Tahoma</c> font family.
/// </value>
/// <remarks>
/// The possible font names are <c>Tahoma</c>, <c>Arial</c>,
/// <c>Verdana</c>, <c>Trebuchet</c>, <c>MS Sans Serif</c> and <c>Helvetica</c>.
/// </remarks>
public static FontFamily GenericSansSerif
{
get
{
if (_genericSansSerif == null)
{
// Possibilities: Tahoma, Arial, Verdana, Trebuchet, MS Sans Serif, Helvetica
_genericSansSerif = new FontFamily("Tahoma");
}
return _genericSansSerif;
}
set
{
if (value != null)
{
_genericSansSerif = value;
}
}
}
/// <summary>
/// Gets or set the globally available generic Monospace font family.
/// </summary>
/// <value>
/// An instance of <see cref="FontFamily"/> specifying the generic
/// Monospace font family. The default is <c>MS Gothic</c> font family.
/// </value>
public static FontFamily GenericMonospace
{
get
{
if (_genericMonospace == null)
{
// Possibilities: Courier New, MS Gothic
_genericMonospace = new FontFamily("MS Gothic");
}
return _genericMonospace;
}
set
{
if (value != null)
{
_genericMonospace = value;
}
}
}
#endregion
#region ICloneable Members
/// <overloads>
/// This creates a new settings object that is a deep copy of the current
/// instance.
/// </overloads>
/// <summary>
/// This creates a new settings object that is a deep copy of the current
/// instance.
/// </summary>
/// <returns>
/// A new settings object that is a deep copy of this instance.
/// </returns>
/// <remarks>
/// This is deep cloning of the members of this settings object. If you
/// need just a copy, use the copy constructor to create a new instance.
/// </remarks>
public WpfDrawingSettings Clone()
{
WpfDrawingSettings settings = new WpfDrawingSettings(this);
return settings;
}
/// <summary>
/// This creates a new settings object that is a deep copy of the current
/// instance.
/// </summary>
/// <returns>
/// A new settings object that is a deep copy of this instance.
/// </returns>
/// <remarks>
/// This is deep cloning of the members of this style object. If you need just a copy,
/// use the copy constructor to create a new instance.
/// </remarks>
object ICloneable.Clone()
{
return this.Clone();
}
#endregion
}
}
| 32.172775 | 97 | 0.503662 | [
"BSD-3-Clause"
] | yavor87/sharpvectors | Main/Source/WPF/SharpVectorRenderingWpf/Wpf/WpfDrawingSettings.cs | 12,292 | 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("3. DivideBySevenAndFive")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("3. DivideBySevenAndFive")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("a64568ed-40e3-46e7-9835-051c5fa78717")]
// 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.837838 | 84 | 0.749478 | [
"MIT"
] | Yordanov101/OperatorsAndExpressionsHW | 3. DivideBySevenAndFive/Properties/AssemblyInfo.cs | 1,440 | C# |
using ExampleClaimOfResponsability.Entities;
namespace ExampleClaimOfResponsability.Interfaces
{
public interface IChargeAppService
{
Charge AlteraMeioPagamento(string payMethod);
}
} | 22.666667 | 53 | 0.784314 | [
"MIT"
] | wodsonluiz/ExampleClaimOfResponsibility | src/ExampleClaimOfResponsability/Interfaces/IChargeAppService.cs | 204 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗
// ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝
// ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗
// ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝
// ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗
// ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝
// ------------------------------------------------
//
// This file is automatically generated.
// Please do not edit these files manually.
//
// ------------------------------------------------
using Elastic.Transport.Products.Elasticsearch;
using System.Collections.Generic;
using System.Text.Json.Serialization;
#nullable restore
namespace Elastic.Clients.Elasticsearch.IndexManagement
{
public sealed partial class ForcemergeResponse : ElasticsearchResponseBase
{
[JsonInclude]
[JsonPropertyName("_shards")]
public Elastic.Clients.Elasticsearch.ShardStatistics Shards { get; init; }
}
} | 35.870968 | 76 | 0.499101 | [
"Apache-2.0"
] | SimonCropp/elasticsearch-net | src/Elastic.Clients.Elasticsearch/_Generated/Api/IndexManagement/ForcemergeResponse.g.cs | 1,558 | C# |
using MongoDB.Driver;
namespace RedCapped.Core.Extensions
{
public static class ExtensionMethods
{
internal static WriteConcern ToWriteConcern(this QoS qos)
{
switch (qos)
{
default:
return WriteConcern.W1;
case QoS.Low:
return WriteConcern.Acknowledged;
case QoS.High:
return WriteConcern.WMajority;
}
}
}
}
| 23.380952 | 65 | 0.503055 | [
"Apache-2.0"
] | AppSpaceIT/RedCapped | src/RedCapped.Core/Extensions/ExtensionMethods.cs | 493 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Discord
{
/// <summary>
/// Represents a container for a series of overwrite permissions.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct OverwritePermissions
{
/// <summary>
/// Gets a blank <see cref="OverwritePermissions" /> that inherits all permissions.
/// </summary>
public static OverwritePermissions InheritAll { get; } = new OverwritePermissions();
/// <summary>
/// Gets a <see cref="OverwritePermissions" /> that grants all permissions for the given channel.
/// </summary>
/// <exception cref="ArgumentException">Unknown channel type.</exception>
public static OverwritePermissions AllowAll(IChannel channel)
=> new OverwritePermissions(ChannelPermissions.All(channel).RawValue, 0);
/// <summary>
/// Gets a <see cref="OverwritePermissions" /> that denies all permissions for the given channel.
/// </summary>
/// <exception cref="ArgumentException">Unknown channel type.</exception>
public static OverwritePermissions DenyAll(IChannel channel)
=> new OverwritePermissions(0, ChannelPermissions.All(channel).RawValue);
/// <summary>
/// Gets a packed value representing all the allowed permissions in this <see cref="OverwritePermissions"/>.
/// </summary>
public ulong AllowValue { get; internal set; }
/// <summary>
/// Gets a packed value representing all the denied permissions in this <see cref="OverwritePermissions"/>.
/// </summary>
public ulong DenyValue { get; internal set; }
/// <summary> If Allowed, a user may create invites. </summary>
public PermValue CreateInstantInvite => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.CreateInstantInvite);
/// <summary> If Allowed, a user may create, delete and modify this channel. </summary>
public PermValue ManageChannel => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageChannels);
/// <summary> If Allowed, a user may add reactions. </summary>
public PermValue AddReactions => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.AddReactions);
/// <summary> If Allowed, a user may join channels. </summary>
[Obsolete("Use ViewChannel instead.")]
public PermValue ReadMessages => ViewChannel;
/// <summary> If Allowed, a user may join channels. </summary>
public PermValue ViewChannel => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ViewChannel);
/// <summary> If Allowed, a user may send messages. </summary>
public PermValue SendMessages => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.SendMessages);
/// <summary> If Allowed, a user may send text-to-speech messages. </summary>
public PermValue SendTTSMessages => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.SendTTSMessages);
/// <summary> If Allowed, a user may delete messages. </summary>
public PermValue ManageMessages => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageMessages);
/// <summary> If Allowed, Discord will auto-embed links sent by this user. </summary>
public PermValue EmbedLinks => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.EmbedLinks);
/// <summary> If Allowed, a user may send files. </summary>
public PermValue AttachFiles => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.AttachFiles);
/// <summary> If Allowed, a user may read previous messages. </summary>
public PermValue ReadMessageHistory => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ReadMessageHistory);
/// <summary> If Allowed, a user may mention @everyone. </summary>
public PermValue MentionEveryone => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MentionEveryone);
/// <summary> If Allowed, a user may use custom emoji from other guilds. </summary>
public PermValue UseExternalEmojis => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.UseExternalEmojis);
/// <summary> If Allowed, a user may connect to a voice channel. </summary>
public PermValue Connect => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Connect);
/// <summary> If Allowed, a user may speak in a voice channel. </summary>
public PermValue Speak => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Speak);
/// <summary> If Allowed, a user may mute users. </summary>
public PermValue MuteMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MuteMembers);
/// <summary> If Allowed, a user may deafen users. </summary>
public PermValue DeafenMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.DeafenMembers);
/// <summary> If Allowed, a user may move other users between voice channels. </summary>
public PermValue MoveMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MoveMembers);
/// <summary> If Allowed, a user may use voice-activity-detection rather than push-to-talk. </summary>
public PermValue UseVAD => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.UseVAD);
/// <summary> If Allowed, a user may use priority speaker in a voice channel. </summary>
public PermValue PrioritySpeaker => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.PrioritySpeaker);
/// <summary> If Allowed, a user may go live in a voice channel. </summary>
public PermValue Stream => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Stream);
/// <summary> If Allowed, a user may adjust role permissions. This also implicitly grants all other permissions. </summary>
public PermValue ManageRoles => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageRoles);
/// <summary> If True, a user may edit the webhooks for this channel. </summary>
public PermValue ManageWebhooks => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageWebhooks);
/// <summary> Creates a new OverwritePermissions with the provided allow and deny packed values. </summary>
public OverwritePermissions(ulong allowValue, ulong denyValue)
{
AllowValue = allowValue;
DenyValue = denyValue;
}
private OverwritePermissions(ulong allowValue, ulong denyValue,
PermValue? createInstantInvite = null,
PermValue? manageChannel = null,
PermValue? addReactions = null,
PermValue? viewChannel = null,
PermValue? sendMessages = null,
PermValue? sendTTSMessages = null,
PermValue? manageMessages = null,
PermValue? embedLinks = null,
PermValue? attachFiles = null,
PermValue? readMessageHistory = null,
PermValue? mentionEveryone = null,
PermValue? useExternalEmojis = null,
PermValue? connect = null,
PermValue? speak = null,
PermValue? muteMembers = null,
PermValue? deafenMembers = null,
PermValue? moveMembers = null,
PermValue? useVoiceActivation = null,
PermValue? manageRoles = null,
PermValue? manageWebhooks = null,
PermValue? prioritySpeaker = null,
PermValue? stream = null)
{
Permissions.SetValue(ref allowValue, ref denyValue, createInstantInvite, ChannelPermission.CreateInstantInvite);
Permissions.SetValue(ref allowValue, ref denyValue, manageChannel, ChannelPermission.ManageChannels);
Permissions.SetValue(ref allowValue, ref denyValue, addReactions, ChannelPermission.AddReactions);
Permissions.SetValue(ref allowValue, ref denyValue, viewChannel, ChannelPermission.ViewChannel);
Permissions.SetValue(ref allowValue, ref denyValue, sendMessages, ChannelPermission.SendMessages);
Permissions.SetValue(ref allowValue, ref denyValue, sendTTSMessages, ChannelPermission.SendTTSMessages);
Permissions.SetValue(ref allowValue, ref denyValue, manageMessages, ChannelPermission.ManageMessages);
Permissions.SetValue(ref allowValue, ref denyValue, embedLinks, ChannelPermission.EmbedLinks);
Permissions.SetValue(ref allowValue, ref denyValue, attachFiles, ChannelPermission.AttachFiles);
Permissions.SetValue(ref allowValue, ref denyValue, readMessageHistory, ChannelPermission.ReadMessageHistory);
Permissions.SetValue(ref allowValue, ref denyValue, mentionEveryone, ChannelPermission.MentionEveryone);
Permissions.SetValue(ref allowValue, ref denyValue, useExternalEmojis, ChannelPermission.UseExternalEmojis);
Permissions.SetValue(ref allowValue, ref denyValue, connect, ChannelPermission.Connect);
Permissions.SetValue(ref allowValue, ref denyValue, speak, ChannelPermission.Speak);
Permissions.SetValue(ref allowValue, ref denyValue, muteMembers, ChannelPermission.MuteMembers);
Permissions.SetValue(ref allowValue, ref denyValue, deafenMembers, ChannelPermission.DeafenMembers);
Permissions.SetValue(ref allowValue, ref denyValue, moveMembers, ChannelPermission.MoveMembers);
Permissions.SetValue(ref allowValue, ref denyValue, useVoiceActivation, ChannelPermission.UseVAD);
Permissions.SetValue(ref allowValue, ref denyValue, prioritySpeaker, ChannelPermission.PrioritySpeaker);
Permissions.SetValue(ref allowValue, ref denyValue, stream, ChannelPermission.Stream);
Permissions.SetValue(ref allowValue, ref denyValue, manageRoles, ChannelPermission.ManageRoles);
Permissions.SetValue(ref allowValue, ref denyValue, manageWebhooks, ChannelPermission.ManageWebhooks);
AllowValue = allowValue;
DenyValue = denyValue;
}
/// <summary>
/// Initializes a new <see cref="ChannelPermissions"/> struct with the provided permissions.
/// </summary>
public OverwritePermissions(
PermValue createInstantInvite = PermValue.Inherit,
PermValue manageChannel = PermValue.Inherit,
PermValue addReactions = PermValue.Inherit,
PermValue viewChannel = PermValue.Inherit,
PermValue sendMessages = PermValue.Inherit,
PermValue sendTTSMessages = PermValue.Inherit,
PermValue manageMessages = PermValue.Inherit,
PermValue embedLinks = PermValue.Inherit,
PermValue attachFiles = PermValue.Inherit,
PermValue readMessageHistory = PermValue.Inherit,
PermValue mentionEveryone = PermValue.Inherit,
PermValue useExternalEmojis = PermValue.Inherit,
PermValue connect = PermValue.Inherit,
PermValue speak = PermValue.Inherit,
PermValue muteMembers = PermValue.Inherit,
PermValue deafenMembers = PermValue.Inherit,
PermValue moveMembers = PermValue.Inherit,
PermValue useVoiceActivation = PermValue.Inherit,
PermValue manageRoles = PermValue.Inherit,
PermValue manageWebhooks = PermValue.Inherit,
PermValue prioritySpeaker = PermValue.Inherit,
PermValue stream = PermValue.Inherit)
: this(0, 0, createInstantInvite, manageChannel, addReactions, viewChannel, sendMessages, sendTTSMessages, manageMessages,
embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers,
moveMembers, useVoiceActivation, manageRoles, manageWebhooks, prioritySpeaker, stream) { }
/// <summary>
/// Initializes a new <see cref="OverwritePermissions" /> from the current one, changing the provided
/// non-null permissions.
/// </summary>
public OverwritePermissions Modify(
PermValue? createInstantInvite = null,
PermValue? manageChannel = null,
PermValue? addReactions = null,
PermValue? viewChannel = null,
PermValue? sendMessages = null,
PermValue? sendTTSMessages = null,
PermValue? manageMessages = null,
PermValue? embedLinks = null,
PermValue? attachFiles = null,
PermValue? readMessageHistory = null,
PermValue? mentionEveryone = null,
PermValue? useExternalEmojis = null,
PermValue? connect = null,
PermValue? speak = null,
PermValue? muteMembers = null,
PermValue? deafenMembers = null,
PermValue? moveMembers = null,
PermValue? useVoiceActivation = null,
PermValue? manageRoles = null,
PermValue? manageWebhooks = null,
PermValue? prioritySpeaker = null,
PermValue? stream = null)
=> new OverwritePermissions(AllowValue, DenyValue, createInstantInvite, manageChannel, addReactions, viewChannel, sendMessages, sendTTSMessages, manageMessages,
embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers,
moveMembers, useVoiceActivation, manageRoles, manageWebhooks, prioritySpeaker, stream);
/// <summary>
/// Creates a <see cref="List{T}"/> of all the <see cref="ChannelPermission"/> values that are allowed.
/// </summary>
/// <returns>A <see cref="List{T}"/> of all allowed <see cref="ChannelPermission"/> flags. If none, the list will be empty.</returns>
public List<ChannelPermission> ToAllowList()
{
List<ChannelPermission> perms = new List<ChannelPermission>();
for (byte i = 0; i < Permissions.MaxBits; i++)
{
// first operand must be long or ulong to shift >31 bits
ulong flag = ((ulong)1 << i);
if ((AllowValue & flag) != 0)
perms.Add((ChannelPermission)flag);
}
return perms;
}
/// <summary>
/// Creates a <see cref="List{T}"/> of all the <see cref="ChannelPermission"/> values that are denied.
/// </summary>
/// <returns>A <see cref="List{T}"/> of all denied <see cref="ChannelPermission"/> flags. If none, the list will be empty.</returns>
public List<ChannelPermission> ToDenyList()
{
List<ChannelPermission> perms = new List<ChannelPermission>();
for (byte i = 0; i < Permissions.MaxBits; i++)
{
ulong flag = ((ulong)1 << i);
if ((DenyValue & flag) != 0)
perms.Add((ChannelPermission)flag);
}
return perms;
}
public override string ToString() => $"Allow {AllowValue}, Deny {DenyValue}";
private string DebuggerDisplay =>
$"Allow {string.Join(", ", ToAllowList())}, " +
$"Deny {string.Join(", ", ToDenyList())}";
}
}
| 62.785425 | 173 | 0.670041 | [
"MIT"
] | VACEfron/DNetPlus | DNetPlus/Core/Entities/Permissions/OverwritePermissions.cs | 15,508 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Reflection.Metadata.Decoding
{
[Flags]
internal enum IdentifierOptions
{
None = 0,
TrimStart = 1,
Trim = 2,
Required = 4,
}
}
| 22.933333 | 101 | 0.642442 | [
"MIT"
] | controlflow/srm-extensions | src/System.Reflection.Metadata.Extensions/Decoding/TypeNameParsing/IdentifierOptions.cs | 346 | 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("FibonacciValidator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FibonacciValidator")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("071dcf9d-fda2-4970-940d-6e16e5089ca9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027778 | 84 | 0.750913 | [
"Unlicense"
] | dojonate/FibonacciValidator | FibonacciValidator/Properties/AssemblyInfo.cs | 1,372 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Pssg.Css.Interfaces.DynamicsAutorest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Microsoft.Dynamics.CRM.discount
/// </summary>
public partial class MicrosoftDynamicsCRMdiscount
{
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMdiscount
/// class.
/// </summary>
public MicrosoftDynamicsCRMdiscount()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MicrosoftDynamicsCRMdiscount
/// class.
/// </summary>
public MicrosoftDynamicsCRMdiscount(bool? isamounttype = default(bool?), string discountid = default(string), string name = default(string), string _transactioncurrencyidValue = default(string), string _createdonbehalfbyValue = default(string), string _createdbyValue = default(string), string versionnumber = default(string), string organizationid = default(string), string _modifiedbyValue = default(string), int? utcconversiontimezonecode = default(int?), string _discounttypeidValue = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), int? importsequencenumber = default(int?), decimal? lowquantity = default(decimal?), decimal? highquantity = default(decimal?), int? timezoneruleversionnumber = default(int?), decimal? exchangerate = default(decimal?), string _modifiedonbehalfbyValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), decimal? amountBase = default(decimal?), decimal? percentage = default(decimal?), decimal? amount = default(decimal?), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMsyncerror> discountSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMasyncoperation> discountAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMmailboxtrackingfolder> discountMailboxTrackingFolders = default(IList<MicrosoftDynamicsCRMmailboxtrackingfolder>), IList<MicrosoftDynamicsCRMprocesssession> discountProcessSessions = default(IList<MicrosoftDynamicsCRMprocesssession>), IList<MicrosoftDynamicsCRMbulkdeletefailure> discountBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> discountPrincipalObjectAttributeAccesses = default(IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess>), MicrosoftDynamicsCRMtransactioncurrency transactioncurrencyid = default(MicrosoftDynamicsCRMtransactioncurrency), MicrosoftDynamicsCRMdiscounttype discounttypeid = default(MicrosoftDynamicsCRMdiscounttype))
{
Isamounttype = isamounttype;
Discountid = discountid;
Name = name;
this._transactioncurrencyidValue = _transactioncurrencyidValue;
this._createdonbehalfbyValue = _createdonbehalfbyValue;
this._createdbyValue = _createdbyValue;
Versionnumber = versionnumber;
Organizationid = organizationid;
this._modifiedbyValue = _modifiedbyValue;
Utcconversiontimezonecode = utcconversiontimezonecode;
this._discounttypeidValue = _discounttypeidValue;
Modifiedon = modifiedon;
Overriddencreatedon = overriddencreatedon;
Importsequencenumber = importsequencenumber;
Lowquantity = lowquantity;
Highquantity = highquantity;
Timezoneruleversionnumber = timezoneruleversionnumber;
Exchangerate = exchangerate;
this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue;
Createdon = createdon;
AmountBase = amountBase;
Percentage = percentage;
Amount = amount;
Createdby = createdby;
Createdonbehalfby = createdonbehalfby;
Modifiedby = modifiedby;
Modifiedonbehalfby = modifiedonbehalfby;
DiscountSyncErrors = discountSyncErrors;
DiscountAsyncOperations = discountAsyncOperations;
DiscountMailboxTrackingFolders = discountMailboxTrackingFolders;
DiscountProcessSessions = discountProcessSessions;
DiscountBulkDeleteFailures = discountBulkDeleteFailures;
DiscountPrincipalObjectAttributeAccesses = discountPrincipalObjectAttributeAccesses;
Transactioncurrencyid = transactioncurrencyid;
Discounttypeid = discounttypeid;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isamounttype")]
public bool? Isamounttype { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "discountid")]
public string Discountid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_transactioncurrencyid_value")]
public string _transactioncurrencyidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdonbehalfby_value")]
public string _createdonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdby_value")]
public string _createdbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public string Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "organizationid")]
public string Organizationid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedby_value")]
public string _modifiedbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "utcconversiontimezonecode")]
public int? Utcconversiontimezonecode { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_discounttypeid_value")]
public string _discounttypeidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedon")]
public System.DateTimeOffset? Modifiedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "overriddencreatedon")]
public System.DateTimeOffset? Overriddencreatedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "importsequencenumber")]
public int? Importsequencenumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "lowquantity")]
public decimal? Lowquantity { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "highquantity")]
public decimal? Highquantity { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezoneruleversionnumber")]
public int? Timezoneruleversionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "exchangerate")]
public decimal? Exchangerate { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedonbehalfby_value")]
public string _modifiedonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdon")]
public System.DateTimeOffset? Createdon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "amount_base")]
public decimal? AmountBase { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "percentage")]
public decimal? Percentage { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "amount")]
public decimal? Amount { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdby")]
public MicrosoftDynamicsCRMsystemuser Createdby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedby")]
public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Discount_SyncErrors")]
public IList<MicrosoftDynamicsCRMsyncerror> DiscountSyncErrors { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Discount_AsyncOperations")]
public IList<MicrosoftDynamicsCRMasyncoperation> DiscountAsyncOperations { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "discount_MailboxTrackingFolders")]
public IList<MicrosoftDynamicsCRMmailboxtrackingfolder> DiscountMailboxTrackingFolders { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Discount_ProcessSessions")]
public IList<MicrosoftDynamicsCRMprocesssession> DiscountProcessSessions { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Discount_BulkDeleteFailures")]
public IList<MicrosoftDynamicsCRMbulkdeletefailure> DiscountBulkDeleteFailures { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "discount_PrincipalObjectAttributeAccesses")]
public IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> DiscountPrincipalObjectAttributeAccesses { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "transactioncurrencyid")]
public MicrosoftDynamicsCRMtransactioncurrency Transactioncurrencyid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "discounttypeid")]
public MicrosoftDynamicsCRMdiscounttype Discounttypeid { get; set; }
}
}
| 44.893701 | 2,462 | 0.664737 | [
"Apache-2.0"
] | GeorgeWalker/pssg-psd-csa | interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMdiscount.cs | 11,403 | C# |
namespace eKuharica.WinUI.Recipes
{
partial class frmAddRecipes
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAddRecipes));
this.btnRecipePreview = new System.Windows.Forms.Button();
this.btnSubmit = new System.Windows.Forms.Button();
this.lblTitle = new System.Windows.Forms.Label();
this.txtTitle = new System.Windows.Forms.TextBox();
this.txtIntroduction = new System.Windows.Forms.TextBox();
this.lblIntroduction = new System.Windows.Forms.Label();
this.pbCoverPicture = new System.Windows.Forms.PictureBox();
this.lblCoverPicture = new System.Windows.Forms.Label();
this.ofdPicture = new System.Windows.Forms.OpenFileDialog();
this.panel1 = new System.Windows.Forms.Panel();
this.lblIngredients = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.txtMethod = new System.Windows.Forms.TextBox();
this.lblPreparation = new System.Windows.Forms.Label();
this.txtServing = new System.Windows.Forms.TextBox();
this.lblServing = new System.Windows.Forms.Label();
this.txtAdvice = new System.Windows.Forms.TextBox();
this.lblAdvice = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.lblTags = new System.Windows.Forms.Label();
this.lblPreparationTime = new System.Windows.Forms.Label();
this.lblWeightOfPreparation = new System.Windows.Forms.Label();
this.lblMealGroup = new System.Windows.Forms.Label();
this.lblMin = new System.Windows.Forms.Label();
this.cmbWeightOfPreparation = new System.Windows.Forms.ComboBox();
this.cmbMealType = new System.Windows.Forms.ComboBox();
this.nudPreparationTime = new System.Windows.Forms.NumericUpDown();
this.txtIngridients = new System.Windows.Forms.TextBox();
this.gbTags = new System.Windows.Forms.GroupBox();
this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
this.lblBack = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pbCoverPicture)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudPreparationTime)).BeginInit();
this.gbTags.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit();
this.SuspendLayout();
//
// btnRecipePreview
//
resources.ApplyResources(this.btnRecipePreview, "btnRecipePreview");
this.btnRecipePreview.Name = "btnRecipePreview";
this.btnRecipePreview.UseVisualStyleBackColor = true;
this.btnRecipePreview.Click += new System.EventHandler(this.btnRecipePreview_Click);
//
// btnSubmit
//
resources.ApplyResources(this.btnSubmit, "btnSubmit");
this.btnSubmit.Name = "btnSubmit";
this.btnSubmit.UseVisualStyleBackColor = true;
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
//
// lblTitle
//
resources.ApplyResources(this.lblTitle, "lblTitle");
this.lblTitle.Name = "lblTitle";
//
// txtTitle
//
resources.ApplyResources(this.txtTitle, "txtTitle");
this.txtTitle.Name = "txtTitle";
//
// txtIntroduction
//
resources.ApplyResources(this.txtIntroduction, "txtIntroduction");
this.txtIntroduction.Name = "txtIntroduction";
//
// lblIntroduction
//
resources.ApplyResources(this.lblIntroduction, "lblIntroduction");
this.lblIntroduction.Name = "lblIntroduction";
//
// pbCoverPicture
//
resources.ApplyResources(this.pbCoverPicture, "pbCoverPicture");
this.pbCoverPicture.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pbCoverPicture.Name = "pbCoverPicture";
this.pbCoverPicture.TabStop = false;
this.pbCoverPicture.Click += new System.EventHandler(this.pbCoverPicture_Click);
//
// lblCoverPicture
//
resources.ApplyResources(this.lblCoverPicture, "lblCoverPicture");
this.lblCoverPicture.Name = "lblCoverPicture";
//
// ofdPicture
//
this.ofdPicture.FileName = "ofdPicture";
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.Desktop;
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// lblIngredients
//
resources.ApplyResources(this.lblIngredients, "lblIngredients");
this.lblIngredients.Name = "lblIngredients";
//
// panel2
//
this.panel2.BackColor = System.Drawing.SystemColors.Desktop;
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Name = "panel2";
//
// txtMethod
//
resources.ApplyResources(this.txtMethod, "txtMethod");
this.txtMethod.Name = "txtMethod";
//
// lblPreparation
//
resources.ApplyResources(this.lblPreparation, "lblPreparation");
this.lblPreparation.Name = "lblPreparation";
//
// txtServing
//
resources.ApplyResources(this.txtServing, "txtServing");
this.txtServing.Name = "txtServing";
//
// lblServing
//
resources.ApplyResources(this.lblServing, "lblServing");
this.lblServing.Name = "lblServing";
//
// txtAdvice
//
resources.ApplyResources(this.txtAdvice, "txtAdvice");
this.txtAdvice.Name = "txtAdvice";
//
// lblAdvice
//
resources.ApplyResources(this.lblAdvice, "lblAdvice");
this.lblAdvice.Name = "lblAdvice";
//
// panel3
//
this.panel3.BackColor = System.Drawing.SystemColors.Desktop;
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// lblTags
//
resources.ApplyResources(this.lblTags, "lblTags");
this.lblTags.Name = "lblTags";
//
// lblPreparationTime
//
resources.ApplyResources(this.lblPreparationTime, "lblPreparationTime");
this.lblPreparationTime.Name = "lblPreparationTime";
//
// lblWeightOfPreparation
//
resources.ApplyResources(this.lblWeightOfPreparation, "lblWeightOfPreparation");
this.lblWeightOfPreparation.Name = "lblWeightOfPreparation";
//
// lblMealGroup
//
resources.ApplyResources(this.lblMealGroup, "lblMealGroup");
this.lblMealGroup.Name = "lblMealGroup";
//
// lblMin
//
resources.ApplyResources(this.lblMin, "lblMin");
this.lblMin.Name = "lblMin";
//
// cmbWeightOfPreparation
//
this.cmbWeightOfPreparation.FormattingEnabled = true;
resources.ApplyResources(this.cmbWeightOfPreparation, "cmbWeightOfPreparation");
this.cmbWeightOfPreparation.Name = "cmbWeightOfPreparation";
//
// cmbMealType
//
this.cmbMealType.FormattingEnabled = true;
resources.ApplyResources(this.cmbMealType, "cmbMealType");
this.cmbMealType.Name = "cmbMealType";
//
// nudPreparationTime
//
resources.ApplyResources(this.nudPreparationTime, "nudPreparationTime");
this.nudPreparationTime.Name = "nudPreparationTime";
//
// txtIngridients
//
resources.ApplyResources(this.txtIngridients, "txtIngridients");
this.txtIngridients.Name = "txtIngridients";
//
// gbTags
//
this.gbTags.Controls.Add(this.lblPreparationTime);
this.gbTags.Controls.Add(this.lblTags);
this.gbTags.Controls.Add(this.cmbMealType);
this.gbTags.Controls.Add(this.nudPreparationTime);
this.gbTags.Controls.Add(this.lblMealGroup);
this.gbTags.Controls.Add(this.cmbWeightOfPreparation);
this.gbTags.Controls.Add(this.lblMin);
this.gbTags.Controls.Add(this.lblWeightOfPreparation);
resources.ApplyResources(this.gbTags, "gbTags");
this.gbTags.Name = "gbTags";
this.gbTags.TabStop = false;
//
// errorProvider1
//
this.errorProvider1.ContainerControl = this;
//
// lblBack
//
resources.ApplyResources(this.lblBack, "lblBack");
this.lblBack.BackColor = System.Drawing.SystemColors.ButtonFace;
this.lblBack.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblBack.Name = "lblBack";
this.lblBack.Click += new System.EventHandler(this.lblBack_Click);
//
// frmAddRecipes
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ControlBox = false;
this.Controls.Add(this.lblBack);
this.Controls.Add(this.gbTags);
this.Controls.Add(this.txtIngridients);
this.Controls.Add(this.panel3);
this.Controls.Add(this.txtAdvice);
this.Controls.Add(this.lblAdvice);
this.Controls.Add(this.txtServing);
this.Controls.Add(this.lblServing);
this.Controls.Add(this.txtMethod);
this.Controls.Add(this.lblPreparation);
this.Controls.Add(this.panel2);
this.Controls.Add(this.lblIngredients);
this.Controls.Add(this.panel1);
this.Controls.Add(this.lblCoverPicture);
this.Controls.Add(this.pbCoverPicture);
this.Controls.Add(this.txtIntroduction);
this.Controls.Add(this.lblIntroduction);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.btnSubmit);
this.Controls.Add(this.btnRecipePreview);
this.Name = "frmAddRecipes";
this.Load += new System.EventHandler(this.frmAddRecipes_Load);
((System.ComponentModel.ISupportInitialize)(this.pbCoverPicture)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudPreparationTime)).EndInit();
this.gbTags.ResumeLayout(false);
this.gbTags.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnRecipePreview;
private System.Windows.Forms.Button btnSubmit;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.TextBox txtTitle;
private System.Windows.Forms.TextBox txtIntroduction;
private System.Windows.Forms.Label lblIntroduction;
private System.Windows.Forms.PictureBox pbCoverPicture;
private System.Windows.Forms.Label lblCoverPicture;
private System.Windows.Forms.OpenFileDialog ofdPicture;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label lblIngredients;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.TextBox txtMethod;
private System.Windows.Forms.Label lblPreparation;
private System.Windows.Forms.TextBox txtServing;
private System.Windows.Forms.Label lblServing;
private System.Windows.Forms.TextBox txtAdvice;
private System.Windows.Forms.Label lblAdvice;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Label lblTags;
private System.Windows.Forms.Label lblPreparationTime;
private System.Windows.Forms.Label lblWeightOfPreparation;
private System.Windows.Forms.Label lblMealGroup;
private System.Windows.Forms.Label lblMin;
private System.Windows.Forms.ComboBox cmbWeightOfPreparation;
private System.Windows.Forms.ComboBox cmbMealType;
private System.Windows.Forms.NumericUpDown nudPreparationTime;
private System.Windows.Forms.TextBox txtIngridients;
private System.Windows.Forms.GroupBox gbTags;
private System.Windows.Forms.ErrorProvider errorProvider1;
private System.Windows.Forms.Label lblBack;
}
} | 45.278997 | 145 | 0.598657 | [
"MIT"
] | almahuskovic/eKuharica | eKuharica/eKuharica.WinUI/Recipes/frmAddRecipes.Designer.cs | 14,446 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
namespace Utility
{
public abstract class Data
{
private static string connectionString = string.Empty;
static Data()
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
{
connectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
}
if (connectionString == string.Empty)
{
if (ConfigurationManager.AppSettings["default"] == null)
{
connectionString = ConfigurationManager.AppSettings["default"].ToString();
}
}
if (string.IsNullOrEmpty(connectionString))
throw new Exception("Não foi encontrado uma conexão.");
}
public static int ExecuteNonQuery(string commandText)
{
return ExecuteNonQuery(commandText, null, CommandType.StoredProcedure);
}
public static int ExecuteNonQuery(string commandText, List<SqlParameter> parameters)
{
return ExecuteNonQuery(commandText, parameters, CommandType.StoredProcedure);
}
public static int ExecuteNonQuery(string commandText, List<SqlParameter> parameters, CommandType commandType)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.Clear();
command.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
connection.Close();
connection.Dispose();
return recordsAffected;
}
}
}
public static object ExecuteScalar(string commandText)
{
return ExecuteScalar(commandText, null, CommandType.StoredProcedure);
}
public static object ExecuteScalar(string commandText, List<SqlParameter> parameters)
{
return ExecuteScalar(commandText, parameters, CommandType.StoredProcedure);
}
public static object ExecuteScalar(string commandText, List<SqlParameter> parameters, CommandType commandType)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.Clear();
command.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
object unknownType = command.ExecuteScalar();
connection.Close();
connection.Dispose();
return unknownType;
}
}
}
public static DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(commandText, null, CommandType.StoredProcedure);
}
public static DataTable ExecuteDataTable(string commandText, List<SqlParameter> parameters)
{
return ExecuteDataTable(commandText, parameters, CommandType.StoredProcedure);
}
public static DataTable ExecuteDataTable(string commandText, List<SqlParameter> parameters, CommandType commandType)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.Clear();
command.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
DataTable dataTable = new DataTable();
dataTable.Load(command.ExecuteReader());
connection.Close();
connection.Dispose();
return dataTable;
}
}
}
public static DataSet ExecuteDataSet(string commandText)
{
return ExecuteDataSet(commandText, null, CommandType.StoredProcedure);
}
public static DataSet ExecuteDataSet(string commandText, List<SqlParameter> parameters)
{
return ExecuteDataSet(commandText, parameters, CommandType.StoredProcedure);
}
public static DataSet ExecuteDataSet(string commandText, List<SqlParameter> parameters, CommandType commandType)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = commandType;
if (parameters != null)
{
command.Parameters.Clear();
command.Parameters.AddRange(parameters.ToArray());
}
command.CommandTimeout = 600;
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
connection.Close();
connection.Dispose();
return dataSet;
}
}
}
public static SqlParameter CreateParameter(string name, object value)
{
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = name;
parameter.SqlValue = value;
parameter.Value = value;
if (value == null)
{
parameter.SqlValue = DBNull.Value;
parameter.IsNullable = true;
}
parameter.Direction = ParameterDirection.Input;
return parameter;
}
}
}
| 35.412371 | 124 | 0.546579 | [
"Apache-2.0"
] | LUCASDESENVOLVEDOR/ProjetoUtility | Utility/Data.cs | 6,874 | C# |
using Masuit.MyBlogs.Core.Common;
using Masuit.MyBlogs.Core.Extensions;
using Masuit.MyBlogs.Core.Models.ViewModel;
using Masuit.Tools;
using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
using Masuit.Tools.Files;
using Masuit.Tools.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Polly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Masuit.MyBlogs.Core.Controllers
{
/// <summary>
/// 资源管理器
/// </summary>
[Route("[controller]/[action]")]
public class FileController : AdminController
{
public IWebHostEnvironment HostEnvironment { get; set; }
/// <summary>
///
/// </summary>
public ISevenZipCompressor SevenZipCompressor { get; set; }
/// <summary>
/// 获取文件列表
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public ActionResult GetFiles(string path)
{
var files = Directory.GetFiles(HostEnvironment.WebRootPath + path).OrderByDescending(s => s).Select(s => new
{
filename = Path.GetFileName(s),
path = s
}).ToList();
return ResultData(files);
}
/// <summary>
/// 读取文件内容
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public ActionResult Read(string filename)
{
if (System.IO.File.Exists(filename))
{
string text = new FileInfo(filename).ShareReadWrite().ReadAllText(Encoding.UTF8);
return ResultData(text);
}
return ResultData(null, false, "文件不存在!");
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="filename"></param>
/// <param name="content"></param>
/// <returns></returns>
public ActionResult Save(string filename, string content)
{
try
{
new FileInfo(filename).ShareReadWrite().WriteAllText(content, Encoding.UTF8);
return ResultData(null, message: "保存成功");
}
catch (IOException e)
{
LogManager.Error(GetType(), e);
return ResultData(null, false, "保存失败");
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult> Upload(string destination)
{
var form = await Request.ReadFormAsync();
foreach (var t in form.Files)
{
string path = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'), destination.TrimStart('\\', '/'), t.FileName);
await using var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
await t.CopyToAsync(fs);
}
return Json(new
{
result = new List<object>()
});
}
/// <summary>
/// 操作文件
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Handle([FromBody] FileRequest req)
{
var list = new List<object>();
var root = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'));
switch (req.Action)
{
case "list":
var path = Path.Combine(root, req.Path.TrimStart('\\', '/'));
var dirs = Directory.GetDirectories(path);
var files = Directory.GetFiles(path);
list.AddRange(dirs.Select(s => new DirectoryInfo(s)).Select(dirinfo => new FileList
{
date = dirinfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
name = dirinfo.Name,
size = 0,
type = "dir"
}).Union(files.Select(s => new FileInfo(s)).Select(info => new FileList
{
name = info.Name,
size = info.Length,
date = info.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
type = "file"
})));
break;
case "remove":
req.Items.ForEach(s =>
{
s = Path.Combine(root, s.TrimStart('\\', '/'));
try
{
Policy.Handle<IOException>().WaitAndRetry(5, i => TimeSpan.FromSeconds(1)).Execute(() => System.IO.File.Delete(s));
}
catch
{
Policy.Handle<IOException>().WaitAndRetry(5, i => TimeSpan.FromSeconds(1)).Execute(() => Directory.Delete(s, true));
}
});
list.Add(new
{
success = "true"
});
break;
case "rename":
case "move":
string newpath;
if (!string.IsNullOrEmpty(req.Item))
{
newpath = Path.Combine(root, req.NewItemPath?.TrimStart('\\', '/'));
path = Path.Combine(root, req.Item.TrimStart('\\', '/'));
try
{
System.IO.File.Move(path, newpath);
}
catch
{
Directory.Move(path, newpath);
}
}
else
{
newpath = Path.Combine(root, req.NewPath.TrimStart('\\', '/'));
req.Items.ForEach(s =>
{
try
{
System.IO.File.Move(Path.Combine(root, s.TrimStart('\\', '/')), Path.Combine(newpath, Path.GetFileName(s)));
}
catch
{
Directory.Move(Path.Combine(root, s.TrimStart('\\', '/')), Path.Combine(newpath, Path.GetFileName(s)));
}
});
}
list.Add(new
{
success = "true"
});
break;
case "copy":
if (!string.IsNullOrEmpty(req.Item))
{
System.IO.File.Copy(Path.Combine(root, req.Item.TrimStart('\\', '/')), Path.Combine(root, req.NewItemPath.TrimStart('\\', '/')));
}
else
{
newpath = Path.Combine(root, req.NewPath.TrimStart('\\', '/'));
req.Items.ForEach(s => System.IO.File.Copy(Path.Combine(root, s.TrimStart('\\', '/')), !string.IsNullOrEmpty(req.SingleFilename) ? Path.Combine(newpath, req.SingleFilename) : Path.Combine(newpath, Path.GetFileName(s))));
}
list.Add(new
{
success = "true"
});
break;
case "edit":
new FileInfo(Path.Combine(root, req.Item.TrimStart('\\', '/'))).ShareReadWrite().WriteAllText(req.Content, Encoding.UTF8);
list.Add(new
{
success = "true"
});
break;
case "getContent":
return Json(new
{
result = new FileInfo(Path.Combine(root, req.Item.TrimStart('\\', '/'))).ShareReadWrite().ReadAllText(Encoding.UTF8)
});
case "createFolder":
list.Add(new
{
success = Directory.CreateDirectory(Path.Combine(root, req.NewPath.TrimStart('\\', '/'))).Exists.ToString()
});
break;
case "changePermissions":
//todo:文件权限修改
break;
case "compress":
var filename = Path.Combine(Path.Combine(root, req.Destination.TrimStart('\\', '/')), Path.GetFileNameWithoutExtension(req.CompressedFilename) + ".zip");
SevenZipCompressor.Zip(req.Items.Select(s => Path.Combine(root, s.TrimStart('\\', '/'))), filename);
list.Add(new
{
success = "true"
});
break;
case "extract":
var folder = Path.Combine(Path.Combine(root, req.Destination.TrimStart('\\', '/')), req.FolderName.Trim('/', '\\'));
var zip = Path.Combine(root, req.Item.TrimStart('\\', '/'));
SevenZipCompressor.Extract(zip, folder);
list.Add(new
{
success = "true"
});
break;
}
return Json(new
{
result = list
});
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="path"></param>
/// <param name="items"></param>
/// <param name="toFilename"></param>
/// <returns></returns>
[HttpGet]
public ActionResult Handle(string path, string[] items, string toFilename)
{
path = path?.TrimStart('\\', '/') ?? "";
var root = CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/');
var file = Path.Combine(HostEnvironment.ContentRootPath, root, path);
switch (Request.Query["action"])
{
case "download":
if (System.IO.File.Exists(file))
{
return this.ResumePhysicalFile(file, Path.GetFileName(file));
}
break;
case "downloadMultiple":
var buffer = SevenZipCompressor.ZipStream(items.Select(s => Path.Combine(HostEnvironment.ContentRootPath, root, s.TrimStart('\\', '/')))).ToArray();
return this.ResumeFile(buffer, Path.GetFileName(toFilename));
}
throw new NotFoundException("文件未找到");
}
}
} | 39.792727 | 244 | 0.440921 | [
"MIT"
] | chjenlove113/Masuit.MyBlogs | src/Masuit.MyBlogs.Core/Controllers/FileController.cs | 11,061 | C# |
using AbpCoreEf6Sample.EntityFramework.Seed.Host;
using AbpCoreEf6Sample.EntityFramework.Seed.Tenants;
namespace AbpCoreEf6Sample.EntityFramework.Seed
{
public static class SeedHelper
{
public static void SeedHostDb(AbpCoreEf6SampleDbContext context)
{
context.SuppressAutoSetTenantId = true;
// Host seed
new InitialHostDbBuilder(context).Create();
// Default tenant seed (in host database).
new DefaultTenantBuilder(context).Create();
new TenantRoleAndUserBuilder(context, 1).Create();
}
}
}
| 28.857143 | 72 | 0.669967 | [
"MIT"
] | TechnicalConsultant123/aspnetboilerplate-samples | AbpCoreEf6Sample/aspnet-core/src/AbpCoreEf6Sample.EntityFramework/EntityFramework/Seed/SeedHelper.cs | 608 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EveneumSample.Models;
namespace EveneumSample.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 24.342105 | 112 | 0.642162 | [
"MIT"
] | Eveneum/Sample | EveneumSample/Controllers/HomeController.cs | 927 | C# |
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace excel2json
{
/// <summary>
/// 将DataTable对象,转换成JSON string,并保存到文件中
/// </summary>
class JsonExporter : ExcelExporter
{
public override void SerializeObject()
{
var jsonSettings = new JsonSerializerSettings
{
DateFormatString = mOptions.DateFormat,
Formatting = Formatting.Indented
};
//-- convert to json string
mContext = JsonConvert.SerializeObject(sheetValueList, jsonSettings);
}
/// <summary>
/// 构造函数:完成内部数据创建
/// </summary>
/// <param name="excel">ExcelLoader Object</param>
public JsonExporter(ExcelLoader excel, Program.Options mOptions) : base(excel, mOptions)
{
}
public override string SerializeObjectToString(string sheetName, object sheetValue)
{
var jsonSettings = new JsonSerializerSettings
{
DateFormatString = mOptions.DateFormat,
Formatting = Formatting.Indented
};
//-- convert to json string
string strContext = JsonConvert.SerializeObject(sheetValue, jsonSettings);
return strContext;
}
/// <summary>
/// 对于表格中的空值,找到一列中的非空值,并构造一个同类型的默认值
/// </summary>
private object getColumnDefault(DataTable sheet, DataColumn column, int firstDataRow)
{
for (int i = firstDataRow; i < sheet.Rows.Count; i++)
{
object value = sheet.Rows[i][column];
Type valueType = value.GetType();
if (valueType != typeof(System.DBNull))
{
if (valueType.IsValueType)
return Activator.CreateInstance(valueType);
break;
}
}
return "";
}
/// <summary>
/// 将内部数据转换成Json文本,并保存至文件
/// </summary>
/// <param name="jsonPath">输出文件路径</param>
public void SaveToFile(string filePath, Encoding encoding)
{
//-- 保存文件
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (TextWriter writer = new StreamWriter(file, encoding))
writer.Write(mContext);
}
}
}
}
| 32.898734 | 98 | 0.529819 | [
"MIT"
] | rooong/excel2json | JsonExporter.cs | 2,773 | C# |
using System;
using Stylophone.Common.ViewModels;
using Stylophone.iOS.Helpers;
namespace Stylophone.iOS.ViewControllers
{
public interface IViewController<T>: IPreparableViewController where T: ViewModelBase
{
T ViewModel { get; }
PropertyBinder<T> Binder { get; }
}
public interface IPreparableViewController
{
void Prepare(object parameter)
{
}
}
}
| 19.136364 | 89 | 0.669834 | [
"MIT"
] | Difegue/Stylophone | Sources/Stylophone.iOS/ViewControllers/IViewController.cs | 423 | C# |
using Mosa.Runtime;
using Mosa.Runtime.x86;
using System.Collections.Generic;
namespace Mosa.External.x86
{
public readonly struct MemoryBlock
{
private readonly Pointer address;
private readonly uint size;
private readonly bool IsManaged;
public Pointer Address { get { return address; } }
public uint Size { get { return size; } }
public MemoryBlock(Pointer address, uint size)
{
this.size = size;
this.address = address;
IsManaged = false;
}
public MemoryBlock(uint size)
{
this.size = size;
address = GC.AllocateObject(size);
IsManaged = true;
}
public MemoryBlock(byte[] data)
{
size = (uint)data.Length;
address = GC.AllocateObject(size);
IsManaged = true;
for (int i = 0; i < data.Length; i++)
Write8((uint)i, data[i]);
}
public MemoryBlock(List<byte> data)
{
size = (uint)data.Count;
address = GC.AllocateObject(size);
IsManaged = true;
for (int i = 0; i < data.Count; i++)
Write8((uint)i, data[i]);
}
public MemoryBlock(int[] data)
{
size = (uint)data.Length * 4;
address = GC.AllocateObject(size);
IsManaged = true;
for (int i = 0; i < data.Length; i++)
this[(uint)i] = data[i];
}
public MemoryBlock(List<int> data)
{
size = (uint)data.Count * 4;
address = GC.AllocateObject(size);
IsManaged = true;
for (int i = 0; i < data.Count; i++)
this[(uint)i] = data[i];
}
public void Free()
{
if (IsManaged)
GC.Dispose((uint)address, size);
GC.Dispose(this);
}
public int this[uint offset]
{
get { return (int)address.Load32(offset * 4); }
set { address.Store32(offset * 4, value); }
}
public void Clear()
{
ASM.MEMFILL((uint)address, size, 0);
}
public void FlushToArray(byte[] dest)
{
for (uint i = 0; i < dest.Length; i++)
dest[i] = Read8(i);
}
public byte Read8(uint offset)
{
return address.Load8(offset);
}
public void Write8(uint offset, byte value)
{
if (offset < size)
{
address.Store8(offset, value);
}
}
public ushort Read16(uint offset)
{
return address.Load16(offset);
}
public void Write16(uint offset, ushort value)
{
if (offset < size)
{
address.Store16(offset, value);
}
}
public uint Read24(uint offset)
{
return address.Load16(offset) | (uint)(address.Load8(offset + 2) << 16);
}
public void Write24(uint offset, uint value)
{
if (offset < size)
{
address.Store16(offset, (ushort)(value & 0xFFFF));
address.Store8(offset + 2, (byte)((value >> 16) & 0xFF));
}
}
public uint Read32(uint offset)
{
return address.Load32(offset);
}
public void Write32(uint offset, uint value)
{
if (offset < size)
{
address.Store32(offset, value);
}
}
}
}
| 23.722581 | 84 | 0.466413 | [
"BSD-3-Clause"
] | TRDP1404/MOSA-Core | Mosa/Mosa.External.x86/MemoryBlock.cs | 3,679 | C# |
//--------------------------------------------------
// <copyright file="AppiumIosUnitTests.cs" company="Magenic">
// Copyright 2021 Magenic, All rights Reserved
// </copyright>
// <summary>Test class for ios related functions</summary>
//--------------------------------------------------
using Magenic.Maqs.BaseAppiumTest;
using Magenic.Maqs.Utilities.Helper;
using Magenic.Maqs.Utilities.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using System.IO;
namespace AppiumUnitTests
{
/// <summary>
/// iOS related Appium tests
/// </summary>
[TestClass]
public class AppiumIosUnitTests : BaseAppiumTest
{
/// <summary>
/// Tests the creation of the Appium iOS Driver
/// </summary>
[TestMethod]
[TestCategory(TestCategories.Appium)]
public void AppiumIOSDriverTest()
{
Assert.IsNotNull(this.TestObject.AppiumDriver);
}
/// <summary>
/// Tests lazy element with Appium iOS Driver
/// </summary>
[TestMethod]
[TestCategory(TestCategories.Appium)]
public void AppiumIOSDriverLazyTest()
{
Assert.IsNotNull(this.TestObject.AppiumDriver);
this.AppiumDriver.Navigate().GoToUrl(Config.GetValueForSection(ConfigSection.AppiumMaqs, "WebSiteBase"));
LazyMobileElement lazy = new LazyMobileElement(this.TestObject, By.XPath("//button[@class=\"navbar-toggle\"]"), "Nav toggle");
Assert.IsTrue(lazy.Enabled, "Expect enabled");
Assert.IsTrue(lazy.Displayed, "Expect displayed");
Assert.IsTrue(lazy.ExistsNow, "Expect exists now");
lazy.Click();
}
[TestMethod]
[TestCategory(TestCategories.Appium)]
public void AssertFuncFailPath()
{
Assert.IsNotNull(this.TestObject.AppiumDriver);
this.AppiumDriver.Navigate().GoToUrl(Config.GetValueForSection(ConfigSection.AppiumMaqs, "WebSiteBase"));
Log = new FileLogger(string.Empty, "AssertFuncFailPath.txt", MessageType.GENERIC, true);
AppiumSoftAssert appiumSoftAssert = new AppiumSoftAssert(TestObject);
string logLocation = ((IFileLogger)Log).FilePath;
string screenShotLocation = $"{logLocation.Substring(0, logLocation.LastIndexOf('.'))} assertName (1).Png";
bool isFalse = appiumSoftAssert.Assert(() => Assert.IsTrue(false), "assertName");
Assert.IsTrue(File.Exists(screenShotLocation), "Fail to find screenshot");
File.Delete(screenShotLocation);
File.Delete(logLocation);
Assert.IsFalse(isFalse);
}
/// <summary>
/// Sets capabilities for testing the iOS Driver creation
/// </summary>
/// <returns>iOS instance of the Appium Driver</returns>
protected override AppiumDriver<IWebElement> GetMobileDevice()
{
AppiumOptions options = new AppiumOptions();
options.AddAdditionalCapability("deviceName", "iPhone 8 Simulator");
options.AddAdditionalCapability("deviceOrientation", "portrait");
options.AddAdditionalCapability("platformVersion", "12.2");
options.AddAdditionalCapability("platformName", "iOS");
options.AddAdditionalCapability("browserName", "Safari");
options.AddAdditionalCapability("username", Config.GetValueForSection(ConfigSection.AppiumCapsMaqs, "userName"));
options.AddAdditionalCapability("accessKey", Config.GetValueForSection(ConfigSection.AppiumCapsMaqs, "accessKey"));
return AppiumDriverFactory.GetIOSDriver(AppiumConfig.GetMobileHubUrl(), options, AppiumConfig.GetMobileCommandTimeout());
}
}
}
| 41.532609 | 138 | 0.645381 | [
"MIT"
] | Magenic/MAQS | Framework/AppiumUnitTests/AppiumIosUnitTests.cs | 3,823 | C# |
//*******************************************************************************************//
// //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer //
// //
// Also available as Web API! Free Trial Sign Up: https://secure.bytescout.com/users/sign_up //
// //
// Copyright © 2017-2018 ByteScout Inc. All rights reserved. //
// http://www.bytescout.com //
// //
//*******************************************************************************************//
using System;
using System.IO;
using System.Diagnostics;
using Bytescout.PDFExtractor;
namespace ReduceMemoryUsage
{
class Program
{
static void Main(string[] args)
{
// When processing huge PDF documents you may run into OutOfMemoryException.
// This example demonstrates a way to spare the memory by disabling page data caching.
// Create Bytescout.PDFExtractor.TextExtractor instance
using (TextExtractor extractor = new TextExtractor("demo", "demo"))
{
try
{
// Load sample PDF document
extractor.LoadDocumentFromFile("sample2.pdf");
// Disable page data caching, so processed pages wiil be disposed automatically
extractor.PageDataCaching = PageDataCaching.None;
// Save extracted text to file
extractor.SaveTextToFile("output.txt");
}
catch (PDFExtractorException exception)
{
Console.Write(exception.ToString());
}
}
// Open result document in default associated application (for demo purpose)
ProcessStartInfo processStartInfo = new ProcessStartInfo("output.txt");
processStartInfo.UseShellExecute = true;
Process.Start(processStartInfo);
}
}
}
| 45.444444 | 100 | 0.426243 | [
"Apache-2.0"
] | jboddiford/ByteScout-SDK-SourceCode | PDF Extractor SDK/C#/Reduce Memory Usage for PDF to Text/Program.cs | 2,455 | 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 evidently-2021-02-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.CloudWatchEvidently.Model
{
/// <summary>
/// A structure that contains the information about one evaluation event or custom event
/// sent to Evidently. This is a JSON payload. If this event specifies a pre-defined event
/// type, the payload must follow the defined event schema.
/// </summary>
public partial class Event
{
private string _data;
private DateTime? _timestamp;
private EventType _type;
/// <summary>
/// Gets and sets the property Data.
/// <para>
/// The event data.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Data
{
get { return this._data; }
set { this._data = value; }
}
// Check to see if Data property is set
internal bool IsSetData()
{
return this._data != null;
}
/// <summary>
/// Gets and sets the property Timestamp.
/// <para>
/// The timestamp of the event.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DateTime Timestamp
{
get { return this._timestamp.GetValueOrDefault(); }
set { this._timestamp = value; }
}
// Check to see if Timestamp property is set
internal bool IsSetTimestamp()
{
return this._timestamp.HasValue;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// <code>aws.evidently.evaluation</code> specifies an evaluation event, which determines
/// which feature variation that a user sees. <code>aws.evidently.custom</code> specifies
/// a custom event, which generates metrics from user actions such as clicks and checkouts.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public EventType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 30.372549 | 107 | 0.601679 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/CloudWatchEvidently/Generated/Model/Event.cs | 3,098 | C# |
using McMaster.Extensions.CommandLineUtils;
namespace AppCore.SigningTool.Commands
{
public class SnCommand : ICommand
{
public string Name => "sn";
public string Description => "Assembly strong naming commands.";
public void Configure(CommandLineApplication cmd)
{
}
public int Execute(CommandLineApplication cmd)
{
cmd.ShowRootCommandFullNameAndVersion();
cmd.ShowHelp();
return 0;
}
}
} | 22.954545 | 72 | 0.613861 | [
"MIT"
] | AppCoreNet/SigningTool | src/AppCore.SigningTool/Commands/SnCommand.cs | 505 | C# |
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using NLog;
using Logger = NLog.Logger;
namespace Utility
{
public static class Requester
{
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Send a byte array to the specified address at the specified port
/// </summary>
/// <param name="data">The data that will be sent</param>
/// <param name="type">The type of header that needs te be added to the data</param>
/// <param name="ip_address">The address to which it will be sent</param>
/// <param name="port">The port at which it will be sent</param>
/// <param name="catch_socket_exc">If socket exceptions need to be caught, give false if they will be handled elsewhere</param>
/// <returns></returns>
public static byte[] send(byte[] data, byte type, IPAddress ip_address, ushort port, bool catch_socket_exc = true)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//ip_address = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ip_address, port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
logger.Debug($"Socket connected to {sender.RemoteEndPoint}");
byte[] msg = add_header_footer(data, type);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
logger.Debug("Waiting for response from server");
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
logger.Debug($"Recieved from server = {Encoding.ASCII.GetString(bytes, 0, bytesRec)}");
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
bytes = bytes.TakeWhile(b => b != Network_codes.end_of_stream).ToArray();
return bytes;
}
catch (ArgumentNullException ane)
{
logger.Error($"ArgumentNullException : {ane}");
}
catch (SocketException se)
{
if (catch_socket_exc)
{
logger.Error($"SocketException : {se}");
}
else
{
throw se;
}
}
catch (Exception e)
{
logger.Error($"Unexpected exception : {e}");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return new byte[0];
}
internal static byte[] add_header_footer(byte[] data, byte type)
{
//Create a byte-array that is 2 larger then the data that must be send so there is room for a header and a footer
byte[] msg = new byte[data.Length + 2];
//Add a header based on the given signal-type
msg[0] = type;
//Add a footer witn an end-of-stream token
msg[msg.Length - 1] = Network_codes.end_of_stream;
//Copy all the data to the middle part of the array
data.CopyTo(msg, 1);
return msg;
}
public static bool ping(IPAddress address, ushort port, out string s)
{
Ping ping_sender = new Ping();
PingReply reply = ping_sender.Send(address);
try
{
byte[] data = send(new byte[0], Network_codes.ping, address, port, false);
if (data.Length == 0)
{
s = $"The address that was specified is valid but there is no server listening to this port";
logger.Info(s);
return false;
}
byte b = data[0];
if (b == Network_codes.ping_respond)
{
s = $"Server is online. Ping took {reply.RoundtripTime} ms";
logger.Info(s);
return true;
}
s = $"Something responded the ping but not with the correct code. Ping took Ping took {reply.RoundtripTime} ms";
logger.Info(s);
return false;
}
catch (SocketException)
{
s = $"The address that was specified is valid but the request was rejected at the specified port";
logger.Info(s);
return false;
}
}
/// <summary>
/// Returns the details for a given field
/// </summary>
/// <param name="field_data"></param>
/// <param name="address"></param>
/// <param name="port"></param>
/// <returns>First half of the array are the total amount of games played per column, the second half of the array are the won games per column</returns>
public static int[] get_field_details(byte[] field_data, IPAddress address, ushort port)
{
byte[] data = send(field_data, Network_codes.details_request, address, port);
if (data.Length % 4 != 0)
throw new FormatException("Byte array not dividable by 4 and thus cannot contain only integers");
int[] details = new int[14];
// The first 7 integers are the total games played in those columns
for (int i = 0; i < details.Length / 8; i++)
{
byte[] arr = new byte[4];
Array.Copy(data, i * 4, arr, 0, 4);
details[i] = BitConverter.ToInt32(arr, 0);
}
// The second 7 integers are the winning games in those columns
for (int i = 0; i < details.Length / 8; i++)
{
byte[] arr = new byte[4];
Array.Copy(data, (i + 7) * 4, arr, 0, 4);
details[i + 7] = BitConverter.ToInt32(arr, 0);
}
return details;
}
}
}
| 39.170455 | 161 | 0.510734 | [
"MIT"
] | Derivolate/4-in-a-row-AI | Util/Requester.cs | 6,896 | C# |
// Credit: https://github.com/andrewzimmer906/PocketPortalVR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PortalsVR
{
enum Direction { Up, Down, West, East, North, South };
public class SubdividedCube : MonoBehaviour
{
private MeshFilter meshFilter;
private Mesh mesh;
private List<Vector3> verticies = new List<Vector3>();
private List<int> triangles = new List<int>();
private int squareCount;
[Range(0, 4)]
public int divisions;
public void Awake()
{
RenderCube();
}
/*-- Public --*/
public Vector3[] GetCorners()
{
Vector3[] corners = new Vector3[5];
corners[0] = transform.TransformVector(new Vector3(-0.5f, 0.5f, 0)); // bottom-left
corners[1] = transform.TransformPoint(new Vector3(0.5f, 0.5f, 0)); // bottom-right
corners[2] = transform.TransformPoint(new Vector3(-0.5f, -0.5f, 0)); // top-left
corners[3] = transform.TransformPoint(new Vector3(0.5f, -0.5f, 0)); // top-right
corners[4] = transform.TransformPoint(new Vector3(0, 0, 0)); // center
return corners;
}
/*-- Render --*/
public void RenderCube()
{
if (meshFilter == null)
{
meshFilter = GetComponent<MeshFilter>();
mesh = new Mesh();
}
float sizeOfFace = 1f / (float)(divisions + 1);
for (int x = 0; x < divisions + 1; x++)
{
for (int y = 0; y < divisions + 1; y++)
{
for (int z = 0; z < 1; z++)
{
float fx = x * sizeOfFace - 0.5f;
float fy = y * sizeOfFace - 0.5f;
float fz = -sizeOfFace / 2;
if (x == 0)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.West);
}
if (x == divisions)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.East);
}
if (y == 0)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.Down);
}
if (y == divisions)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.Up);
}
if (z == 0)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.South);
}
if (z == 0)
{
AddSquare(fx, fy, fz, sizeOfFace, Direction.North);
}
}
}
}
UpdateMesh();
}
/* -- Geometry -- */
void AddSquare(float x, float y, float z, float size, Direction direction)
{
if (direction == Direction.Up ||
direction == Direction.Down)
{
AddFaceForTopBottom(x, y, z, size, direction);
}
else if (direction == Direction.North ||
direction == Direction.South)
{
AddFaceForNorthSouth(x, y, z, size, direction);
}
else if (direction == Direction.West ||
direction == Direction.East)
{
AddFaceForWestEast(x, y, z, size, direction);
}
squareCount++;
}
void AddFaceForTopBottom(float x, float y, float z, float size, Direction direction)
{
if (direction == Direction.Up)
{
y += size;
}
verticies.Add(new Vector3(x, y, z + size));
verticies.Add(new Vector3(x + size, y, z + size));
verticies.Add(new Vector3(x + size, y, z));
verticies.Add(new Vector3(x, y, z));
AddLatestTriangles(direction != Direction.Up);
}
void AddFaceForWestEast(float x, float y, float z, float size, Direction direction)
{
if (direction == Direction.East)
{
x += size;
}
verticies.Add(new Vector3(x, y + size, z));
verticies.Add(new Vector3(x, y + size, z + size));
verticies.Add(new Vector3(x, y, z + size));
verticies.Add(new Vector3(x, y, z));
AddLatestTriangles(direction != Direction.East);
}
void AddFaceForNorthSouth(float x, float y, float z, float size, Direction direction)
{
if (direction == Direction.North)
{
z += size;
}
verticies.Add(new Vector3(x, y + size, z));
verticies.Add(new Vector3(x + size, y + size, z));
verticies.Add(new Vector3(x + size, y, z));
verticies.Add(new Vector3(x, y, z));
AddLatestTriangles(direction != Direction.South);
}
void AddLatestTriangles(bool clockwise)
{
if (clockwise)
{
triangles.Add(squareCount * 4); // 1
triangles.Add(squareCount * 4 + 1); // 2
triangles.Add(squareCount * 4 + 2); // 3
triangles.Add(squareCount * 4); // 1
triangles.Add(squareCount * 4 + 2); // 3
triangles.Add(squareCount * 4 + 3); // 4
}
else
{
triangles.Add(squareCount * 4 + 2); // 3
triangles.Add(squareCount * 4 + 1); // 2
triangles.Add(squareCount * 4); // 1
triangles.Add(squareCount * 4 + 3); // 4
triangles.Add(squareCount * 4 + 2); // 3
triangles.Add(squareCount * 4); // 1
}
}
/* -- Draw -- */
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = verticies.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
// Reset back to factory
verticies.Clear();
triangles.Clear();
squareCount = 0;
meshFilter.sharedMesh = mesh;
}
}
} | 31.572816 | 95 | 0.442651 | [
"MIT"
] | AH228589/PortalsVR | Assets/PortalsVR/Scripts/Portal/SubdividedCube/SubdividedCube.cs | 6,506 | C# |
using System.IO;
using NUnit.Framework;
namespace Mirror.Tests
{
// NetworkWriterTest already covers most cases for NetworkReader.
// only a few are left
[TestFixture]
public class NetworkReaderTest
{
/* uncomment if needed. commented for faster test workflow. this takes >3s.
[Test]
public void Benchmark()
{
// 10 million reads, Unity 2019.3, code coverage disabled
// 4049ms (+GC later)
byte[] bytes = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C };
for (int i = 0; i < 10000000; ++i)
{
ArraySegment<byte> segment = new ArraySegment<byte>(bytes);
NetworkReader reader = new NetworkReader(segment);
Vector3 value = reader.ReadVector3();
}
}
*/
[Test]
public void SetBuffer()
{
// start with an initial buffer
byte[] firstBuffer = {0xFF};
NetworkReader reader = new NetworkReader(firstBuffer);
// read one byte so we modify position
reader.ReadByte();
// set another buffer
byte[] secondBuffer = {0x42};
reader.SetBuffer(secondBuffer);
// was position reset?
Assert.That(reader.Position, Is.EqualTo(0));
// are we really on the second buffer now?
Assert.That(reader.ReadByte(), Is.EqualTo(0x42));
}
[Test]
public void Remaining()
{
byte[] bytes = {0x00, 0x01};
NetworkReader reader = new NetworkReader(bytes);
Assert.That(reader.Remaining, Is.EqualTo(2));
reader.ReadByte();
Assert.That(reader.Remaining, Is.EqualTo(1));
reader.ReadByte();
Assert.That(reader.Remaining, Is.EqualTo(0));
}
[Test]
public void ReadBytesCountTooBigTest()
{
// calling ReadBytes with a count bigger than what is in Reader
// should throw an exception
byte[] bytes = { 0x00, 0x01 };
using (PooledNetworkReader reader = NetworkReaderPool.GetReader(bytes))
{
try
{
byte[] result = reader.ReadBytes(bytes, bytes.Length + 1);
// BAD: IF WE GOT HERE, THEN NO EXCEPTION WAS THROWN
Assert.Fail();
}
catch (EndOfStreamException)
{
// GOOD
}
}
}
}
}
| 30.870588 | 102 | 0.514863 | [
"MIT"
] | 10allday/OpenMMO | Plugins/3rdParty/Mirror/Tests/Editor/NetworkReaderTest.cs | 2,624 | C# |
using Dibware.EventDispatcher.Core;
using System;
using System.Windows.Forms;
namespace Dibware.EventDispatcher.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ApplicationEventDispatcher applicationEventDispatcher = null;
MainProcess mainProcess = null;
try
{
applicationEventDispatcher = new ApplicationEventDispatcher();
mainProcess = new MainProcess(applicationEventDispatcher);
mainProcess.Start();
Application.Run();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, @"Error!");
}
finally
{
if (mainProcess != null) mainProcess.Dispose();
if (applicationEventDispatcher != null) applicationEventDispatcher.Dispose();
}
}
}
} | 29.435897 | 93 | 0.554878 | [
"MIT"
] | dibley1973/EventDispatcher | UI/Dibware.EventDispatcher.UI/Program.cs | 1,150 | C# |
using Quick.Localize;
using System;
using System.Text;
namespace Test
{
[TextResource]
public enum TextFromCode
{
[Text("Hello World!", Language = "en-US")]
[Text("你好世界!", Language = "zh-CN")]
HelloWorld
}
[TextResource]
public enum TextFromEmbedResource
{
HelloCSharp
}
[TextResource]
public enum TextFromExternalFile
{
HelloDotNet
}
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("--English 英文--");
var textManager = TextManager.GetInstance("en-US");
Console.WriteLine(textManager.GetText(TextFromCode.HelloWorld));
Console.WriteLine(textManager.GetText(TextFromEmbedResource.HelloCSharp));
Console.WriteLine(textManager.GetText(TextFromExternalFile.HelloDotNet));
Console.WriteLine();
Console.WriteLine("--Chinese 中文--");
textManager = TextManager.GetInstance("zh-CN");
Console.WriteLine(textManager.GetText(TextFromCode.HelloWorld));
Console.WriteLine(textManager.GetText(TextFromEmbedResource.HelloCSharp));
Console.WriteLine(textManager.GetText(TextFromExternalFile.HelloDotNet));
Console.ReadLine();
}
}
} | 28.755102 | 87 | 0.606813 | [
"Apache-2.0"
] | aaasoft/Quick.Localize | Test/Program.cs | 1,427 | C# |
// ———————————————————————–
// <copyright file="SituationObservation.cs" company="EDXLSharp">
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.ServiceModel.Syndication;
using System.Xml;
using EDXLSharp;
using GeoOASISWhereLib;
namespace MEXLSitRepLib
{
/// <summary>
/// A Lightweight Field or Spot Report
/// </summary>
[Serializable]
public partial class SituationObservation : ISitRepReport
{
#region Public Delegates/Events
#endregion
#region Private Member Variables
/// <summary>
/// The Geo-Location This Observation Applies To
/// </summary>
private GeoOASISWhere reportLocation;
/// <summary>
/// Free Text String to Communicate Immediate Needs
/// </summary>
private string immediateNeeds;
/// <summary>
/// Represents The General Type of Observation
/// </summary>
private SitRepObservationType? observationType;
/// <summary>
/// Free Text of the Observation
/// </summary>
private string observationText;
/// <summary>
/// Unique Identifier for This Observation
/// </summary>
private string observationID;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the SituationObservation class
/// Default Constructor - Does Nothing
/// </summary>
public SituationObservation()
{
}
#endregion
#region Public Accessors
/// <summary>
/// Gets or sets
/// Unique Identifier for This Observation
/// </summary>
public string ObservationID
{
get { return this.observationID; }
set { this.observationID = value; }
}
/// <summary>
/// Gets or sets
/// Free Text of the Observation
/// </summary>
public string ObservationText
{
get { return this.observationText; }
set { this.observationText = value; }
}
/// <summary>
/// Gets or sets
/// Represents The General Type of Observation
/// </summary>
public SitRepObservationType? ObservationType
{
get { return this.observationType; }
set { this.observationType = value; }
}
/// <summary>
/// Gets or sets
/// Free Text String to Communicate Immediate Needs
/// </summary>
public string ImmediateNeeds
{
get { return this.immediateNeeds; }
set { this.immediateNeeds = value; }
}
/// <summary>
/// Gets or sets
/// The Geo-Location This Observation Applies To
/// </summary>
public GeoOASISWhere ReportLocation
{
get { return this.reportLocation; }
set { this.reportLocation = value; }
}
#endregion
#region Public Member Functions
/// <summary>
/// Writes this Object to an inline XML Document
/// </summary>
/// <param name="xwriter">Valid XMLWriter</param>
internal override void WriteXML(XmlWriter xwriter)
{
xwriter.WriteStartElement("SituationObservation");
if (!string.IsNullOrEmpty(this.observationID))
{
xwriter.WriteElementString("ObservationID", this.observationID);
}
if (this.observationType != null)
{
xwriter.WriteElementString("ObservationType", this.observationType.ToString());
}
if (!string.IsNullOrEmpty(this.observationText))
{
xwriter.WriteElementString("ObservationText", this.observationText);
}
if (!string.IsNullOrEmpty(this.immediateNeeds))
{
xwriter.WriteElementString("ImmediateNeeds", this.immediateNeeds);
}
if (this.reportLocation != null)
{
xwriter.WriteStartElement("ReportLocation");
this.reportLocation.WriteXML(xwriter);
xwriter.WriteEndElement();
}
xwriter.WriteEndElement();
}
/// <summary>
/// Reads this Object's values from an XML node list
/// </summary>
/// <param name="rootnode">root XML Node of the Object element</param>
internal override void ReadXML(XmlNode rootnode)
{
foreach (XmlNode childnode in rootnode.ChildNodes)
{
if (string.IsNullOrEmpty(childnode.InnerText))
{
continue;
}
switch (childnode.LocalName)
{
case "ObservationID":
this.observationID = childnode.InnerText;
break;
case "ObservationType":
this.observationType = (SitRepObservationType)Enum.Parse(typeof(SitRepObservationType), childnode.InnerText);
break;
case "ObservationText":
this.observationText = childnode.InnerText;
break;
case "ImmediateNeeds":
this.immediateNeeds = childnode.InnerText;
break;
case "ReportLocation":
this.reportLocation = new GeoOASISWhere();
this.reportLocation.ReadXML(childnode.FirstChild);
break;
case "#comment":
break;
default:
throw new ArgumentException("Unexpected Child Node Name: " + childnode.Name + " in SituationObservation");
}
}
}
/// <summary>
/// Converts This IComposableMessage Into A Geo-RSS SyndicationItem
/// </summary>
/// <param name="myitem">Pointer to a Syndication Item to Populate</param>
internal override void ToGeoRSS(System.ServiceModel.Syndication.SyndicationItem myitem)
{
myitem.Title = new TextSyndicationContent("Field Observation - " + this.observationType.ToString() + " (EDXL-SitRep)");
TextSyndicationContent content = new TextSyndicationContent("Observation: " + this.observationText + "\nImmediate Needs: " + this.immediateNeeds);
myitem.Content = content;
}
/// <summary>
/// Override of IContentObject Interface Function
/// </summary>
/// <param name="ckw">ValueList Object for Content Keywords</param>
internal override void SetContentKeywords(ValueList ckw)
{
ckw.Value.Add("MEXL-SitRep SituationObservation");
}
#endregion
#region Protected Member Functions
/// <summary>
/// Validates This Message element For Required Values and Conformance
/// </summary>
protected override void Validate()
{
if (this.observationType == null)
{
throw new ArgumentNullException("Observation Type is required and can't be null or empty!");
}
}
#endregion
#region Private Member Functions
#endregion
}
}
| 28.37247 | 152 | 0.63613 | [
"Apache-2.0"
] | 1stResponder/em-serializers | EDXLSHARP/MEXLSitRepLib/SituationObservation.cs | 7,058 | C# |
using OnlineServices.Common.RegistrationServices.TransferObject;
using System;
using System.Collections.Generic;
using System.Text;
namespace OnlineServices.Common.RegistrationServices
{
public interface IRSAttendeeRole
{
public SessionTO GetSessionByUserByDate(int userId, DateTime date);
public int GetIdByMail(string mail);
public IEnumerable<SessionTO> GetSessionsByDate(DateTime date);
}
} | 28.866667 | 75 | 0.775982 | [
"Apache-2.0"
] | TheRealDelep/OnlineServices | Cross-Cutting/OnlineServices.Common/RegistrationServices/IRSAttendeeRole.cs | 435 | C# |
using System;
namespace Exportable.Attribute
{
/// <summary>
/// Información para leer un documento
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ImportableAttribute : System.Attribute
{
/// <summary>
/// Posición de la columna que debe ser leida
/// </summary>
public int Position { get; set; }
/// <summary>
/// Valor por defecto en caso que el dato contenido en la celda no exista o sea inválido
/// </summary>
public string DefaultForNullOrInvalidValues { get; set; }
/// <summary>
/// Constructor de la clase
/// </summary>
/// <param name="position"></param>
public ImportableAttribute(int position)
{
this.Position = position;
}
}
}
| 28.096774 | 96 | 0.584386 | [
"MIT"
] | Infodinamica/exportable | src/Exportable/Attribute/ImportableAttribute.cs | 876 | C# |
namespace PholioVisualisation.PholioObjects
{
public class ContentItem
{
public int Id { get; set; }
public string ContentKey { get; set; }
public int ProfileId { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public bool IsPlainText { get; set; }
}
}
| 27.230769 | 47 | 0.601695 | [
"MIT"
] | PublicHealthEngland/fingertips-open | PholioVisualisationWS/PholioObjects/ContentItem.cs | 356 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Utils.Helpers
{
using System;
using YAF.Utils.Helpers.MinifyUtils;
/// <summary>
/// The JS and CSS helper.
/// </summary>
public static class JsAndCssHelper
{
/// <summary>
/// Compresses JavaScript
/// </summary>
/// <param name="javaScript">
/// The Uncompressed Input JS
/// </param>
/// <returns>
/// The compressed java script.
/// </returns>
public static string CompressJavaScript(string javaScript)
{
try
{
return JSMinify.Minify(javaScript);
}
catch (Exception)
{
return javaScript;
}
}
/// <summary>
/// Compresses CSS
/// </summary>
/// <param name="css">
/// The Uncompressed Input CSS
/// </param>
/// <returns>
/// The compressed CSS output.
/// </returns>
public static string CompressCss(string css)
{
try
{
return JSMinify.Minify(css);
}
catch (Exception)
{
return css;
}
}
}
} | 29.974026 | 67 | 0.559792 | [
"Apache-2.0"
] | AlbertoP57/YAFNET | yafsrc/YAF.Utils/Helpers/JsAndCssHelper.cs | 2,233 | C# |
#if WINDOWS
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Nucleus.Platform.Windows.Controls {
public class TitleBarControl : UserControl {
private PictureBox icon;
private Label titleLabel;
private string text = "";
private Button minimize;
private Button maximize;
private Button close;
private DateTime lastUpdateDate;
private bool mouseDown;
private Point dragStartPoint;
private Image cachedIcon;
private Font btnFont;
private Font titleFont;
public bool EnableMaximize { get; set; } = true;
public bool ShowIcon { get; set; }
public int StripWidth { get; set; } = 30;
public Image Icon {
get {
if (icon == null) {
return cachedIcon;
} else {
return icon.Image;
}
}
set {
if (icon == null) {
cachedIcon = value;
} else {
icon.Image = value;
}
}
}
[Browsable(true)]
public override string Text {
get {
if (titleLabel == null) {
return text;
}
return titleLabel.Text;
}
set {
text = value;
if (titleLabel == null) {
return;
}
titleLabel.Text = value;
}
}
public TitleBarControl() {
this.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
this.Size = new Size(1000, 21);
this.BackColor = Color.FromArgb(255, 32, 34, 37);
this.Padding = Padding.Empty;
this.Margin = Padding.Empty;
this.SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
InitializeButtons();
}
private void InitializeButtons() {
btnFont = new Font(this.Font.FontFamily, 6, FontStyle.Regular);
titleFont = new Font(this.Font.FontFamily, 10, FontStyle.Regular);
titleLabel = new Label();
titleLabel.Text = text;
titleLabel.AutoSize = true;
titleLabel.Font = titleFont;
titleLabel.DoubleClick += TitleLabel_DoubleClick;
titleLabel.Visible = false;
Controls.Add(titleLabel);
icon = new PictureBox();
icon.Location = new Point(2, 2);
icon.Size = new Size(17, 17);
icon.SizeMode = PictureBoxSizeMode.StretchImage;
icon.Image = cachedIcon;
this.Controls.Add(icon);
if (ShowIcon) {
titleLabel.Location = new Point(20, 2);
} else {
titleLabel.Location = new Point(2, 2);
icon.Visible = false;
}
close = MakeFlatBtn();
maximize = MakeFlatBtn();
minimize = MakeFlatBtn();
close.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 240, 30, 30);
close.Location = new Point(this.Width - 26, 0);
close.Left = this.Width - 26;
close.Text = "X";
close.Click += Close_Click;
if (EnableMaximize) {
maximize.Left = close.Left - 26;
maximize.Text = "[]";
maximize.Click += Maximize_Click;
minimize.Left = maximize.Left - 26;
} else {
minimize.Left = close.Left - 26;
}
minimize.Text = "_";
minimize.Click += Minimize_Click;
}
private void Minimize_Click(object sender, EventArgs e) {
if (this.ParentForm != null) {
this.ParentForm.WindowState = FormWindowState.Minimized;
}
}
private void Maximize_Click(object sender, EventArgs e) {
SwapMaximized();
}
private void TitleLabel_DoubleClick(object sender, EventArgs e) {
SwapMaximized();
}
private void SwapMaximized() {
if (!EnableMaximize) {
return;
}
Form parent = this.ParentForm;
if (parent != null) {
DateTime now = DateTime.Now;
// TODO: is this bad
if (now - lastUpdateDate < TimeSpan.FromMilliseconds(300)) {
return;
}
lastUpdateDate = now;
if (parent.WindowState == FormWindowState.Maximized) {
parent.WindowState = FormWindowState.Normal;
} else {
parent.WindowState = FormWindowState.Maximized;
}
}
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
float stripWidth = this.Width * (this.StripWidth / 100.0f);
int x = 2;
if (Icon != null) {
e.Graphics.DrawImage(Icon, new Rectangle(x, 1, 16, 16));
x = 19;
}
//e.Graphics.FillRectangle(Brushes.Black, new RectangleF(21, 1, stripWidth, 19));
//e.Graphics.DrawRectangle(Pens.Black, new Rectangle(21, 1, (int)stripWidth, 19));
e.Graphics.DrawString(text, this.titleLabel.Font, Brushes.White, x, 1);
}
protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
Form parent = this.ParentForm;
if (parent != null) {
mouseDown = true;
Point nP = new Point(e.Location.X + this.Location.X, e.Location.Y + this.Location.Y);
dragStartPoint = nP;
//User32Interop.ReleaseCapture();
//User32Interop.SendMessage(parent.Handle, User32_WS.WM_NCLBUTTONDOWN, User32_WS.HT_CAPTION, 0);
// menustrip
float stripWidth = this.Width * (this.StripWidth / 100.0f);
Refresh();
}
}
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
if (mouseDown) {
Form parent = this.ParentForm;
if (parent != null) {
if (parent.WindowState == FormWindowState.Maximized) {
var ox = parent.Location.X;
var width = parent.Width;
parent.WindowState = FormWindowState.Normal;
// update the drag start point to be relative
// scale parent location x over the original size
var nwidth = parent.Width;
float factor = nwidth / (float)width;
int newX = (int)(factor * ox);
parent.Location = new Point(
parent.Location.X - dragStartPoint.X + e.X,
parent.Location.Y - dragStartPoint.Y + e.Y);
dragStartPoint = new Point(parent.Location.X + newX, dragStartPoint.Y);
} else {
parent.Location = new Point(
parent.Location.X - dragStartPoint.X + e.X,
parent.Location.Y - dragStartPoint.Y + e.Y);
}
this.Update();
// menustrip
float stripWidth = this.Width * (this.StripWidth / 100.0f);
Refresh();
}
}
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left) {
Form parent = this.ParentForm;
if (parent != null) {
mouseDown = false;
Point pos = Cursor.Position;
if (parent.WindowState == FormWindowState.Normal &&
pos.Y < 30) {
SwapMaximized();
}
}
}
}
protected override void OnDoubleClick(EventArgs e) {
base.OnDoubleClick(e);
SwapMaximized();
}
protected override void OnClick(EventArgs e) {
base.OnClick(e);
titleLabel.Focus();
}
private Button MakeFlatBtn() {
Button btn = new Button();
btn.Font = btnFont;
btn.FlatStyle = FlatStyle.Flat;
btn.FlatAppearance.BorderColor = Color.FromArgb(0, 0, 0, 0);
btn.FlatAppearance.BorderSize = 0;
btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 120, 120, 120);
btn.Anchor = AnchorStyles.Top | AnchorStyles.Right;
btn.Size = new Size(26, 21);
btn.Text = "X";
Controls.Add(btn);
return btn;
}
private void Close_Click(object sender, EventArgs e) {
if (this.ParentForm != null) {
this.ParentForm.Close();
}
//Application.Exit();
}
protected override void OnParentChanged(EventArgs e) {
base.OnParentChanged(e);
if (Parent != null) {
Parent.Resize += Parent_Resize;
this.Width = Parent.ClientSize.Width;
}
}
private void Parent_Resize(object sender, EventArgs e) {
if (Parent != null) {
this.Width = Parent.ClientSize.Width;
}
}
}
}
#endif | 33.604027 | 152 | 0.49251 | [
"MIT"
] | lucasassislar/nucleusdotnet | Nucleus.Gaming/Nucleus.Gaming/Platform/Windows/Controls/TitleBarControl.cs | 10,016 | C# |
using System;
namespace FFXIV.Packets
{
public class WorldInit : OpcodePacket
{
//public List<Byte> ZeroPad = new List<Byte>(new Byte[0x20]);
public UInt64 Zero2;
public UInt32 EntityId;
public String Client = new String(' ', 4);
public static WorldInit ClientVersion()
{
return new WorldInit { Client = "\0\0\0\0\0\0\0\0client\0\0RUDP\0\0\0\0RUDP2\0\0\0%u\0\0\0\0\0\0\0\0chs\0ko\0\0%s(%d):Assertion %s %s\0\0at\0\0wt\0\0%s(%d)" };
}
}
}
| 30.588235 | 171 | 0.584615 | [
"MIT"
] | shalzuth/SaBOTender | FFXIVPackets/World/Opcodes/WorldInit.cs | 522 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Atividade_9_Desafio_Segmento_Reta")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Atividade_9_Desafio_Segmento_Reta")]
[assembly: System.Reflection.AssemblyTitleAttribute("Atividade_9_Desafio_Segmento_Reta")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Gerado pela classe WriteCodeFragment do MSBuild.
| 45.291667 | 91 | 0.678933 | [
"MIT"
] | Eduardo007-lang/Codigos-C- | Atividade_9_Desafio_Segmento_Reta/Atividade_9_Desafio_Segmento_Reta/obj/Release/netcoreapp3.1/Atividade_9_Desafio_Segmento_Reta.AssemblyInfo.cs | 1,096 | C# |
using OpenTK;
using OpenTK.Graphics.OpenGL;
using SFGenericModel.VertexAttributes;
namespace StudioSB.Scenes.Ultimate
{
public struct IVec4
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public int W { get; set; }
public int this[int i]
{
get
{
switch (i) {
case 0: return X;
case 1: return Y;
case 2: return Z;
case 3: return W;
default:
throw new System.IndexOutOfRangeException();
}
}
set
{
switch (i)
{
case 0: X = value; break;
case 1: Y = value; break;
case 2: Z = value; break;
case 3: W = value; break;
default:
throw new System.IndexOutOfRangeException();
}
}
}
}
public struct UltimateVertex
{
[VertexFloat("Position0", ValueCount.Three, VertexAttribPointerType.Float, false)]
public Vector3 Position0 { get; }
[VertexFloat("Normal0", ValueCount.Three, VertexAttribPointerType.Float, false)]
public Vector3 Normal0 { get; }
[VertexFloat("Tangent0", ValueCount.Three, VertexAttribPointerType.Float, false)]
public Vector3 Tangent0 { get; }
// Generated value.
[VertexFloat("Bitangent0", ValueCount.Three, VertexAttribPointerType.Float, false)]
public Vector3 Bitangent0 { get; }
[VertexFloat("map1", ValueCount.Two, VertexAttribPointerType.Float, false)]
public Vector2 Map1 { get; }
[VertexFloat("uvSet", ValueCount.Two, VertexAttribPointerType.Float, false)]
public Vector2 UvSet { get; }
[VertexFloat("uvSet1", ValueCount.Two, VertexAttribPointerType.Float, false)]
public Vector2 UvSet1 { get; }
[VertexFloat("uvSet2", ValueCount.Two, VertexAttribPointerType.Float, false)]
public Vector2 UvSet2 { get; }
[VertexInt("boneIndices", ValueCount.Four, VertexAttribIntegerType.UnsignedInt)]
public IVec4 BoneIndices { get; }
[VertexFloat("boneWeights", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 BoneWeights { get; }
[VertexFloat("bake1", ValueCount.Two, VertexAttribPointerType.Float, false)]
public Vector2 Bake1 { get; }
[VertexFloat("colorSet1", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet1 { get; }
[VertexFloat("colorSet2", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet2 { get; }
[VertexFloat("colorSet21", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet21 { get; }
[VertexFloat("colorSet22", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet22 { get; }
[VertexFloat("colorSet23", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet23 { get; }
[VertexFloat("colorSet3", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet3 { get; }
[VertexFloat("colorSet4", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet4 { get; }
[VertexFloat("colorSet5", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet5 { get; }
[VertexFloat("colorSet6", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet6 { get; }
[VertexFloat("colorSet7", ValueCount.Four, VertexAttribPointerType.Float, false)]
public Vector4 ColorSet7 { get; }
public UltimateVertex(Vector3 position0, Vector3 normal0, Vector3 tangent0, Vector3 bitangent0,
Vector2 map1, Vector2 uvSet, Vector2 uvSet1, Vector2 uvSet2,
IVec4 boneIndices, Vector4 boneWeights,
Vector2 bake1,
Vector4 colorSet1,
Vector4 colorSet2, Vector4 colorSet21, Vector4 colorSet22, Vector4 colorSet23,
Vector4 colorSet3, Vector4 colorSet4, Vector4 colorSet5, Vector4 colorSet6, Vector4 colorSet7)
{
Position0 = position0;
Normal0 = normal0;
Tangent0 = tangent0;
Bitangent0 = bitangent0;
Map1 = map1;
UvSet = uvSet;
UvSet1 = uvSet1;
UvSet2 = uvSet2;
BoneIndices = boneIndices;
BoneWeights = boneWeights;
Bake1 = bake1;
ColorSet1 = colorSet1;
ColorSet2 = colorSet2;
ColorSet21 = colorSet21;
ColorSet22 = colorSet22;
ColorSet23 = colorSet23;
ColorSet3 = colorSet3;
ColorSet4 = colorSet4;
ColorSet5 = colorSet5;
ColorSet6 = colorSet6;
ColorSet7 = colorSet7;
}
}
}
| 36.657143 | 106 | 0.5947 | [
"MIT"
] | Ploaj/StudioSB | StudioSB/Scenes/Ultimate/Rendering/UltimateVertex.cs | 5,134 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Auditing;
using NPS.Sessions.Dto;
namespace NPS.Sessions
{
public class SessionAppService : NPSAppServiceBase, ISessionAppService
{
[DisableAuditing]
public async Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations()
{
var output = new GetCurrentLoginInformationsOutput
{
Application = new ApplicationInfoDto
{
Version = AppVersionHelper.Version,
ReleaseDate = AppVersionHelper.ReleaseDate,
Features = new Dictionary<string, bool>()
}
};
if (AbpSession.TenantId.HasValue)
{
output.Tenant = ObjectMapper.Map<TenantLoginInfoDto>(await GetCurrentTenantAsync());
}
if (AbpSession.UserId.HasValue)
{
output.User = ObjectMapper.Map<UserLoginInfoDto>(await GetCurrentUserAsync());
}
return output;
}
}
}
| 29.621622 | 100 | 0.583942 | [
"MIT"
] | leonardo-buta/automated-nps | aspnet-core/src/NPS.Application/Sessions/SessionAppService.cs | 1,098 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.