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 |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Xml;
namespace DocumentFormat.OpenXml
{
/// <summary>
/// Represents the Int16 value for attributes.
/// </summary>
[DebuggerDisplay("{InnerText}")]
public class Int16Value : OpenXmlSimpleValue<Int16>
{
/// <summary>
/// Initializes a new instance of the Int16Value class.
/// </summary>
public Int16Value()
: base()
{
}
/// <summary>
/// Initializes a new instance of the Int16Value class using the supplied Int16 value.
/// </summary>
/// <param name="value">The Int16 value.</param>
public Int16Value(Int16 value)
: base(value)
{
}
/// <summary>
/// Initializes a new instance of the Int16Value by deep copying the supplied IntValue class.
/// </summary>
/// <param name="source">The source Int16Value class.</param>
public Int16Value(Int16Value source)
: base(source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
}
/// <inheritdoc/>
public override string InnerText
{
get
{
if (this.TextValue == null && this.InnerValue.HasValue)
{
// this.TextValue = this._value.ToString();
this.TextValue = XmlConvert.ToString(this.InnerValue.Value);
}
else
{
Debug.Assert(this.TextValue == null && !this.InnerValue.HasValue ||
this.TextValue != null && !this.InnerValue.HasValue ||
this.TextValue != null && this.TextValue == this.InnerValue.ToString() ||
// special case: signed number like text is "+5", value is 5
this.TextValue != null && this.TextValue == "+" + this.InnerValue.ToString());
}
return this.TextValue;
}
}
/// <inheritdoc/>
internal override void Parse()
{
this.InnerValue = XmlConvert.ToInt16(this.TextValue);
}
/// <inheritdoc/>
internal override bool TryParse()
{
Int16 value;
this.InnerValue = null;
try
{
value = XmlConvert.ToInt16(this.TextValue);
this.InnerValue = value;
return true;
}
catch (FormatException)
{
return false;
}
catch (OverflowException)
{
return false;
}
}
/// <summary>
/// Implicitly converts the specified value to an Int16 value.
/// </summary>
/// <param name="xmlAttribute">The Int16Value to convert.</param>
/// <returns>The converted Int16 value.</returns>
/// <exception cref="InvalidOperationException">Thrown when xmlAttribute is null.</exception>
public static implicit operator Int16(Int16Value xmlAttribute)
{
if (xmlAttribute == null)
{
throw new InvalidOperationException(ExceptionMessages.ImplicitConversionExceptionOnNull);
}
return ToInt16(xmlAttribute);
}
/// <summary>
/// Implicitly converts an Int16 value to a Int16Value instance.
/// </summary>
/// <param name="value">The specified value.</param>
/// <returns>A new Int16Value instance with the value.</returns>
public static implicit operator Int16Value(Int16 value)
{
return FromInt16(value);
}
/// <summary>
/// Returns a new Int16Value object that was created from an Int16 value.
/// </summary>
/// <param name="value">An Int16 value to use to create a new Int16Value object.</param>
/// <returns>An Int16Value that corresponds to the value parameter.</returns>
public static Int16Value FromInt16(Int16 value)
{
return new Int16Value(value);
}
/// <summary>
/// Returns an Int16 representation of an Int16Value object.
/// </summary>
/// <param name="xmlAttribute">
/// An Int16Value object to retrieve an Int16 representation.
/// </param>
/// <returns>An Int16 value that represents an Int16Value object.</returns>
public static Int16 ToInt16(Int16Value xmlAttribute)
{
if (xmlAttribute == null)
{
throw new InvalidOperationException(ExceptionMessages.ImplicitConversionExceptionOnNull);
}
return xmlAttribute.Value;
}
private protected override OpenXmlSimpleType CloneImpl() => new Int16Value(this);
}
}
| 34.092715 | 111 | 0.539433 | [
"Apache-2.0"
] | lpperras/Open-XML-SDK | DocumentFormat.OpenXml/SimpleTypes/Int16Value.cs | 5,150 | C# |
using System;
using System.Text.RegularExpressions;
using log4net;
namespace CKAN.CmdLine
{
public class ConsoleUser : NullUser
{
private static readonly ILog log = LogManager.GetLogger(typeof(ConsoleUser));
private bool m_Headless = false;
public ConsoleUser(bool headless)
{
m_Headless = headless;
}
public override bool Headless
{
get
{
return m_Headless;
}
}
protected override bool DisplayYesNoDialog(string message)
{
if (m_Headless)
{
return true;
}
Console.Write("{0} [Y/n] ", message);
while (true)
{
var input = Console.In.ReadLine();
if (input == null)
{
log.ErrorFormat("No console available for input, assuming no.");
return false;
}
input = input.ToLower().Trim();
if (input.Equals("y") || input.Equals("yes"))
{
return true;
}
if (input.Equals("n") || input.Equals("no"))
{
return false;
}
if (input.Equals(string.Empty))
{
// User pressed enter without any text, assuming default choice.
return true;
}
Console.Write("Invalid input. Please enter yes or no");
}
}
protected override void DisplayMessage(string message, params object[] args)
{
Console.WriteLine(message, args);
}
protected override void DisplayError(string message, params object[] args)
{
Console.Error.WriteLine(message, args);
}
protected override int DisplaySelectionDialog(string message, params object[] args)
{
const int return_cancel = -1;
// Check for the headless flag.
if (m_Headless)
{
// Return that the user cancelled the selection process.
return return_cancel;
}
// Validate input.
if (String.IsNullOrWhiteSpace(message))
{
throw new Kraken("Passed message string must be non-empty.");
}
if (args.Length == 0)
{
throw new Kraken("Passed list of selection candidates must be non-empty.");
}
// Check if we have a default selection.
int defaultSelection = -1;
if (args[0] is int)
{
// Check that the default selection makes sense.
defaultSelection = (int)args[0];
if (defaultSelection < 0 || defaultSelection > args.Length - 1)
{
throw new Kraken("Passed default arguments is out of range of the selection candidates.");
}
// Extract the relevant arguments.
object[] newArgs = new object[args.Length - 1];
for (int i = 1; i < args.Length; i++)
{
newArgs[i - 1] = args[i];
}
args = newArgs;
}
// Further data validation.
foreach (object argument in args)
{
if (String.IsNullOrWhiteSpace(argument.ToString()))
{
throw new Kraken("Candidate may not be empty.");
}
}
// List options.
for (int i = 0; i < args.Length; i++)
{
string CurrentRow = String.Format("{0}", i + 1);
if (i == defaultSelection)
{
CurrentRow += "*";
}
CurrentRow += String.Format(") {0}", args[i]);
RaiseMessage(CurrentRow);
}
// Create message string.
string output = String.Format("Enter a number between {0} and {1} (To cancel press \"c\" or \"n\".", 1, args.Length);
if (defaultSelection >= 0)
{
output += String.Format(" \"Enter\" will select {0}.", defaultSelection + 1);
}
output += "): ";
RaiseMessage(output);
bool valid = false;
int result = 0;
while (!valid)
{
// Wait for input from the command line.
string input = Console.In.ReadLine();
if (input == null)
{
// No console present, cancel the process.
return return_cancel;
}
input = input.Trim().ToLower();
// Check for default selection.
if (String.IsNullOrEmpty(input))
{
if (defaultSelection >= 0)
{
return defaultSelection;
}
}
// Check for cancellation characters.
if (input == "c" || input == "n")
{
RaiseMessage("Selection cancelled.");
return return_cancel;
}
// Attempt to parse the input.
try
{
result = Convert.ToInt32(input);
}
catch (FormatException)
{
RaiseMessage("The input is not a number.");
continue;
}
catch (OverflowException)
{
RaiseMessage("The number in the input is too large.");
continue;
}
// Check the input against the boundaries.
if (result > args.Length)
{
RaiseMessage("The number in the input is too large.");
RaiseMessage(output);
continue;
}
else if (result < 1)
{
RaiseMessage("The number in the input is too small.");
RaiseMessage(output);
continue;
}
// The list we provide is index 1 based, but the array is index 0 based.
result--;
// We have checked for all errors and have gotten a valid result. Stop the input loop.
valid = true;
}
return result;
}
protected override void ReportProgress(string format, int percent)
{
if (Regex.IsMatch(format, "download", RegexOptions.IgnoreCase))
{
Console.Write(
// The \r at the front here causes download messages to *overwrite* each other.
"\r{0} - {1}% ", format, percent);
}
else
{
// The percent looks weird on non-download messages.
// The leading newline makes sure we don't end up with a mess from previous
// download messages.
Console.Write("\n{0}", format);
}
}
protected override void ReportDownloadsComplete(Uri[] urls, string[] filenames, Exception[] errors)
{
}
public override int WindowWidth
{
get { return Console.WindowWidth; }
}
}
}
| 30.046875 | 129 | 0.443708 | [
"MIT"
] | RichardLake/CKAN | Cmdline/ConsoleUser.cs | 7,694 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StatesAndProvinces.UnitTests
{
[TestClass]
public class UntTest1
{
[TestMethod]
public void MakesUSStates()
{
var actual = Factory.Make(CountrySelection.UnitedStates);
Assert.AreEqual(51, actual.Count);
}
[TestMethod]
public void MakesCanadianProvinces()
{
var actual = Factory.Make(CountrySelection.Canada);
Assert.AreEqual(13, actual.Count);
}
[TestMethod]
public void MakesBothUSAndCanada()
{
var actual = Factory.Make(CountrySelection.UnitedStates | CountrySelection.Canada);
Assert.AreEqual(64, actual.Count);
}
[TestMethod]
[ExpectedException(typeof(System.NotImplementedException))]
public void ThrowsExceptionIfCountryNotAvailable()
{
var actual = Factory.Make((CountrySelection)100);
}
}
}
| 20.536585 | 86 | 0.741093 | [
"MIT"
] | paulgbrown/StatesAndProvinces | StatesAndProvinces.UnitTests/UntTest1.cs | 844 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Clippit.Word;
using DocumentFormat.OpenXml.Packaging;
using Xunit;
using Xunit.Abstractions;
#if !ELIDE_XUNIT_TESTS
namespace Clippit.Tests.Word
{
public class DocumentAssemblerTests : TestsBase
{
public DocumentAssemblerTests(ITestOutputHelper log) : base(log)
{
_sourceDir = new DirectoryInfo("../../../../TestFiles/");
}
private readonly DirectoryInfo _sourceDir;
[Theory]
[InlineData("DA001-TemplateDocument.docx", "DA-Data.xml", false)]
[InlineData("DA002-TemplateDocument.docx", "DA-DataNotHighValueCust.xml", false)]
[InlineData("DA003-Select-XPathFindsNoData.docx", "DA-Data.xml", true)]
[InlineData("DA004-Select-XPathFindsNoDataOptional.docx", "DA-Data.xml", false)]
[InlineData("DA005-SelectRowData-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA006-SelectTestValue-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA007-SelectRepeatingData-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA008-TableElementWithNoTable.docx", "DA-Data.xml", true)]
[InlineData("DA009-InvalidXPath.docx", "DA-Data.xml", true)]
[InlineData("DA010-InvalidXml.docx", "DA-Data.xml", true)]
[InlineData("DA011-SchemaError.docx", "DA-Data.xml", true)]
[InlineData("DA012-OtherMarkupTypes.docx", "DA-Data.xml", true)]
[InlineData("DA013-Runs.docx", "DA-Data.xml", false)]
[InlineData("DA014-TwoRuns-NoValuesSelected.docx", "DA-Data.xml", true)]
[InlineData("DA015-TwoRunsXmlExceptionInFirst.docx", "DA-Data.xml", true)]
[InlineData("DA016-TwoRunsSchemaErrorInSecond.docx", "DA-Data.xml", true)]
[InlineData("DA017-FiveRuns.docx", "DA-Data.xml", true)]
[InlineData("DA018-SmartQuotes.docx", "DA-Data.xml", false)]
[InlineData("DA019-RunIsEntireParagraph.docx", "DA-Data.xml", false)]
[InlineData("DA020-TwoRunsAndNoOtherContent.docx", "DA-Data.xml", true)]
[InlineData("DA021-NestedRepeat.docx", "DA-DataNestedRepeat.xml", false)]
[InlineData("DA022-InvalidXPath.docx", "DA-Data.xml", true)]
[InlineData("DA023-RepeatWOEndRepeat.docx", "DA-Data.xml", true)]
[InlineData("DA026-InvalidRootXmlElement.docx", "DA-Data.xml", true)]
[InlineData("DA027-XPathErrorInPara.docx", "DA-Data.xml", true)]
[InlineData("DA028-NoPrototypeRow.docx", "DA-Data.xml", true)]
[InlineData("DA029-NoDataForCell.docx", "DA-Data.xml", true)]
[InlineData("DA030-TooMuchDataForCell.docx", "DA-TooMuchDataForCell.xml", true)]
[InlineData("DA031-CellDataInAttributes.docx", "DA-CellDataInAttributes.xml", true)]
[InlineData("DA032-TooMuchDataForConditional.docx", "DA-TooMuchDataForConditional.xml", true)]
[InlineData("DA033-ConditionalOnAttribute.docx", "DA-ConditionalOnAttribute.xml", false)]
[InlineData("DA034-HeaderFooter.docx", "DA-Data.xml", false)]
[InlineData("DA035-SchemaErrorInRepeat.docx", "DA-Data.xml", true)]
[InlineData("DA036-SchemaErrorInConditional.docx", "DA-Data.xml", true)]
[InlineData("DA100-TemplateDocument.docx", "DA-Data.xml", false)]
[InlineData("DA101-TemplateDocument.docx", "DA-Data.xml", true)]
[InlineData("DA102-TemplateDocument.docx", "DA-Data.xml", true)]
[InlineData("DA201-TemplateDocument.docx", "DA-Data.xml", false)]
[InlineData("DA202-TemplateDocument.docx", "DA-DataNotHighValueCust.xml", false)]
[InlineData("DA203-Select-XPathFindsNoData.docx", "DA-Data.xml", true)]
[InlineData("DA204-Select-XPathFindsNoDataOptional.docx", "DA-Data.xml", false)]
[InlineData("DA205-SelectRowData-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA206-SelectTestValue-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA207-SelectRepeatingData-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA209-InvalidXPath.docx", "DA-Data.xml", true)]
[InlineData("DA210-InvalidXml.docx", "DA-Data.xml", true)]
[InlineData("DA211-SchemaError.docx", "DA-Data.xml", true)]
[InlineData("DA212-OtherMarkupTypes.docx", "DA-Data.xml", true)]
[InlineData("DA213-Runs.docx", "DA-Data.xml", false)]
[InlineData("DA214-TwoRuns-NoValuesSelected.docx", "DA-Data.xml", true)]
[InlineData("DA215-TwoRunsXmlExceptionInFirst.docx", "DA-Data.xml", true)]
[InlineData("DA216-TwoRunsSchemaErrorInSecond.docx", "DA-Data.xml", true)]
[InlineData("DA217-FiveRuns.docx", "DA-Data.xml", true)]
[InlineData("DA218-SmartQuotes.docx", "DA-Data.xml", false)]
[InlineData("DA219-RunIsEntireParagraph.docx", "DA-Data.xml", false)]
[InlineData("DA220-TwoRunsAndNoOtherContent.docx", "DA-Data.xml", true)]
[InlineData("DA221-NestedRepeat.docx", "DA-DataNestedRepeat.xml", false)]
[InlineData("DA222-InvalidXPath.docx", "DA-Data.xml", true)]
[InlineData("DA223-RepeatWOEndRepeat.docx", "DA-Data.xml", true)]
[InlineData("DA226-InvalidRootXmlElement.docx", "DA-Data.xml", true)]
[InlineData("DA227-XPathErrorInPara.docx", "DA-Data.xml", true)]
[InlineData("DA228-NoPrototypeRow.docx", "DA-Data.xml", true)]
[InlineData("DA229-NoDataForCell.docx", "DA-Data.xml", true)]
[InlineData("DA230-TooMuchDataForCell.docx", "DA-TooMuchDataForCell.xml", true)]
[InlineData("DA231-CellDataInAttributes.docx", "DA-CellDataInAttributes.xml", true)]
[InlineData("DA232-TooMuchDataForConditional.docx", "DA-TooMuchDataForConditional.xml", true)]
[InlineData("DA233-ConditionalOnAttribute.docx", "DA-ConditionalOnAttribute.xml", false)]
[InlineData("DA234-HeaderFooter.docx", "DA-Data.xml", false)]
[InlineData("DA235-Crashes.docx", "DA-Content-List.xml", false)]
[InlineData("DA236-Page-Num-in-Footer.docx", "DA-Content-List.xml", false)]
[InlineData("DA237-SchemaErrorInRepeat.docx", "DA-Data.xml", true)]
[InlineData("DA238-SchemaErrorInConditional.docx", "DA-Data.xml", true)]
[InlineData("DA239-RunLevelCC-Repeat.docx", "DA-Data.xml", false)]
[InlineData("DA250-ConditionalWithRichXPath.docx", "DA250-Address.xml", false)]
[InlineData("DA251-EnhancedTables.docx", "DA-Data.xml", false)]
[InlineData("DA252-Table-With-Sum.docx", "DA-Data.xml", false)]
[InlineData("DA253-Table-With-Sum-Run-Level-CC.docx", "DA-Data.xml", false)]
[InlineData("DA254-Table-With-XPath-Sum.docx", "DA-Data.xml", false)]
[InlineData("DA255-Table-With-XPath-Sum-Run-Level-CC.docx", "DA-Data.xml", false)]
[InlineData("DA256-NoInvalidDocOnErrorInRun.docx", "DA-Data.xml", true)]
[InlineData("DA257-OptionalRepeat.docx", "DA-Data.xml", false)]
[InlineData("DA258-ContentAcceptsCharsAsXPathResult.docx", "DA-Data.xml", false)]
[InlineData("DA259-MultiLineContents.docx", "DA-Data.xml", false)]
[InlineData("DA260-RunLevelRepeat.docx", "DA-Data.xml", false)]
[InlineData("DA261-RunLevelConditional.docx", "DA-Data.xml", false)]
[InlineData("DA262-ConditionalNotMatch.docx", "DA-Data.xml", false)]
[InlineData("DA263-ConditionalNotMatch.docx", "DA-DataSmallCustomer.xml", false)]
[InlineData("DA264-InvalidRunLevelRepeat.docx", "DA-Data.xml", true)]
[InlineData("DA265-RunLevelRepeatWithWhiteSpaceBefore.docx", "DA-Data.xml", false)]
[InlineData("DA266-RunLevelRepeat-NoData.docx", "DA-Data.xml", true)]
[InlineData("DA267-Repeat-HorizontalAlignType.docx", "DA-Data.xml", false)]
[InlineData("DA268-Repeat-VerticalAlignType.docx", "DA-Data.xml", false)]
[InlineData("DA269-Repeat-InvalidAlignType.docx", "DA-Data.xml", true)]
[InlineData("DA270-ImageSelect.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA270A-ImageSelect.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA271-ImageSelectWithRepeat.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA271A-ImageSelectWithRepeat.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA272-ImageSelectWithRepeatHorizontalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA272A-ImageSelectWithRepeatHorizontalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA273-ImageSelectInsideTextBoxWithRepeatVerticalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA273A-ImageSelectInsideTextBoxWithRepeatVerticalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA274-ImageSelectInsideTextBoxWithRepeatHorizontalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA274A-ImageSelectInsideTextBoxWithRepeatHorizontalAlign.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA275-ImageSelectWithRepeatInvalidAlign.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA275A-ImageSelectWithRepeatInvalidAlign.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA276-ImageSelectInsideTable.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA276A-ImageSelectInsideTable.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA277-ImageSelectMissingOrInvalidPictureContent.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA277A-ImageSelectMissingOrInvalidPictureContent.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA278-ImageSelect.docx", "DA-Data-WithImagesInvalidPath.xml", true)]
[InlineData("DA278A-ImageSelect.docx", "DA-Data-WithImagesInvalidPath.xml", true)]
[InlineData("DA279-ImageSelectWithRepeat.docx", "DA-Data-WithImagesInvalidMIMEType.xml", true)]
[InlineData("DA279A-ImageSelectWithRepeat.docx", "DA-Data-WithImagesInvalidMIMEType.xml", true)]
[InlineData("DA280-ImageSelectWithRepeat.docx", "DA-Data-WithImagesInvalidImageDataFormat.xml", true)]
[InlineData("DA280A-ImageSelectWithRepeat.docx", "DA-Data-WithImagesInvalidImageDataFormat.xml", true)]
[InlineData("DA281-ImageSelectExtraWhitespaceBeforeImageContent.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA281A-ImageSelectExtraWhitespaceBeforeImageContent.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA282-ImageSelectWithHeader.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA282A-ImageSelectWithHeader.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA282-ImageSelectWithHeader.docx", "DA-Data-WithImagesInvalidPath.xml", true)]
[InlineData("DA282A-ImageSelectWithHeader.docx", "DA-Data-WithImagesInvalidPath.xml", true)]
[InlineData("DA283-ImageSelectWithFooter.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA283A-ImageSelectWithFooter.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA284-ImageSelectWithHeaderAndFooter.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA284A-ImageSelectWithHeaderAndFooter.docx", "DA-Data-WithImages.xml", false)]
[InlineData("DA285-ImageSelectNoParagraphFollowedAfterMetadata.docx", "DA-Data-WithImages.xml", true)]
[InlineData("DA285A-ImageSelectNoParagraphFollowedAfterMetadata.docx", "DA-Data-WithImages.xml", true)]
public void DA101(string name, string data, bool err)
{
var templateDocx = new FileInfo(Path.Combine(_sourceDir.FullName, name));
var dataFile = new FileInfo(Path.Combine(_sourceDir.FullName, data));
var wmlTemplate = new WmlDocument(templateDocx.FullName);
var xmldata = XElement.Load(dataFile.FullName);
var afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, xmldata, out var returnedTemplateError);
var assembledDocx = new FileInfo(Path.Combine(TempDir, templateDocx.Name.Replace(".docx", "-processed-by-DocumentAssembler.docx")));
afterAssembling.SaveAs(assembledDocx.FullName);
Validate(assembledDocx);
Assert.Equal(err, returnedTemplateError);
}
[Theory]
[InlineData("DA259-MultiLineContents.docx", "DA-Data.xml", false)]
public void DA259(string name, string data, bool err)
{
DA101(name, data, err);
var assembledDocx = new FileInfo(Path.Combine(TempDir, name.Replace(".docx", "-processed-by-DocumentAssembler.docx")));
var afterAssembling = new WmlDocument(assembledDocx.FullName);
var brCount = afterAssembling.MainDocumentPart
.Element(W.body)
.Elements(W.p).ElementAt(1)
.Elements(W.r)
.Elements(W.br).Count();
Assert.Equal(4, brCount);
}
[Theory]
[InlineData("DA024-TrackedRevisions.docx", "DA-Data.xml")]
public void DA102_Throws(string name, string data)
{
var templateDocx = new FileInfo(Path.Combine(_sourceDir.FullName, name));
var dataFile = new FileInfo(Path.Combine(_sourceDir.FullName, data));
var wmlTemplate = new WmlDocument(templateDocx.FullName);
var xmldata = XElement.Load(dataFile.FullName);
bool returnedTemplateError;
WmlDocument afterAssembling;
Assert.Throws<OpenXmlPowerToolsException>(() =>
{
afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, xmldata, out returnedTemplateError);
});
}
[Theory]
[InlineData("DA025-TemplateDocument.docx", "DA-Data.xml", false)]
public void DA103_UseXmlDocument(string name, string data, bool err)
{
var templateDocx = new FileInfo(Path.Combine(_sourceDir.FullName, name));
var dataFile = new FileInfo(Path.Combine(_sourceDir.FullName, data));
var wmlTemplate = new WmlDocument(templateDocx.FullName);
var xmldata = new XmlDocument();
xmldata.Load(dataFile.FullName);
var afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, xmldata, out var returnedTemplateError);
var assembledDocx = new FileInfo(Path.Combine(TempDir, templateDocx.Name.Replace(".docx", "-processed-by-DocumentAssembler.docx")));
afterAssembling.SaveAs(assembledDocx.FullName);
Validate(assembledDocx);
Assert.Equal(err, returnedTemplateError);
}
private void Validate(FileInfo fi)
{
using var wDoc = WordprocessingDocument.Open(fi.FullName, false);
Validate(wDoc, s_expectedErrors);
}
private static readonly List<string> s_expectedErrors = new()
{
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:evenHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:evenVBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRow' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRowFirstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRowLastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRow' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRowFirstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRowLastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:noHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:noVBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:oddHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:oddVBand' attribute is not declared.",
};
}
}
#endif
| 65.724409 | 144 | 0.684378 | [
"MIT"
] | nmase88/Clippit | OpenXmlPowerTools.Tests/Word/DocumentAssemblerTests.cs | 16,696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ListOfPredicates
{
class StartUp
{
static void Main()
{
int endofTheRange = int.Parse(Console.ReadLine());
List<int> dividers = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.Distinct()
.ToList();
List<int> numbers = new List<int>();
for (int i = 1; i <= endofTheRange; i++)
{
numbers.Add(i);
}
Action<List<int>> print = x => Console.WriteLine(string.Join(" ", x));
for (int i = 0; i < dividers.Count; i++)
{
Predicate<int> predicate = x => x % dividers[i] != 0;
numbers.RemoveAll(predicate);
}
print(numbers);
}
}
}
| 24.736842 | 82 | 0.476596 | [
"MIT"
] | A-Manev/SoftUni-CSharp-Advanced-january-2020 | Functional Programming - Exercise/09. List Of Predicates/StartUp.cs | 942 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Components;
namespace StackableUi.Component.Button
{
public class ButtonBase: SComponentBase
{
[Parameter] public EnumButtonType Type { get; set; } = EnumButtonType.Default;
}
}
| 22.615385 | 86 | 0.744898 | [
"MIT"
] | hueifeng/StackableUi | src/StackableUi.Component/Button/ButtonBase.cs | 296 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// An immutable client-side representation of an Azure virtual machine extension image version.
/// </summary>
public interface IVirtualMachineExtensionImageVersion :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Models.VirtualMachineExtensionImageInner>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName
{
/// <summary>
/// Gets the region in which virtual machine extension image version is available.
/// </summary>
string RegionName { get; }
/// <summary>
/// Gets the resource ID of the extension image version.
/// </summary>
string Id { get; }
/// <summary>
/// Gets the virtual machine extension image type this version belongs to.
/// </summary>
Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtensionImageType Type { get; }
/// <return>Virtual machine extension image this version represents.</return>
Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtensionImage GetImage();
/// <return>An observable upon subscription emits the image.</return>
Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtensionImage> GetImageAsync(CancellationToken cancellationToken = default(CancellationToken));
}
} | 46.315789 | 166 | 0.715909 | [
"MIT"
] | abharath27/azure-libraries-for-net | src/ResourceManagement/Compute/Domain/IVirtualMachineExtensionImageVersion.cs | 1,760 | 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("Actions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Actions")]
[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("b2744174-c251-4fef-855a-88e746379f60")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.351351 | 84 | 0.74602 | [
"MIT"
] | cheficha/TelerikAcademyAlpha | Actions/Actions/Properties/AssemblyInfo.cs | 1,385 | 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("AgeCalculation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AgeCalculation")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("630e9c13-caa5-4317-b843-496b7b51654c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.745896 | [
"MIT"
] | PetarTilevRusev/Introduction-to-Programming-Homework | AgeCalculation/Properties/AssemblyInfo.cs | 1,404 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
namespace Microsoft.EntityFrameworkCore.Migrations.Design
{
/// <summary>
/// Used to generate code for migrations.
/// </summary>
public interface IMigrationsCodeGenerator : ILanguageBasedService
{
/// <summary>
/// Generates the migration metadata code.
/// </summary>
/// <param name="migrationNamespace"> The migration's namespace. </param>
/// <param name="contextType"> The migration's <see cref="DbContext" /> type. </param>
/// <param name="migrationName"> The migration's name. </param>
/// <param name="migrationId"> The migration's ID. </param>
/// <param name="targetModel"> The migration's target model. </param>
/// <returns> The migration metadata code. </returns>
string GenerateMetadata(
string? migrationNamespace,
Type contextType,
string migrationName,
string migrationId,
IModel targetModel);
/// <summary>
/// Generates the migration code.
/// </summary>
/// <param name="migrationNamespace"> The migration's namespace. </param>
/// <param name="migrationName"> The migration's name. </param>
/// <param name="upOperations"> The migration's up operations. </param>
/// <param name="downOperations"> The migration's down operations. </param>
/// <returns> The migration code. </returns>
string GenerateMigration(
string? migrationNamespace,
string migrationName,
IReadOnlyList<MigrationOperation> upOperations,
IReadOnlyList<MigrationOperation> downOperations);
/// <summary>
/// Generates the model snapshot code.
/// </summary>
/// <param name="modelSnapshotNamespace"> The model snapshot's namespace. </param>
/// <param name="contextType"> The model snapshot's <see cref="DbContext" /> type. </param>
/// <param name="modelSnapshotName"> The model snapshot's name. </param>
/// <param name="model"> The model. </param>
/// <returns> The model snapshot code. </returns>
string GenerateSnapshot(
string? modelSnapshotNamespace,
Type contextType,
string modelSnapshotName,
IModel model);
/// <summary>
/// Gets the file extension code files should use.
/// </summary>
/// <value> The file extension. </value>
string FileExtension { get; }
}
}
| 42.176471 | 99 | 0.622734 | [
"MIT"
] | FelicePollano/efcore | src/EFCore.Design/Migrations/Design/IMigrationsCodeGenerator.cs | 2,868 | C# |
using System;
using Arrowgene.O2Jam.Server.Common;
using Arrowgene.O2Jam.Server.Core;
using Arrowgene.O2Jam.Server.Packet;
using Arrowgene.Logging;
using Arrowgene.Networking.Tcp;
namespace Arrowgene.O2Jam.Server.Logging
{
public class ServerLogger : Logger
{
private Setting _setting;
public override void Initialize(string identity, string name, Action<Log> write, object configuration)
{
base.Initialize(identity, name, write, configuration);
_setting = configuration as Setting;
if (_setting == null)
{
Error("Couldn't apply ServerLogger configuration");
}
}
public void Info(Client client, string message)
{
Info($"{client.Identity} {message}");
}
public void Debug(Client client, string message)
{
Debug($"{client.Identity} {message}");
}
public void Error(Client client, string message)
{
Error($"{client.Identity} {message}");
}
public void Exception(Client client, Exception exception)
{
if (exception == null)
{
Write(LogLevel.Error, $"{client.Identity} Exception was null.", null);
}
else
{
Write(LogLevel.Error, $"{client.Identity} {exception}", exception);
}
}
public void Info(ITcpSocket socket, string message)
{
Info($"[{socket.Identity}] {message}");
}
public void Debug(ITcpSocket socket, string message)
{
Debug($"[{socket.Identity}] {message}");
}
public void Error(ITcpSocket socket, string message)
{
Error($"[{socket.Identity}] {message}");
}
public void Exception(ITcpSocket socket, Exception exception)
{
if (exception == null)
{
Write(LogLevel.Error, $"{socket.Identity} Exception was null.", null);
}
else
{
Write(LogLevel.Error, $"{socket.Identity} {exception}", exception);
}
}
public void Packet(ITcpSocket socket, NetPacket packet)
{
Write(LogLevel.Info, $"{socket.Identity}{Environment.NewLine}{packet.AsString()}", packet);
}
public void Packet(Client client, NetPacket packet)
{
Write(LogLevel.Info, $"{client.Identity}{Environment.NewLine}{packet.AsString()}", packet);
}
public void Data(ITcpSocket socket, byte[] data, string message = "Data")
{
Write(LogLevel.Info, $"{socket.Identity} {message}{Environment.NewLine}{Util.HexDump(data)}", data);
}
public void Data(Client client, byte[] data, string message = "Data")
{
Write(LogLevel.Info, $"{client.Identity} {message}{Environment.NewLine}{Util.HexDump(data)}", data);
}
}
} | 30.765306 | 112 | 0.558541 | [
"MIT"
] | sebastian-heinz/Arrowgene.O2Jam | Arrowgene.O2Jam.Server/Logging/ServerLogger.cs | 3,017 | C# |
namespace Logic
{
/// <summary>
/// Json Validator.
/// </summary>
public interface IJsonValidator
{
/// <summary>
/// Checks if string is json.
/// </summary>
/// <param name="value">String for checking.</param>
/// <returns>true if string is json.</returns>
public bool IsValid(string value);
}
}
| 23.25 | 60 | 0.537634 | [
"MIT"
] | ntulenev/KafkaSimpleAppender | src/Logic/IJsonValidator.cs | 374 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementAndStatementStatementNotStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString")]
public class Wafv2WebAclRuleStatementAndStatementStatementNotStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString : aws.IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString
{
}
}
| 49.75 | 311 | 0.902848 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2WebAclRuleStatementAndStatementStatementNotStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString.cs | 597 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mindbox.WorkingCalendar
{
public sealed class WorkingCalendar
{
private static readonly IReadOnlyDictionary<DayOfWeek, int> dayOfWeekOffsets = new Dictionary<DayOfWeek, int>
{
[DayOfWeek.Monday] = 0,
[DayOfWeek.Tuesday] = 1,
[DayOfWeek.Wednesday] = 2,
[DayOfWeek.Thursday] = 3,
[DayOfWeek.Friday] = 4,
[DayOfWeek.Saturday] = 5,
[DayOfWeek.Sunday] = 6
};
public static WorkingCalendar Russia { get; } = new WorkingCalendar(new RussianWorkingDaysExceptionsProvider());
public DateRange SupportedDateRange { get; }
private readonly IWorkingDaysExceptionsProvider exceptionsProvider;
public WorkingCalendar(IWorkingDaysExceptionsProvider exceptionsProvider)
{
if (exceptionsProvider == null)
throw new ArgumentNullException(nameof(exceptionsProvider));
this.exceptionsProvider = exceptionsProvider;
SupportedDateRange = exceptionsProvider.SupportedDateRange;
}
public WorkingCalendar(IDictionary<DateTime, DayType> exceptions) : this(new FixedWorkingDaysExceptionsProvider(exceptions))
{
}
public bool IsWorkingDay(DateTime dateTime)
{
switch (GetDayType(dateTime))
{
case DayType.Working:
case DayType.Short:
return true;
case DayType.Holiday:
case DayType.Weekend:
return false;
default:
throw new NotSupportedException($"Unknown DayType value: {GetDayType(dateTime)}");
}
}
public DayType GetDayType(DateTime dateTime)
{
if (exceptionsProvider.TryGet(dateTime.Date, out var result))
{
return result;
}
else if (dateTime.DayOfWeek.IsWeekend())
{
return DayType.Weekend;
}
else
{
return DayType.Working;
}
}
/// <summary>
/// Computes whole working days count in period considering holidays and extra working days.
/// </summary>
/// <param name="startDateTime">Period start date and time.</param>
/// <param name="endDateTime">Period end date and time.</param>
public int CountWorkingDaysInPeriod(DateTime startDateTime, DateTime endDateTime)
{
if (endDateTime < startDateTime)
throw new ArgumentException("startDateTime must be greater then or equal to endDateTime.");
var startDateTimeRounded = startDateTime.Date == startDateTime
? startDateTime
: startDateTime.Date.AddDays(1);
var endDateTimeRounded = endDateTime.Date;
var totalElapsedDays = (int) (endDateTimeRounded - startDateTimeRounded).TotalDays;
var daysFromNearestMonday = dayOfWeekOffsets[startDateTimeRounded.DayOfWeek] + totalElapsedDays;
var weekendDays = (daysFromNearestMonday / 7) * 2
+ (daysFromNearestMonday % 7 == 6 ? 1 : 0)
- (startDateTimeRounded.DayOfWeek == DayOfWeek.Sunday ? 1 : 0);
var exceptionsInPeriod = exceptionsProvider.GetExceptionsInPeriod(startDateTimeRounded, endDateTimeRounded).ToArray();
var nonWeekendHolidays = exceptionsInPeriod
.Where(exception => exception.DayType == DayType.Holiday)
.Count(exception => !exception.Date.DayOfWeek.IsWeekend());
var workingWeekendDays = exceptionsInPeriod
.Where(exception => exception.DayType == DayType.Working || exception.DayType == DayType.Short)
.Count(exception => exception.Date.DayOfWeek.IsWeekend());
var dateParts = TimeSpan.Zero;
if (IsWorkingDay(startDateTime))
{
dateParts = dateParts.Add(startDateTimeRounded - startDateTime);
}
if (IsWorkingDay(endDateTime))
{
dateParts = dateParts.Add(endDateTime - endDateTimeRounded);
}
totalElapsedDays += (int)dateParts.TotalDays;
return totalElapsedDays - weekendDays - nonWeekendHolidays + workingWeekendDays;
}
/// <summary>
/// Computes DateTime in `daysToAdd` working days after `dateTime`.
/// </summary>
public DateTime AddWorkingDays(DateTime dateTime, int daysToAdd)
{
if (daysToAdd == 0)
return dateTime;
var result = dateTime;
var oneDayPeriod = daysToAdd > 0 ? 1 : -1;
var addedDays = 0;
while (addedDays != daysToAdd)
{
result += TimeSpan.FromDays(oneDayPeriod);
if (IsWorkingDay(result))
{
addedDays += oneDayPeriod;
}
}
return result;
}
}
} | 29.443662 | 126 | 0.719684 | [
"MIT"
] | mindbox-moscow/working-calendar | Mindbox.WorkingCalendar/WorkingCalendar.cs | 4,183 | C# |
using VI.NumSharp.Arrays;
namespace VI.Neural.Layer
{
public class MultipleActivationLayer : IMultipleLayer
{
public MultipleActivationLayer(int size, int[] conectionsSize)
{
Size = size;
ConectionsSize = conectionsSize;
}
public Array<FloatArray2D> KnowlodgeMatrix { get; set; }
public Array<FloatArray2D> GradientMatrix { get; set; }
public Array<FloatArray> SumVector { get; set; }
public FloatArray Sum { get; set; }
public FloatArray ErrorVector { get; set; }
public FloatArray BiasVector { get; set; }
public FloatArray OutputVector { get; set; }
public int Size { get; set; }
public int[] ConectionsSize { get; set; }
public float LearningRate { get; set; }
public float CachedLearningRate { get; set; }
public float Momentum { get; set; }
public float CachedMomentum { get; set; }
}
} | 31.064516 | 70 | 0.617861 | [
"MIT"
] | snownz/Virtual-Intelligence | VI/VI.Neural/Layer/MultipleActivationLayer.cs | 965 | C# |
using System;
using Microsoft.Extensions.Logging;
using System.Threading;
namespace Boyd.DataBuses.Interfaces
{
/// <summary>
/// provides a mechanism to couple duplex data pipelines
/// </summary>
public interface IDataCoupler<TData>
{
/// <summary>
///
/// </summary>
/// <param name="pObjEgress"></param>
/// <param name="pObjIngress"></param>
/// <param name="pLogger"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IDisposable CoupleEgressToIngress(IDataEgress<TData> pObjEgress, IDataIngress<TData> pObjIngress, ILogger pLogger, CancellationToken cancellationToken);
}
} | 29.5 | 160 | 0.632768 | [
"MIT"
] | akboyd88/DataBuses | DataBuses/Interfaces/IDataCoupler.cs | 710 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssemblyDefender.Net
{
public abstract class SignaturePredicate
{
protected bool _defaultValue;
public virtual bool Predicate(Signature signature)
{
switch (signature.SignatureType)
{
case SignatureType.Assembly:
{
if (_defaultValue != Predicate((AssemblyReference)signature))
return !_defaultValue;
}
break;
case SignatureType.Module:
{
if (_defaultValue != Predicate((ModuleReference)signature))
return !_defaultValue;
}
break;
case SignatureType.File:
{
if (_defaultValue != Predicate((FileReference)signature))
return !_defaultValue;
}
break;
case SignatureType.Type:
{
if (_defaultValue != Predicate((TypeSignature)signature))
return !_defaultValue;
}
break;
case SignatureType.Method:
{
if (_defaultValue != Predicate((MethodSignature)signature))
return !_defaultValue;
}
break;
case SignatureType.Field:
{
if (_defaultValue != Predicate((FieldReference)signature))
return !_defaultValue;
}
break;
default:
throw new InvalidOperationException();
}
return _defaultValue;
}
public virtual bool Predicate(AssemblyReference assemblyRef)
{
return _defaultValue;
}
public virtual bool Predicate(ModuleReference moduleRef)
{
return _defaultValue;
}
public virtual bool Predicate(FileReference fileRef)
{
return _defaultValue;
}
public virtual bool Predicate(TypeSignature typeSig)
{
switch (typeSig.ElementCode)
{
case TypeElementCode.Array:
{
if (_defaultValue != Predicate((ArrayType)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.ByRef:
{
if (_defaultValue != Predicate((ByRefType)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.CustomModifier:
{
if (_defaultValue != Predicate((CustomModifier)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.FunctionPointer:
{
if (_defaultValue != Predicate((FunctionPointer)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.GenericParameter:
{
if (_defaultValue != Predicate((GenericParameterType)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.GenericType:
{
if (_defaultValue != Predicate((GenericTypeReference)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.Pinned:
{
if (_defaultValue != Predicate((PinnedType)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.Pointer:
{
if (_defaultValue != Predicate((PointerType)typeSig))
return !_defaultValue;
}
break;
case TypeElementCode.DeclaringType:
{
if (_defaultValue != Predicate((TypeReference)typeSig))
return !_defaultValue;
}
break;
default:
throw new InvalidOperationException();
}
return _defaultValue;
}
public virtual bool Predicate(ArrayType arrayType)
{
if (_defaultValue != Predicate(arrayType.ElementType))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(ByRefType byRefType)
{
if (_defaultValue != Predicate(byRefType.ElementType))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(CustomModifier customModifier)
{
if (customModifier.Modifier != null)
{
if (_defaultValue != Predicate(customModifier.Modifier))
return !_defaultValue;
}
if (_defaultValue != Predicate(customModifier.ElementType))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(FunctionPointer functionPointer)
{
if (_defaultValue != Predicate(functionPointer.CallSite))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(GenericParameterType genericType)
{
return _defaultValue;
}
public virtual bool Predicate(PinnedType pinnedType)
{
if (_defaultValue != Predicate(pinnedType.ElementType))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(PointerType pointerType)
{
if (_defaultValue != Predicate(pointerType.ElementType))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(TypeReference typeRef)
{
if (typeRef.Owner != null)
{
if (_defaultValue != Predicate(typeRef.Owner))
return !_defaultValue;
}
return _defaultValue;
}
public virtual bool Predicate(GenericTypeReference genericTypeRef)
{
if (_defaultValue != Predicate(genericTypeRef.DeclaringType))
return !_defaultValue;
for (int i = 0; i < genericTypeRef.GenericArguments.Count; i++)
{
if (_defaultValue != Predicate(genericTypeRef.GenericArguments[i]))
return !_defaultValue;
}
return _defaultValue;
}
public virtual bool Predicate(MethodSignature methodSig)
{
switch (methodSig.Type)
{
case MethodSignatureType.CallSite:
{
if (_defaultValue != Predicate((CallSite)methodSig))
return !_defaultValue;
}
break;
case MethodSignatureType.GenericMethod:
{
if (_defaultValue != Predicate((GenericMethodReference)methodSig))
return !_defaultValue;
}
break;
case MethodSignatureType.DeclaringMethod:
{
if (_defaultValue != Predicate((MethodReference)methodSig))
return !_defaultValue;
}
break;
default:
throw new InvalidOperationException();
}
return _defaultValue;
}
public virtual bool Predicate(CallSite callSite)
{
for (int i = 0; i < callSite.Arguments.Count; i++)
{
if (_defaultValue != Predicate(callSite.Arguments[i]))
return !_defaultValue;
}
return _defaultValue;
}
public virtual bool Predicate(MethodReference methodRef)
{
if (_defaultValue != Predicate(methodRef.Owner))
return !_defaultValue;
if (_defaultValue != Predicate(methodRef.CallSite))
return !_defaultValue;
return _defaultValue;
}
public virtual bool Predicate(GenericMethodReference genericMethodRef)
{
if (_defaultValue != Predicate(genericMethodRef.DeclaringMethod))
return !_defaultValue;
for (int i = 0; i < genericMethodRef.GenericArguments.Count; i++)
{
if (_defaultValue != Predicate(genericMethodRef.GenericArguments[i]))
return !_defaultValue;
}
return _defaultValue;
}
public virtual bool Predicate(FieldReference fieldRef)
{
if (_defaultValue != Predicate(fieldRef.FieldType))
return !_defaultValue;
if (_defaultValue != Predicate(fieldRef.Owner))
return !_defaultValue;
return _defaultValue;
}
}
}
| 21.72327 | 73 | 0.679357 | [
"MIT"
] | nickyandreev/AssemblyDefender | src/AssemblyDefender.Net/Signature/SignaturePredicate.cs | 6,910 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ghostscript.NET;
using Ghostscript.NET.Rasterizer;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using NLog;
using MongoDB.Driver;
using System.Drawing;
using iTextSharp.text.pdf;
namespace ScanMonitorApp
{
class PdfRasterizer
{
//private GhostscriptVersionInfo _lastInstalledVersion = null;
private static GhostscriptRasterizer _rasterizer = new GhostscriptRasterizer();
private Dictionary<int, System.Drawing.Image> _pageCache = new Dictionary<int, System.Drawing.Image>();
private string _inputPdfPath;
private List<int> _pageRotationInfo = new List<int>();
private List<iTextSharp.text.Rectangle> _pageSizes = new List<iTextSharp.text.Rectangle>();
private int _pointsPerInch = 0;
private static Logger logger = LogManager.GetCurrentClassLogger();
public PdfRasterizer(string inputPdfPath, int pointsPerInch)
{
_pointsPerInch = pointsPerInch;
// Extract info from pdf using iTextSharp
try
{
using (Stream newpdfStream = new FileStream(inputPdfPath, FileMode.Open, FileAccess.Read))
{
using (PdfReader pdfReader = new PdfReader(newpdfStream))
{
int numPagesToUse = pdfReader.NumberOfPages;
for (int pageNum = 1; pageNum <= numPagesToUse; pageNum++)
{
iTextSharp.text.Rectangle pageRect = pdfReader.GetPageSize(pageNum);
_pageSizes.Add(pageRect);
int pageRot = pdfReader.GetPageRotation(pageNum);
_pageRotationInfo.Add(pageRot);
}
}
}
}
catch (Exception excp)
{
logger.Error("Cannot open PDF with iTextSharp {0} excp {1}", inputPdfPath, excp.Message);
}
//_lastInstalledVersion =
// GhostscriptVersionInfo.GetLastInstalledVersion(
// GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
// GhostscriptLicense.GPL);
try
{
//string inpPath = inputPdfPath.Replace("/", @"\");
byte[] buffer = File.ReadAllBytes(inputPdfPath);
MemoryStream ms = new MemoryStream(buffer);
_rasterizer.Open(ms);
//string inpPath = inputPdfPath.Replace("/", @"\");
//inpPath = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(inpPath));
//_rasterizer.Open(inpPath, _lastInstalledVersion, false);
}
catch (Exception excp)
{
logger.Error("Cannot open PDF with ghostscript {0} excp {1}", inputPdfPath, excp.Message);
}
_inputPdfPath = inputPdfPath;
}
public void Close()
{
_rasterizer.Close();
}
public int NumPages()
{
return _pageRotationInfo.Count;
}
public System.Drawing.Image GetPageImage(int pageNum, bool rotateBasedOnText)
{
// Return from cache if available
if (_pageCache.ContainsKey(pageNum))
return _pageCache[pageNum];
// Fill cache
System.Drawing.Image img = null;
try
{
img = _rasterizer.GetPage(_pointsPerInch, _pointsPerInch, pageNum);
// Rotate image as required
if (rotateBasedOnText)
{
int pageIdx = pageNum - 1;
if (pageIdx < _pageRotationInfo.Count)
if (_pageRotationInfo[pageIdx] != 0)
img = RotateImageWithoutCrop(img, _pageRotationInfo[pageIdx]);
}
_pageCache.Add(pageNum, img);
}
catch (Exception excp)
{
Console.WriteLine("Failed to create image of page {0}", _inputPdfPath, excp.Message);
}
return img;
}
public List<string> GeneratePageFiles(string uniqName, ScanPages scanPages, string outputPath, int maxPages, bool rotateBasedOnText)
{
List<string> imgFileNames = new List<string>();
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
int numPagesToConvert = _rasterizer.PageCount;
if (numPagesToConvert > maxPages)
numPagesToConvert = maxPages;
for (int pageNumber = 1; pageNumber <= numPagesToConvert; pageNumber++)
{
string pageFileName = GetFilenameOfImageOfPage(outputPath, uniqName, pageNumber, true, "jpg");
try
{
System.Drawing.Image img = _rasterizer.GetPage(_pointsPerInch, _pointsPerInch, pageNumber);
// Rotate image as required
if (rotateBasedOnText)
{
if (pageNumber - 1 < scanPages.pageRotations.Count)
if (scanPages.pageRotations[pageNumber - 1] != 0)
img = RotateImageWithoutCrop(img, scanPages.pageRotations[pageNumber - 1]);
}
// Save to file
if (Delimon.Win32.IO.File.Exists(pageFileName))
Delimon.Win32.IO.File.Delete(pageFileName);
img.Save(pageFileName, ImageFormat.Jpeg);
imgFileNames.Add(pageFileName);
}
catch (Exception excp)
{
logger.Error("Failed to create image of page {0} {1}", pageFileName, excp.Message);
}
}
// Stop timing
stopwatch.Stop();
logger.Debug("Converted {0} ({1} pages) to image files in {2}", _inputPdfPath, numPagesToConvert, stopwatch.Elapsed);
return imgFileNames;
}
private Bitmap RotateImage(System.Drawing.Image inputImage, float angle)
{
int outWidth = inputImage.Width;
int outHeight = inputImage.Height;
if ((angle > 60 && angle < 120) || (angle > 240 && angle < 300))
{
outWidth = inputImage.Height;
outHeight = inputImage.Width;
}
Bitmap rotatedImage = new Bitmap(outWidth, outHeight);
using (Graphics g = Graphics.FromImage(rotatedImage))
{
g.TranslateTransform(inputImage.Width / 2, inputImage.Height / 2); //set the rotation point as the center into the matrix
g.RotateTransform(angle); //rotate
g.TranslateTransform(-inputImage.Width / 2, -inputImage.Height / 2); //restore rotation point into the matrix
g.DrawImage(inputImage, new Point(0, 0)); //draw the image on the new bitmap
}
return rotatedImage;
}
public Image RotateImageWithoutCrop(Image b, float angle)
{
if (angle > 0)
{
int l = b.Width;
int h = b.Height;
double an = angle * Math.PI / 180;
double cos = Math.Abs(Math.Cos(an));
double sin = Math.Abs(Math.Sin(an));
int nl = (int)(l * cos + h * sin);
int nh = (int)(l * sin + h * cos);
Bitmap returnBitmap = new Bitmap(nl, nh);
Graphics g = Graphics.FromImage(returnBitmap);
g.TranslateTransform((float)(nl - l) / 2, (float)(nh - h) / 2);
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
g.RotateTransform(angle);
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
g.DrawImage(b, new Point(0, 0));
return returnBitmap;
}
else return b;
}
public static string GetFilenameOfImageOfPage(string baseFolderForImages, string uniqName, int pageNum, bool bCreateFolderIfReqd, string fileExtForced = "")
{
if (fileExtForced != "")
return Path.Combine(ScanDocInfo.GetImageFolderForFile(baseFolderForImages, uniqName, bCreateFolderIfReqd), uniqName + "_" + pageNum.ToString() + "." + fileExtForced).Replace('\\', '/');
string jpgPath = Path.Combine(ScanDocInfo.GetImageFolderForFile(baseFolderForImages, uniqName, bCreateFolderIfReqd), uniqName + "_" + pageNum.ToString() + ".jpg").Replace('\\', '/');
if (File.Exists(jpgPath))
return jpgPath;
string pngPath = Path.Combine(ScanDocInfo.GetImageFolderForFile(baseFolderForImages, uniqName, bCreateFolderIfReqd), uniqName + "_" + pageNum.ToString() + ".png").Replace('\\', '/');
if (File.Exists(pngPath))
return pngPath;
return jpgPath;
}
public static System.Drawing.Image GetImageOfPage(string fileName, int pageNum)
{
int desired_x_dpi = 150;
int desired_y_dpi = 150;
GhostscriptVersionInfo lastInstalledVersion =
GhostscriptVersionInfo.GetLastInstalledVersion(
GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
GhostscriptLicense.GPL);
GhostscriptRasterizer rasterizer = new GhostscriptRasterizer();
rasterizer.Open(fileName, lastInstalledVersion, false);
if (pageNum > rasterizer.PageCount)
return null;
System.Drawing.Image img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNum);
rasterizer = null;
return img;
}
}
}
| 40.995951 | 201 | 0.552933 | [
"MIT"
] | robdobsn/ScanMonitor | ScanMonitorApp/ScanMonitorApp/PdfRasterizer.cs | 10,128 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using TacitusLogger.Exceptions;
namespace TacitusLogger.UnitTests.ExceptionTests
{
[TestFixture]
public class LogDestinationExceptionTests
{
#region Ctor tests
[Test]
public void Ctor_Taking_Message_When_Called_Sets_Exception_Message()
{
// Act
LogDestinationException logDestinationException = new LogDestinationException("message1");
// Assert
Assert.AreEqual("message1", logDestinationException.Message);
}
[Test]
public void Ctor_Taking_Message_When_Called_With_Null_Sets_Null_Exception_Message()
{
// Act
LogDestinationException logDestinationException = new LogDestinationException(null as string);
// Assert
Assert.AreEqual("Exception of type 'TacitusLogger.Exceptions.LogDestinationException' was thrown.", logDestinationException.Message);
}
[Test]
public void Ctor_Taking_Message_When_Called_InnerException_Is_Null()
{
// Act
LogDestinationException logDestinationException = new LogDestinationException("message1");
// Assert
Assert.AreEqual(null, logDestinationException.InnerException);
}
[Test]
public void Ctor_Taking_Message_And_InnerException_When_Called_Sets_Exception_Message_And_InnerException()
{
// Arrange
Exception innerEx = new Exception();
// Act
LogDestinationException logDestinationException = new LogDestinationException("message1", innerEx);
// Assert
Assert.AreEqual("message1", logDestinationException.Message);
Assert.AreEqual(innerEx, logDestinationException.InnerException);
}
[Test]
public void Ctor_Taking_Message_And_InnerException_When_Called_With_Null_Message_Sets_Null_Exception_Message()
{
// Act
LogDestinationException logDestinationException = new LogDestinationException(null as string, new Exception());
// Assert
Assert.AreEqual("Exception of type 'TacitusLogger.Exceptions.LogDestinationException' was thrown.", logDestinationException.Message);
}
[Test]
public void Ctor_Taking_Message_And_InnerException_When_Called_With_Null_Inner_Exception_Sets_Null_Inner_Exception()
{
// Act
LogDestinationException logDestinationException = new LogDestinationException("message1", null as Exception);
// Assert
Assert.AreEqual(null, logDestinationException.InnerException);
}
#endregion
}
}
| 36.116883 | 145 | 0.677095 | [
"Apache-2.0"
] | khanlarmammadov/TacitusLogger | src/TacitusLogger.UnitTests/ExceptionTests/LogDestinationExceptionTests.cs | 2,783 | C# |
using EventCollectorServer.Infrastructure.Interfaces.Configurations;
namespace EventCollectorServer.Infrastructure.Application.Configurations
{
/// <inheritdoc />
public class ApplicationConfiguration : IApplicationConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationConfiguration"/> class.
/// </summary>
/// <param name="secrets">The secrets.</param>
public ApplicationConfiguration(
ISecretConfiguration secrets)
{
Secrets = secrets;
}
/// <inheritdoc />
public ISecretConfiguration Secrets { get; }
}
}
| 26.181818 | 85 | 0.741319 | [
"MIT"
] | AnyCase-Company-LTD/Event-Collector-Server | EventCollectorServer/EventCollectorServer.Infrastructure.Application/Configurations/ApplicationConfiguration.cs | 578 | C# |
namespace BlazorFluentUI
{
public class ScrollDimensions
{
public double ScrollWidth { get; set; }
public double ScrollHeight { get; set; }
}
}
| 19.222222 | 48 | 0.630058 | [
"MIT"
] | 3-PRO/BlazorFluentUI | src/BlazorFluentUI.BFUBaseComponent/ScrollDimensions.cs | 175 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>
/// CA2241: Provide correct arguments to formatting methods
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class ProvideCorrectArgumentsToFormattingMethodsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2241";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.Usage,
RuleLevel.BuildWarningCandidate,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
var formatInfo = new StringFormatInfo(compilationContext.Compilation);
compilationContext.RegisterOperationAction(operationContext =>
{
var invocation = (IInvocationOperation)operationContext.Operation;
StringFormatInfo.Info? info = formatInfo.TryGet(invocation.TargetMethod, operationContext);
if (info == null || invocation.Arguments.Length <= info.FormatStringIndex)
{
// not a target method
return;
}
IArgumentOperation formatStringArgument = invocation.Arguments[info.FormatStringIndex];
if (!object.Equals(formatStringArgument?.Value?.Type, formatInfo.String) ||
!(formatStringArgument?.Value?.ConstantValue.Value is string))
{
// wrong argument
return;
}
var stringFormat = (string)formatStringArgument.Value.ConstantValue.Value;
int expectedStringFormatArgumentCount = GetFormattingArguments(stringFormat);
// explicit parameter case
if (info.ExpectedStringFormatArgumentCount >= 0)
{
// __arglist is not supported here
if (invocation.TargetMethod.IsVararg)
{
// can't deal with this for now.
return;
}
if (info.ExpectedStringFormatArgumentCount != expectedStringFormatArgumentCount)
{
operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule));
}
return;
}
// ensure argument is an array
IArgumentOperation paramsArgument = invocation.Arguments[info.FormatStringIndex + 1];
if (paramsArgument.ArgumentKind is not ArgumentKind.ParamArray and not ArgumentKind.Explicit)
{
// wrong format
return;
}
if (paramsArgument.Value is not IArrayCreationOperation arrayCreation ||
arrayCreation.GetElementType() is not ITypeSymbol elementType ||
!object.Equals(elementType, formatInfo.Object) ||
arrayCreation.DimensionSizes.Length != 1)
{
// wrong format
return;
}
// compiler generating object array for params case
IArrayInitializerOperation intializer = arrayCreation.Initializer;
if (intializer == null)
{
// unsupported format
return;
}
// REVIEW: "ElementValues" is a bit confusing where I need to double dot those to get number of elements
int actualArgumentCount = intializer.ElementValues.Length;
if (actualArgumentCount != expectedStringFormatArgumentCount)
{
operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule));
}
}, OperationKind.Invocation);
});
}
private static int GetFormattingArguments(string format)
{
// code is from mscorlib
// https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Text/StringBuilder.cs#L1312
// return count of this format - {index[,alignment][:formatString]}
var pos = 0;
int len = format.Length;
var uniqueNumbers = new HashSet<int>();
// main loop
while (true)
{
// loop to find starting "{"
char ch;
while (pos < len)
{
ch = format[pos];
pos++;
if (ch == '}')
{
if (pos < len && format[pos] == '}') // Treat as escape character for }}
{
pos++;
}
else
{
return -1;
}
}
if (ch == '{')
{
if (pos < len && format[pos] == '{') // Treat as escape character for {{
{
pos++;
}
else
{
pos--;
break;
}
}
}
// finished with "{"
if (pos == len)
{
break;
}
pos++;
if (pos == len || (ch = format[pos]) < '0' || ch > '9')
{
// finished with "{x"
return -1;
}
// searching for index
var index = 0;
do
{
index = index * 10 + ch - '0';
pos++;
if (pos == len)
{
// wrong index format
return -1;
}
ch = format[pos];
} while (ch >= '0' && ch <= '9' && index < 1000000);
// eat up whitespace
while (pos < len && (ch = format[pos]) == ' ')
{
pos++;
}
// searching for alignment
var width = 0;
if (ch == ',')
{
pos++;
// eat up whitespace
while (pos < len && format[pos] == ' ')
{
pos++;
}
if (pos == len)
{
// wrong format, reached end without "}"
return -1;
}
ch = format[pos];
if (ch == '-')
{
pos++;
if (pos == len)
{
// wrong format. reached end without "}"
return -1;
}
ch = format[pos];
}
if (ch is < '0' or > '9')
{
// wrong format after "-"
return -1;
}
do
{
width = width * 10 + ch - '0';
pos++;
if (pos == len)
{
// wrong width format
return -1;
}
ch = format[pos];
} while (ch >= '0' && ch <= '9' && width < 1000000);
}
// eat up whitespace
while (pos < len && (ch = format[pos]) == ' ')
{
pos++;
}
// searching for embedded format string
if (ch == ':')
{
pos++;
while (true)
{
if (pos == len)
{
// reached end without "}"
return -1;
}
ch = format[pos];
pos++;
if (ch == '{')
{
if (pos < len && format[pos] == '{') // Treat as escape character for {{
pos++;
else
return -1;
}
else if (ch == '}')
{
if (pos < len && format[pos] == '}') // Treat as escape character for }}
{
pos++;
}
else
{
pos--;
break;
}
}
}
}
if (ch != '}')
{
// "}" is expected
return -1;
}
pos++;
uniqueNumbers.Add(index);
} // end of main loop
return uniqueNumbers.Count;
}
private class StringFormatInfo
{
private const string Format = "format";
private readonly ImmutableDictionary<IMethodSymbol, Info> _map;
public StringFormatInfo(Compilation compilation)
{
ImmutableDictionary<IMethodSymbol, Info>.Builder builder = ImmutableDictionary.CreateBuilder<IMethodSymbol, Info>();
INamedTypeSymbol? console = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole);
AddStringFormatMap(builder, console, "Write");
AddStringFormatMap(builder, console, "WriteLine");
INamedTypeSymbol @string = compilation.GetSpecialType(SpecialType.System_String);
AddStringFormatMap(builder, @string, "Format");
_map = builder.ToImmutable();
String = @string;
Object = compilation.GetSpecialType(SpecialType.System_Object);
}
public INamedTypeSymbol String { get; }
public INamedTypeSymbol Object { get; }
public Info? TryGet(IMethodSymbol method, OperationAnalysisContext context)
{
if (_map.TryGetValue(method, out Info? info))
{
return info;
}
// Check if this the underlying method is user configured string formatting method.
var additionalStringFormatMethodsOption = context.Options.GetAdditionalStringFormattingMethodsOption(Rule, context.Operation.Syntax.SyntaxTree, context.Compilation, context.CancellationToken);
if (additionalStringFormatMethodsOption.Contains(method.OriginalDefinition) &&
TryGetFormatInfo(method, out info))
{
return info;
}
// Check if the user configured automatic determination of formatting methods.
// If so, check if the method called has a 'string format' parameter followed by an params array.
var determineAdditionalStringFormattingMethodsAutomatically = context.Options.GetBoolOptionValue(EditorConfigOptionNames.TryDetermineAdditionalStringFormattingMethodsAutomatically,
Rule, context.Operation.Syntax.SyntaxTree, context.Compilation, defaultValue: false, context.CancellationToken);
if (determineAdditionalStringFormattingMethodsAutomatically &&
TryGetFormatInfo(method, out info) &&
info.ExpectedStringFormatArgumentCount == -1)
{
return info;
}
return null;
}
private static void AddStringFormatMap(ImmutableDictionary<IMethodSymbol, Info>.Builder builder, INamedTypeSymbol? type, string methodName)
{
if (type == null)
{
return;
}
foreach (IMethodSymbol method in type.GetMembers(methodName).OfType<IMethodSymbol>())
{
if (TryGetFormatInfo(method, out var formatInfo))
{
builder.Add(method, formatInfo);
}
}
}
private static bool TryGetFormatInfo(IMethodSymbol method, [NotNullWhen(returnValue: true)] out Info? formatInfo)
{
formatInfo = default;
int formatIndex = FindParameterIndexOfName(method.Parameters, Format);
if (formatIndex < 0 || formatIndex == method.Parameters.Length - 1)
{
// no valid format string
return false;
}
if (method.Parameters[formatIndex].Type.SpecialType != SpecialType.System_String)
{
// no valid format string
return false;
}
int expectedArguments = GetExpectedNumberOfArguments(method.Parameters, formatIndex);
formatInfo = new Info(formatIndex, expectedArguments);
return true;
}
private static int GetExpectedNumberOfArguments(ImmutableArray<IParameterSymbol> parameters, int formatIndex)
{
// check params
IParameterSymbol nextParameter = parameters[formatIndex + 1];
if (nextParameter.IsParams)
{
return -1;
}
return parameters.Length - formatIndex - 1;
}
private static int FindParameterIndexOfName(ImmutableArray<IParameterSymbol> parameters, string name)
{
for (var i = 0; i < parameters.Length; i++)
{
if (string.Equals(parameters[i].Name, name, StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
public class Info
{
public Info(int formatIndex, int expectedArguments)
{
FormatStringIndex = formatIndex;
ExpectedStringFormatArgumentCount = expectedArguments;
}
public int FormatStringIndex { get; }
public int ExpectedStringFormatArgumentCount { get; }
}
}
}
} | 39.8125 | 301 | 0.462436 | [
"Apache-2.0"
] | Atrejoe/roslyn-analyzers | src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ProvideCorrectArgumentsToFormattingMethods.cs | 17,836 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ValorantAPI.JsonStructs
{
public class ActiveShard
{
public string puuid { get; set; }
public string game { get; set; }
public string activeShard { get; set; }
}
}
| 20.857143 | 48 | 0.623288 | [
"MIT"
] | Pro-Swapper/ProSwapperValorant | ValorantAPI/JsonStructs/ActiveShard.cs | 294 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IManagedDeviceShutDownRequest.
/// </summary>
public partial interface IManagedDeviceShutDownRequest : IBaseRequest
{
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task PostAsync(
CancellationToken cancellationToken = default);
/// <summary>
/// Issues the POST request and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse"/> object of the request</returns>
System.Threading.Tasks.Task<GraphResponse> PostResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IManagedDeviceShutDownRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IManagedDeviceShutDownRequest Select(string value);
}
}
| 38.122807 | 153 | 0.600552 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IManagedDeviceShutDownRequest.cs | 2,173 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
public class ReflectionUtils
{
public static FieldInfo GetCustomAttributeField<T>(Type type)
{
FieldInfo[] fInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
int l = fInfos.Length;
for (int i = 0; i < l; i++)
{
FieldInfo fInfo = fInfos[i];
if (fInfo.GetCustomAttributes(typeof(T), false).Length == 0) continue;
return fInfo;
}
return null;
}
public static List<FieldInfo> GetCustomAttributeFields<T>(Type type)
{
List<FieldInfo> attributes = new List<FieldInfo>();
FieldInfo[] fInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
int l = fInfos.Length;
for (int i = 0; i < l; i++)
{
FieldInfo fInfo = fInfos[i];
if (fInfo.GetCustomAttributes(typeof(T), false).Length == 0) continue;
attributes.Add(fInfo);
}
return attributes;
}
public static MethodInfo GetCustomAttributeMethod<T>(Type type)
{
MethodInfo[] fInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
int l = fInfos.Length;
for (int i = 0; i < l; i++)
{
MethodInfo fInfo = fInfos[i];
if (fInfo.GetCustomAttributes(typeof(T), false).Length == 0) continue;
return fInfo;
}
return null;
}
} | 28.461538 | 91 | 0.589189 | [
"MIT"
] | tromagon/Gonity | Utils/ReflectionUtils.cs | 1,482 | 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 machinelearning-2014-12-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Amazon.Runtime;
namespace Amazon.MachineLearning
{
///<summary>
/// Common exception for the MachineLearning service.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class AmazonMachineLearningException : AmazonServiceException
{
/// <summary>
/// Construct instance of AmazonMachineLearningException
/// </summary>
/// <param name="message"></param>
public AmazonMachineLearningException(string message)
: base(message)
{
}
/// <summary>
/// Construct instance of AmazonMachineLearningException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public AmazonMachineLearningException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Construct instance of AmazonMachineLearningException
/// </summary>
/// <param name="innerException"></param>
public AmazonMachineLearningException(Exception innerException)
: base(innerException.Message, innerException)
{
}
/// <summary>
/// Construct instance of AmazonMachineLearningException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public AmazonMachineLearningException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode)
{
}
/// <summary>
/// Construct instance of AmazonMachineLearningException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public AmazonMachineLearningException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode)
{
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the AmazonMachineLearningException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected AmazonMachineLearningException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 40.847619 | 178 | 0.658429 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/MachineLearning/Generated/AmazonMachineLearningException.cs | 4,289 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
// 구조체 정보.
public struct PINFO
{
public float MAX_HP; // 체력의 최대치.
public float HP; // 현재 체력
public float BulletPower; // 총알의 힘.
public float MoveSpeed; // 움직임 스피드.
public bool Life; // 플레이어의 생명.
}
public float Speed; // 움직이는 스피드.
public float AttackGap; // 총알이 발사되는 간격.
private PINFO pInfo; // 플레이어 정보.
private Transform Vec; // 카메라 벡터.
private Vector3 MovePos; // 플레이어 움직임에 대한 변수.
private bool ContinuouFire; // 게속 발사할 것인가? 에 대한 플래그.
void Init()
{
// 구조체 정보 초기화.
pInfo.MAX_HP = 100;
pInfo.HP = pInfo.MAX_HP;
pInfo.BulletPower = 20;
pInfo.MoveSpeed = 5;
pInfo.Life = true;
//공개.
AttackGap = 0.2f;
// 비공개
MovePos = Vector3.zero;
ContinuouFire = true;
// 플레이어 정보갱신.
ObjManager.Call().PlayerInfoUpdate();
}
void Start()
{
// 총알 생성 요청.
ObjManager.Call().SetObject("Bullet");
Vec = GameObject.Find("CameraVector").transform;
Init();
}
void Update ()
{
Run();
KeyCheck();
}
// 플레이어 움직임.
void Run()
{
int ButtonDown = 0;
if (Input.GetKey(KeyCode.LeftArrow)) ButtonDown = 1;
if (Input.GetKey(KeyCode.RightArrow)) ButtonDown = 1;
if (Input.GetKey(KeyCode.UpArrow)) ButtonDown = 1;
if (Input.GetKey(KeyCode.DownArrow)) ButtonDown = 1;
// 플레이어가 움직임 버튼에서 손을 땠을 때 Horizontal, Vertical이 0으로 돌아감으로써
// 플레이어의 회전상태가 다시 원상태로 돌아가지 않게 하기 위해서.
if (ButtonDown != 0)
Rotation();
else
return;
transform.Translate(Vector3.forward * Time.deltaTime * pInfo.MoveSpeed * ButtonDown);
}
// 플레이어 회전.
void Rotation()
{
MovePos.Set(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // 벡터 셋팅.
Quaternion q = Quaternion.LookRotation(Vec.TransformDirection(MovePos)); // 회전
if (MovePos != Vector3.zero)
transform.rotation = q;
}
// 총알 키 체크.
void KeyCheck()
{
if (Input.GetButtonDown("Jump")) //스페이스바로 총알 발사
StartCoroutine("NextFire");
else if (Input.GetButtonUp("Jump"))
ContinuouFire = false;
if (Input.GetKeyDown(KeyCode.Q))
ObjManager.Call().MemoryDelete();
// if (Input.GetKeyDown(KeyCode.E))
// ObjManager.Call().CreateObject("Bullet", 20);
}
// 연속발사.
IEnumerator NextFire()
{
ContinuouFire = true;
while (ContinuouFire)
{
// 총알을 리스트에서 가져온다.
BulletInfoSetting(ObjManager.Call().GetObject("Bullet"));
yield return new WaitForSeconds(AttackGap);
}
}
// 총알정보 셋팅.
void BulletInfoSetting(GameObject _Bullet)
{
if (_Bullet == null) return;
Vector3 v = new Vector3(0,-2,0);
// Vector3 screenBottom = new Vector3();
// screenBottom = transform.position-v;
Debug.Log(transform.position);
_Bullet.transform.position = transform.position+v; // 총알의 위치 설정
_Bullet.transform.rotation = transform.rotation; // 총알의 회전 설정.
_Bullet.SetActive(true); // 총알을 활성화 시킨다.
_Bullet.GetComponent<Bullet>().StartCoroutine("MoveBullet"); // 총알을 움직이게 한다.
}
} | 27.94697 | 93 | 0.531309 | [
"MIT"
] | CNU-Core/Core | Assets/ARSurvive/Scripts/Enemy/Player.cs | 4,197 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d2d1svg.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct D2D1_SVG_VIEWBOX
{
[NativeTypeName("FLOAT")]
public float x;
[NativeTypeName("FLOAT")]
public float y;
[NativeTypeName("FLOAT")]
public float width;
[NativeTypeName("FLOAT")]
public float height;
}
}
| 26.73913 | 145 | 0.668293 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/d2d1svg/D2D1_SVG_VIEWBOX.cs | 617 | C# |
// ==========================================================================
// Notifo.io
// ==========================================================================
// Copyright (c) Sebastian Stehle
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using NJsonSchema;
using NSwag.Generation.Processors;
using NSwag.Generation.Processors.Contexts;
namespace Notifo.Areas.Api.OpenApi
{
public sealed class FixProcessor : IOperationProcessor
{
private static readonly JsonSchema StringSchema = new JsonSchema { Type = JsonObjectType.String };
public bool Process(OperationProcessorContext context)
{
foreach (var parameter in context.Parameters.Values)
{
if (parameter.IsRequired && parameter.Schema is { Type: JsonObjectType.String })
{
parameter.Schema = StringSchema;
}
}
return true;
}
}
}
| 32.71875 | 106 | 0.487106 | [
"MIT"
] | INOS-soft/notifo | backend/src/Notifo/Areas/Api/OpenApi/FixProcessor.cs | 1,049 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using ClearCanvas.Common.Utilities;
namespace ClearCanvas.ImageViewer.Imaging
{
/// <summary>
/// Base implementation of a lookup table in the standard grayscale image display pipeline used to transform stored pixel values to manufacturer-independent values implemented as an array of values.
/// </summary>
/// <remarks>
/// Normally, you should not have to inherit directly from this class.
/// <see cref="SimpleDataModalityLut"/> or <see cref="GeneratedDataModalityLut"/> should cover
/// most, if not all, common use cases.
/// </remarks>
[Cloneable(true)]
public abstract class DataModalityLut : IDataModalityLut
{
private event EventHandler _lutChanged;
private int _minInputValue;
private int _maxInputValue;
private double _minOutputValue;
private double _maxOutputValue;
public virtual int MinInputValue
{
get { return _minInputValue; }
set
{
if (value == _minInputValue)
return;
_minInputValue = value;
OnLutChanged();
}
}
public virtual int MaxInputValue
{
get { return _maxInputValue; }
set
{
if (value == _maxInputValue)
return;
_maxInputValue = value;
OnLutChanged();
}
}
/// <summary>
/// Gets or sets the minimum output value.
/// </summary>
public virtual double MinOutputValue
{
get { return _minOutputValue; }
protected set
{
if (_minOutputValue == value)
return;
_minOutputValue = value;
OnLutChanged();
}
}
/// <summary>
/// Gets or sets the maximum output value.
/// </summary>
public virtual double MaxOutputValue
{
get { return _maxOutputValue; }
protected set
{
if (value == _maxOutputValue)
return;
_maxOutputValue = value;
OnLutChanged();
}
}
/// <summary>
/// Gets or sets the output value of the lookup table for a given input value.
/// </summary>
public virtual double this[int input]
{
get
{
if (input <= FirstMappedPixelValue)
return Data[0];
else if (input >= LastMappedPixelValue)
return Data[Length - 1];
else
return Data[input - FirstMappedPixelValue];
}
protected set
{
if (input < FirstMappedPixelValue || input > LastMappedPixelValue)
return;
Data[input - FirstMappedPixelValue] = value;
}
}
double IComposableLut.MinInputValue
{
get { return MinInputValue; }
set { MinInputValue = (int) Math.Round(value); }
}
double IComposableLut.MaxInputValue
{
get { return MaxInputValue; }
set { MaxInputValue = (int) Math.Round(value); }
}
double IComposableLut.MinOutputValue
{
get { return MinOutputValue; }
}
double IComposableLut.MaxOutputValue
{
get { return MaxOutputValue; }
}
double IComposableLut.this[double input]
{
get { return this[(int) Math.Round(input)]; }
}
public event EventHandler LutChanged
{
add { _lutChanged += value; }
remove { _lutChanged -= value; }
}
///<summary>
/// Gets the length of <see cref="Data"/>.
///</summary>
/// <remarks>
/// The reason for this member's existence is that <see cref="Data"/> is lazily-initialized, and thus may
/// not yet exist; this value is based solely on <see cref="FirstMappedPixelValue"/>
/// and <see cref="LastMappedPixelValue"/>.
/// </remarks>
public int Length
{
get { return 1 + LastMappedPixelValue - FirstMappedPixelValue; }
}
public abstract int FirstMappedPixelValue { get; }
/// <summary>
/// Gets the last mapped pixel value.
/// </summary>
public abstract int LastMappedPixelValue { get; }
public abstract double[] Data { get; }
public abstract string GetKey();
public abstract string GetDescription();
IComposableLut IComposableLut.Clone()
{
return Clone();
}
IModalityLut IModalityLut.Clone()
{
return Clone();
}
public IDataModalityLut Clone()
{
return CloneBuilder.Clone(this) as IDataModalityLut;
}
/// <summary>
/// Fires the <see cref="LutChanged"/> event.
/// </summary>
/// <remarks>
/// Inheritors should call this method when any property of the lookup table has changed.
/// </remarks>
protected virtual void OnLutChanged()
{
EventsHelper.Fire(_lutChanged, this, EventArgs.Empty);
}
#region IMemorable Members
/// <summary>
/// Captures the state of the lookup table.
/// </summary>
/// <remarks>
/// <para>
/// The implementation should return an object containing enough state information so that,
/// when <see cref="SetMemento"/> is called, the lookup table can be restored to the original state.
/// </para>
/// <para>
/// If the method is implemented, <see cref="SetMemento"/> must also be implemented.
/// </para>
/// </remarks>
public virtual object CreateMemento()
{
return null;
}
/// <summary>
/// Restores the state of the lookup table.
/// </summary>
/// <param name="memento">An object that was originally created by <see cref="CreateMemento"/>.</param>
/// <remarks>
/// <para>
/// The implementation should return the lookup table to the original state captured by <see cref="CreateMemento"/>.
/// </para>
/// <para>
/// If you implement <see cref="CreateMemento"/> to capture the lookup table's state, you must also implement this method
/// to allow the state to be restored. Failure to do so will result in a <see cref="InvalidOperationException"/>.
/// </para>
/// </remarks>
public virtual void SetMemento(object memento)
{
if (memento != null)
throw new InvalidOperationException(SR.ExceptionMustOverrideSetMemento);
}
#endregion
}
} | 25.282158 | 200 | 0.643525 | [
"Apache-2.0"
] | SNBnani/Xian | ImageViewer/Imaging/DataModalityLut.cs | 6,093 | C# |
using System;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Upgrade;
namespace DNN.Modules.SecurityAnalyzer.Components
{
public class FeatureController : IUpgradeable
{
public string UpgradeModule(string version)
{
switch (version)
{
case "01.00.00":
//Add Extensions Host Page
var moduleDefId = GetModuleDefinition("SecurityAnalyzer", "SecurityAnalyzer");
var auditPage = AddHostPage("Security Analyzer", "Audit site security for best practices.",
"~/Icons/Sigma/Extensions_16x16_Standard.png", "~/Icons/Sigma/Extensions_32x32_Standard.png", true);
var moduleid = AddModuleToPage(auditPage, moduleDefId, "Security Analyzer",
"~/Icons/Sigma/Extensions_32x32_Standard.png");
break;
case "08.00.02":
Utility.CleanUpInstallerFiles();
break;
}
return String.Empty;
}
private static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile)
{
//Call overload with InheritPermisions=True
return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, true);
}
public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile,
bool inheritPermissions)
{
var moduleController = new ModuleController();
ModuleInfo moduleInfo;
var moduleId = Null.NullInteger;
if ((page != null))
{
var isDuplicate = false;
foreach (var kvp in moduleController.GetTabModules(page.TabID))
{
moduleInfo = kvp.Value;
if (moduleInfo.ModuleDefID == moduleDefId)
{
isDuplicate = true;
moduleId = moduleInfo.ModuleID;
}
}
if (!isDuplicate)
{
moduleInfo = new ModuleInfo
{
ModuleID = Null.NullInteger,
PortalID = page.PortalID,
TabID = page.TabID,
ModuleOrder = -1,
ModuleTitle = moduleTitle,
PaneName = Globals.glbDefaultPane,
ModuleDefID = moduleDefId,
CacheTime = 0,
IconFile = moduleIconFile,
AllTabs = false,
Visibility = VisibilityState.None,
InheritViewPermissions = inheritPermissions
};
try
{
moduleId = moduleController.AddModule(moduleInfo);
}
catch (Exception)
{
//DnnLog.Error(exc);
}
}
}
return moduleId;
}
public static int AddModuleToPage(string tabPath, int portalId, int moduleDefId, string moduleTitle,
string moduleIconFile, bool inheritPermissions)
{
var tabController = new TabController();
var moduleId = Null.NullInteger;
var tabID = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString);
if ((tabID != Null.NullInteger))
{
var tab = tabController.GetTab(tabID, portalId, true);
if ((tab != null))
{
moduleId = AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions);
}
}
return moduleId;
}
private static int GetModuleDefinition(string desktopModuleName, string moduleDefinitionName)
{
// get desktop module
var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger);
if (desktopModule == null)
{
return -1;
}
// get module definition
var objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(
moduleDefinitionName, desktopModule.DesktopModuleID);
if (objModuleDefinition == null)
{
return -1;
}
return objModuleDefinition.ModuleDefID;
}
public static TabInfo AddHostPage(string tabName, string description, string tabIconFile,
string tabIconFileLarge, bool isVisible)
{
var tabController = new TabController();
var hostPage = tabController.GetTabByName("Host", Null.NullInteger);
if ((hostPage != null))
{
return AddPage(hostPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible,
new TabPermissionCollection(), true);
}
return null;
}
private static TabInfo AddPage(TabInfo parentTab, string tabName, string description, string tabIconFile,
string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin)
{
var parentId = Null.NullInteger;
var portalId = Null.NullInteger;
if ((parentTab != null))
{
parentId = parentTab.TabID;
portalId = parentTab.PortalID;
}
return AddPage(portalId, parentId, tabName, description, tabIconFile, tabIconFileLarge, isVisible,
permissions, isAdmin);
}
/// -----------------------------------------------------------------------------
/// <summary>
/// AddPage adds a Tab Page
/// </summary>
/// <param name="portalId">The Id of the Portal</param>
/// <param name="parentId">The Id of the Parent Tab</param>
/// <param name="tabName">The Name to give this new Tab</param>
/// <param name="description">Description.</param>
/// <param name="tabIconFile">The Icon for this new Tab</param>
/// <param name="tabIconFileLarge">The large Icon for this new Tab</param>
/// <param name="isVisible">A flag indicating whether the tab is visible</param>
/// <param name="permissions">Page Permissions Collection for this page</param>
/// <param name="isAdmin">Is and admin page</param>
private static TabInfo AddPage(int portalId, int parentId, string tabName, string description,
string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions,
bool isAdmin)
{
var tabController = new TabController();
var tab = tabController.GetTabByName(tabName, portalId, parentId);
if (tab == null || tab.ParentId != parentId)
{
tab = new TabInfo
{
TabID = Null.NullInteger,
PortalID = portalId,
TabName = tabName,
Title = "",
Description = description,
KeyWords = "",
IsVisible = isVisible,
DisableLink = false,
ParentId = parentId,
IconFile = tabIconFile,
IconFileLarge = tabIconFileLarge,
IsDeleted = false
};
tab.TabID = tabController.AddTab(tab, !isAdmin);
if (((permissions != null)))
{
foreach (TabPermissionInfo tabPermission in permissions)
{
tab.TabPermissions.Add(tabPermission, true);
}
TabPermissionController.SaveTabPermissions(tab);
}
}
return tab;
}
}
} | 38.668203 | 124 | 0.528304 | [
"MIT"
] | hismightiness/SecurityAnalyzer | Components/FeatureController.cs | 8,393 | C# |
using MaterialMvvmSample.Utilities;
using MaterialMvvmSample.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MaterialMvvmSample
{
public partial class App : Application
{
public App(INavigationService navigationService)
{
InitializeComponent();
XF.Material.Forms.Material.Init(this, "Material.Style");
XamSvg.Shared.Config.ResourceAssembly = typeof(App).Assembly;
navigationService.SetRootView(ViewNames.LandingView);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| 24.540541 | 73 | 0.627753 | [
"MIT"
] | msc2402/XF-Material-Library | Samples/MaterialMvvmSample/App.xaml.cs | 910 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using static TestVRF.vcsparsing.UtilHelpers;
namespace TestVRF.vcsparsing {
public class DataReaderZFrameByteAnalysis : DataReader {
FILETYPE filetype;
public DataReaderZFrameByteAnalysis(byte[] data, FILETYPE filetype) : base(data) {
if (filetype == FILETYPE.features_file) {
throw new ShaderParserException("file type cannot be features, as they don't contain any zframes");
}
this.filetype = filetype;
}
bool writeAsHtml = false;
public void SetWriteAsHtml(bool writeAsHtml) {
this.writeAsHtml = writeAsHtml;
}
bool saveGlslSources = false;
string outputDir = null;
public void RequestGlslFileSave(string outputDir) {
saveGlslSources = true;
this.outputDir = outputDir;
}
public void PrintByteAnalysis() {
List<(int, int, string)> glslSources = new();
ShowZDataSection(-1);
ShowZFrameHeaderUpdated();
// this applies only to vs files (ps, gs and psrs files don't have this section)
if (filetype == FILETYPE.vs_file) {
// values seen
// 1,2,4,5,8,10,12,16,20,40,48,80,120,160
int blockCountInput = ReadInt16AtPosition();
ShowByteCount("Some kind of state summary (uniforms/variables input?)");
ShowBytes(2, breakLine: false);
TabComment($"nr of data-blocks ({blockCountInput})");
ShowBytes(blockCountInput * 2);
OutputWriteLine("");
}
int blockCount = ReadInt16AtPosition();
ShowByteCount("Data blocks");
ShowBytes(2, breakLine: false);
TabComment($"nr of data-blocks ({blockCount})");
OutputWriteLine("");
for (int i = 0; i < blockCount; i++) {
ShowZDataSection(i);
}
BreakLine();
ShowByteCount("Some kind of state summary (uniforms/variables output?)");
int blockCountOutput = ReadInt16AtPosition();
ShowBytes(2, breakLine: false);
TabComment($"nr of data-blocks ({blockCountOutput})", 1);
ShowBytes(blockCountOutput * 2);
BreakLine();
ShowByteCount();
ShowBytes(4, breakLine: false);
int bin0 = databytes[offset - 4];
int bin1 = databytes[offset - 3];
TabComment($"possible flags {Convert.ToString(bin0, 2).PadLeft(8, '0')} {Convert.ToString(bin1, 2).PadLeft(8, '0')}", 7);
ShowBytes(1, breakLine: false);
TabComment("values seen 0,1", 16);
uint glslSourceCount = ReadUIntAtPosition();
ShowBytes(4, breakLine: false);
TabComment($"glsl source files ({glslSourceCount})", 7);
ShowBytes(1, breakLine: false);
TabComment("values seen 0,1", 16);
BreakLine();
for (int i = 0; i < glslSourceCount; i++) {
var glslSourceItem = ShowZSourceSection(i);
glslSources.Add(glslSourceItem);
}
// End blocks for vs and gs files
if (filetype == FILETYPE.vs_file || filetype == FILETYPE.gs_file) {
ShowZAllEndBlocksTypeVs();
BreakLine();
}
// End blocks for ps and psrs files
if (filetype == FILETYPE.ps_file || filetype == FILETYPE.psrs_file) {
ShowByteCount();
int nrEndBlocks = ReadIntAtPosition();
ShowBytes(4, breakLine: false);
TabComment($"nr of end blocks ({nrEndBlocks})");
OutputWriteLine("");
for (int i = 0; i < nrEndBlocks; i++) {
ShowByteCount($"End-block[{i}]");
int blockId = ReadInt16AtPosition();
ShowBytes(4, breakLine: false);
TabComment($"blockId ref ({blockId})");
ShowBytes(4, breakLine: false);
TabComment("always 0");
int sourceReference = ReadInt16AtPosition();
ShowBytes(4, breakLine: false);
TabComment($"source ref ({sourceReference})");
uint glslPointer = ReadUIntAtPosition();
ShowBytes(4, breakLine: false);
TabComment($"glsl source pointer ({glslPointer})");
ShowBytes(3, breakLine: false);
bool hasData0 = databytes[offset - 3] == 0;
bool hasData1 = databytes[offset - 2] == 0;
bool hasData2 = databytes[offset - 1] == 0;
TabComment($"(data0={hasData0}, data1={hasData1}, data2={hasData2})", 7);
if (hasData0) {
OutputWriteLine("// data-section 0");
ShowBytes(16);
}
if (hasData1) {
OutputWriteLine("// data-section 1");
ShowBytes(20);
}
if (hasData2) {
OutputWriteLine("// data-section 2");
ShowBytes(3);
ShowBytes(8);
ShowBytes(64, 32);
}
OutputWriteLine("");
}
}
EndOfFile();
// write the gsls source, if indicated
if (saveGlslSources && !writeAsHtml) {
SaveGlslSourcestoTxt(glslSources);
}
if (saveGlslSources && writeAsHtml) {
SaveGlslSourcestoHtml(glslSources);
}
}
private void SaveGlslSourcestoHtml(List<(int, int, string)> glslSources) {
foreach (var glslSourceItem in glslSources) {
string htmlFilename = GetGlslHtmlFilename(glslSourceItem.Item3);
string glslFilenamepath = @$"{outputDir}\{htmlFilename}";
if (File.Exists(glslFilenamepath)) {
continue;
}
int glslOffset = glslSourceItem.Item1;
int glslSize = glslSourceItem.Item2;
byte[] glslSourceContent = ReadBytesAtPosition(glslOffset, glslSize, rel: false);
Debug.WriteLine($"writing {glslFilenamepath}");
StreamWriter glslFileWriter = new(glslFilenamepath);
string htmlHeader = GetHtmlHeader(htmlFilename[0..^5], htmlFilename[0..^5]);
glslFileWriter.WriteLine($"{htmlHeader}");
glslFileWriter.Flush();
glslFileWriter.BaseStream.Write(glslSourceContent, 0, glslSourceContent.Length);
glslFileWriter.Flush();
glslFileWriter.WriteLine($"{GetHtmlFooter()}");
glslFileWriter.Flush();
glslFileWriter.Close();
}
}
private void SaveGlslSourcestoTxt(List<(int, int, string)> glslSources) {
foreach (var glslSourceItem in glslSources) {
string glslFilenamepath = @$"{outputDir}\{GetGlslTxtFilename(glslSourceItem.Item3)}";
if (File.Exists(glslFilenamepath)) {
continue;
}
int glslOffset = glslSourceItem.Item1;
int glslSize = glslSourceItem.Item2;
byte[] glslSourceContent = ReadBytesAtPosition(glslOffset, glslSize, rel: false);
Debug.WriteLine($"writing {glslFilenamepath}");
File.WriteAllBytes(glslFilenamepath, glslSourceContent);
}
}
public void PrintIntWithValue() {
int intval = ReadIntAtPosition();
ShowBytes(4, breakLine: false);
TabComment($"{intval}");
}
private bool prevBlockWasZero = false;
public void ShowZDataSection(int blockId) {
int blockSize = ShowZBlockDataHeader(blockId);
ShowZBlockDataBody(blockSize);
}
public int ShowZBlockDataHeader(int blockId) {
int arg0 = ReadIntAtPosition();
int arg1 = ReadIntAtPosition(4);
int arg2 = ReadIntAtPosition(8);
if (arg0 == 0 && arg1 == 0 && arg2 == 0) {
ShowBytes(12, breakLine: false);
TabComment($"data-block[{blockId}]");
return 0;
}
string comment = "";
if (blockId == -1) {
comment = $"leading data";
}
if (blockId >= 0) {
comment = $"data-block[{blockId}]";
}
int blockSize = ReadIntAtPosition();
if (prevBlockWasZero) {
OutputWriteLine("");
}
ShowByteCount(comment);
PrintIntWithValue();
PrintIntWithValue();
PrintIntWithValue();
return blockSize * 4;
}
public void ShowZBlockDataBody(int byteSize) {
if (byteSize == 0) {
prevBlockWasZero = true;
return;
} else {
prevBlockWasZero = false;
}
Comment($"{byteSize / 4}*4 bytes");
ShowBytes(byteSize);
BreakLine();
}
public void ShowZFrameHeaderUpdated() {
ShowByteCount("Frame header");
uint nrArgs = ReadUInt16AtPosition();
ShowBytes(2, breakLine: false);
TabComment($"nr of arguments ({nrArgs})");
OutputWriteLine("");
for (int i = 0; i < nrArgs; i++) {
ShowMurmurString();
int headerOperator = databytes[offset];
if (headerOperator == 0x0e) {
ShowBytes(3);
continue;
}
if (headerOperator == 1) {
int dynExpLen = ReadIntAtPosition(3);
if (dynExpLen == 0) {
ShowBytes(8);
continue;
} else {
ShowBytes(7);
ShowDynamicExpression(dynExpLen);
continue;
}
}
if (headerOperator == 9) {
int dynExpLen = ReadIntAtPosition(3);
if (dynExpLen == 0) {
ShowBytes(8);
continue;
} else {
ShowBytes(7);
ShowDynamicExpression(dynExpLen);
continue;
}
}
if (headerOperator == 5) {
int dynExpLen = ReadIntAtPosition(3);
if (dynExpLen == 0) {
ShowBytes(11);
continue;
} else {
ShowBytes(7);
ShowDynamicExpression(dynExpLen);
continue;
}
}
}
if (nrArgs > 0) {
BreakLine();
}
}
public (int, int, string) ShowZSourceSection(int blockId) {
int sourceSize = ShowZSourceOffsets();
int sourceOffset = offset;
ShowZGlslSourceSummary(blockId);
ShowByteCount();
byte[] fileIdBytes = ReadBytes(16);
string fileIdStr = BytesToString(fileIdBytes);
if (writeAsHtml) {
OutputWrite(GetGlslHtmlLink(fileIdStr));
} else {
OutputWrite(fileIdStr);
}
TabComment($"File ID");
BreakLine();
return (sourceOffset, sourceSize, fileIdStr);
}
public int ShowZSourceOffsets() {
ShowByteCount("glsl source offsets");
uint offset1 = ReadUIntAtPosition();
PrintIntWithValue();
if (offset1 == 0) {
return 0;
}
ShowBytes(4, breakLine: false);
TabComment("always 3");
int sourceSize = ReadIntAtPosition() - 1; // one less because of null-term
PrintIntWithValue();
BreakLine();
return sourceSize;
}
// FIXME - can't I pass the source size here?
public void ShowZGlslSourceSummary(int sourceId) {
int bytesToRead = ReadIntAtPosition(-4);
int endOfSource = offset + bytesToRead;
ShowByteCount($"GLSL-SOURCE[{sourceId}]");
if (bytesToRead == 0) {
OutputWriteLine("// no source present");
}
if (bytesToRead > 100) {
ShowBytes(100);
ShowByteCount();
Comment($"... ({endOfSource - offset} bytes of data not shown)");
} else if (bytesToRead <= 100 && bytesToRead > 0) {
ShowBytes(bytesToRead);
}
offset = endOfSource;
BreakLine();
}
public void ShowZAllEndBlocksTypeVs() {
ShowByteCount();
int nr_end_blocks = ReadIntAtPosition();
ShowBytes(4, breakLine: false);
TabComment($"nr end blocks ({nr_end_blocks})");
BreakLine();
for (int i = 0; i < nr_end_blocks; i++) {
ShowBytes(16);
}
}
private void EndOfFile() {
if (offset != databytes.Length) {
throw new ShaderParserException("End of file not reached!");
}
ShowByteCount();
OutputWriteLine("EOF");
BreakLine();
}
private void ShowMurmurString() {
string nulltermstr = ReadNullTermStringAtPosition();
uint murmur32 = ReadUIntAtPosition(nulltermstr.Length + 1);
uint murmurCheck = MurmurHashPiSeed(nulltermstr.ToLower());
if (murmur32 != murmurCheck) {
throw new ShaderParserException("not a murmur string!");
}
Comment($"{nulltermstr} | 0x{murmur32:x08}");
ShowBytes(nulltermstr.Length + 1 + 4);
}
private void ShowDynamicExpression(int dynExpLen) {
byte[] dynExpDatabytes = ReadBytesAtPosition(0, dynExpLen);
string dynExp = getDynamicExpression(dynExpDatabytes);
OutputWriteLine($"// {dynExp}");
ShowBytes(dynExpLen);
}
private ParseDynamicExpressions myDynParser = null;
private string getDynamicExpression(byte[] dynExpDatabytes) {
if (myDynParser == null) {
myDynParser = new ParseDynamicExpressions();
}
myDynParser.ParseExpression(dynExpDatabytes);
if (myDynParser.errorWhileParsing) {
string errorMessage = $"problem occured parsing dynamic expression {myDynParser.errorMessage}";
Debug.WriteLine(errorMessage);
return errorMessage;
}
return myDynParser.dynamicExpressionResult;
}
}
}
| 36.920673 | 133 | 0.502962 | [
"MIT"
] | robert-hoff/ValveResourceFormat | TestVRF/vcsparsing/DataReaderZFrameByteAnalysis.cs | 15,359 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cor64.Mips.Rsp
{
internal interface IMipsOpcodes
{
void BitwiseLogic(DecodedInstruction inst);
void Add(DecodedInstruction inst);
void Subtract(DecodedInstruction inst);
void Shift(DecodedInstruction inst);
void SetOnLessThan(DecodedInstruction inst);
void TransferReg(DecodedInstruction inst);
void Branch(DecodedInstruction inst);
void Jump(DecodedInstruction inst);
void Store(DecodedInstruction inst);
void Load(DecodedInstruction inst);
void Break(DecodedInstruction inst);
void VectorUnitReserved(DecodedInstruction inst);
void VectorLoad(DecodedInstruction inst);
void VectorStore(DecodedInstruction inst);
void VectorAdd(DecodedInstruction inst);
void VectorSubtract(DecodedInstruction inst);
void VectorMultiply(DecodedInstruction inst);
void VectorAccumulatorReadWrite(DecodedInstruction inst);
void VectorBitwise(DecodedInstruction inst);
void VectorReciprocal(DecodedInstruction inst);
void VectorCompare(DecodedInstruction inst);
void VectorClip(DecodedInstruction inst);
void VectorMove(DecodedInstruction inst);
}
}
| 25 | 66 | 0.677931 | [
"MIT"
] | bryanperris/cor64 | src/cor64/Mips/Rsp/IMipsOpcodes.cs | 1,452 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutoLot.Model.Entities
{
public class SeriLogEntry
{
public int Id { get; set; }
public string? Message { get; set; }
public string? MessageTemplate { get; set; }
public string? Level { get; set; }
public DateTime? TimeStamp { get; set; }
public string? Exception { get; set; }
public string? Properties { get; set; }
public string? LogEvent { get; set; }
public string? SourceContext { get; set; }
public string? RequestPath { get; set; }
public string? ActionName { get; set; }
public string? ApplicationName { get; set; }
public string? MachineName { get; set; }
public string? FilePath { get; set; }
public string? MemberName { get; set; }
public int? LineNumber { get; set; }
public XElement? PropertiesXml => (Properties != null) ? XElement.Parse(Properties) : null;
}
}
| 32.322581 | 95 | 0.668663 | [
"MIT"
] | rontucuman/auto-lot | src/Chapter23_AllProjects/AutoLot.Model/Entities/SeriLogEntry.cs | 1,004 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace NLayerProject.API.DTOs
{
public class CategoryDto
{
public int Id { get; set; }
[Required(ErrorMessage = "{0} alanı gereklidir")]
public string Name { get; set; }
}
}
| 22.3125 | 57 | 0.689076 | [
"MIT"
] | TunaAksit/NLayerProject | NLayerProject.API/DTOs/CategoryDto.cs | 360 | C# |
using System.Threading.Tasks;
namespace Client.Services.Interfaces
{
public interface IClientServerService
{
public void Start();
public Task Stop();
}
} | 18.3 | 41 | 0.666667 | [
"MIT"
] | al3xfischer/DITO | DITO/Client/Services/Interfaces/IClientServerService.cs | 185 | C# |
//
// SEPA.Net SEPA Parser for C#
// https://sepa.codeplex.com
// File: TCDev.SEPA.GenericIdentification32.cs
// Author: Tim Cadenbach, TCDev
// Created: 08.09.2013 - TCA
// Changed: 13.09.2013 - TCA
// Purpose:
//
// Licensed under Microsoft Public License (Ms-PL)
// https://sepa.codeplex.com/license
//
// Recent Changes:
// ==========================================================
using System;
using System.ComponentModel;
using System.Xml.Serialization;
namespace TCDev.SEPA.Generic.Identification
{
[Serializable()]
[DesignerCategory("code")]
public partial class GenericIdentification32
{
private string idField;
private PartyType3Code? tpField;
private PartyType4Code? issrField;
private string shrtNmField;
public string Id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
public PartyType3Code Tp
{
get
{
if (this.tpField.HasValue)
{
return this.tpField.Value;
}
else
{
return default(PartyType3Code);
}
}
set
{
this.tpField = value;
}
}
[XmlIgnore()]
public bool TpSpecified
{
get
{
return this.tpField.HasValue;
}
set
{
if (value == false)
{
this.tpField = null;
}
}
}
public PartyType4Code Issr
{
get
{
if (this.issrField.HasValue)
{
return this.issrField.Value;
}
else
{
return default(PartyType4Code);
}
}
set
{
this.issrField = value;
}
}
[XmlIgnore()]
public bool IssrSpecified
{
get
{
return this.issrField.HasValue;
}
set
{
if (value == false)
{
this.issrField = null;
}
}
}
public string ShrtNm
{
get
{
return this.shrtNmField;
}
set
{
this.shrtNmField = value;
}
}
}
} | 17.736434 | 61 | 0.456731 | [
"Apache-2.0"
] | DeeJayTC/sepa.net | TCDev.SEPA/Generic/Identification/GenericIdentification32.cs | 2,288 | 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("10SrybskoUnleashed")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("10SrybskoUnleashed")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("49ad6cc0-1df0-49cd-aad2-bad2f4313c35")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.945946 | 84 | 0.75 | [
"MIT"
] | lapd87/SoftUniProgrammingFundamentalsCSharp | ProgrammingFundamentalsCSharp/08DictionariesLambdaLINQ/10SrybskoUnleashed/Properties/AssemblyInfo.cs | 1,407 | C# |
using System.Data;
using System.Threading.Tasks;
using DataAccess.Settings;
using Microsoft.Extensions.Options;
using Npgsql;
namespace DataAccess.ConnectionFactories
{
public class NpgConnectionFactory : IConnectionFactory
{
private readonly DatabaseConnectionSettings _settings;
public NpgConnectionFactory(IOptions<DatabaseConnectionSettings> options)
{
_settings = options.Value;
}
public async Task<IDbConnection> CreateConnection()
{
var connection = new NpgsqlConnection(_settings.ConnectionString);
await connection.OpenAsync().ConfigureAwait(false);
return connection;
}
}
} | 26.111111 | 81 | 0.695035 | [
"MIT"
] | jva44ka/sunset_prediction | DataAccess/ConnectionFactories/NpgConnectionFactory.cs | 707 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Tests.NonVisual.Filtering
{
[TestFixture]
public class FilterQueryParserTest
{
[Test]
public void TestApplyQueriesBareWords()
{
const string query = "looking for a beatmap";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("looking for a beatmap", filterCriteria.SearchText);
Assert.AreEqual(4, filterCriteria.SearchTerms.Length);
}
/*
* The following tests have been written a bit strangely (they don't check exact
* bound equality with what the filter says).
* This is to account for floating-point arithmetic issues.
* For example, specifying a bpm<140 filter would previously match beatmaps with BPM
* of 139.99999, which would be displayed in the UI as 140.
* Due to this the tests check the last tick inside the range and the first tick
* outside of the range.
*/
[Test]
public void TestApplyStarQueries()
{
const string query = "stars<4 easy";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("easy", filterCriteria.SearchText.Trim());
Assert.AreEqual(1, filterCriteria.SearchTerms.Length);
Assert.IsNotNull(filterCriteria.StarDifficulty.Max);
Assert.Greater(filterCriteria.StarDifficulty.Max, 3.99d);
Assert.Less(filterCriteria.StarDifficulty.Max, 4.00d);
Assert.IsNull(filterCriteria.StarDifficulty.Min);
}
[Test]
public void TestApplyApproachRateQueries()
{
const string query = "ar>=9 difficult";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("difficult", filterCriteria.SearchText.Trim());
Assert.AreEqual(1, filterCriteria.SearchTerms.Length);
Assert.IsNotNull(filterCriteria.ApproachRate.Min);
Assert.Greater(filterCriteria.ApproachRate.Min, 8.9f);
Assert.Less(filterCriteria.ApproachRate.Min, 9.0f);
Assert.IsNull(filterCriteria.ApproachRate.Max);
}
[Test]
public void TestApplyDrainRateQueriesByDrKeyword()
{
const string query = "dr>2 quite specific dr<:6";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("quite specific", filterCriteria.SearchText.Trim());
Assert.AreEqual(2, filterCriteria.SearchTerms.Length);
Assert.Greater(filterCriteria.DrainRate.Min, 2.0f);
Assert.Less(filterCriteria.DrainRate.Min, 2.1f);
Assert.Greater(filterCriteria.DrainRate.Max, 6.0f);
Assert.Less(filterCriteria.DrainRate.Min, 6.1f);
}
[Test]
public void TestApplyDrainRateQueriesByHpKeyword()
{
const string query = "hp>2 quite specific hp<=6";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("quite specific", filterCriteria.SearchText.Trim());
Assert.AreEqual(2, filterCriteria.SearchTerms.Length);
Assert.Greater(filterCriteria.DrainRate.Min, 2.0f);
Assert.Less(filterCriteria.DrainRate.Min, 2.1f);
Assert.Greater(filterCriteria.DrainRate.Max, 6.0f);
Assert.Less(filterCriteria.DrainRate.Min, 6.1f);
}
[Test]
public void TestApplyBPMQueries()
{
const string query = "bpm>:200 gotta go fast";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("gotta go fast", filterCriteria.SearchText.Trim());
Assert.AreEqual(3, filterCriteria.SearchTerms.Length);
Assert.IsNotNull(filterCriteria.BPM.Min);
Assert.Greater(filterCriteria.BPM.Min, 199.99d);
Assert.Less(filterCriteria.BPM.Min, 200.00d);
Assert.IsNull(filterCriteria.BPM.Max);
}
private static readonly object[] length_query_examples =
{
new object[] { "6ms", TimeSpan.FromMilliseconds(6), TimeSpan.FromMilliseconds(1) },
new object[] { "23s", TimeSpan.FromSeconds(23), TimeSpan.FromSeconds(1) },
new object[] { "9m", TimeSpan.FromMinutes(9), TimeSpan.FromMinutes(1) },
new object[] { "0.25h", TimeSpan.FromHours(0.25), TimeSpan.FromHours(1) },
new object[] { "70", TimeSpan.FromSeconds(70), TimeSpan.FromSeconds(1) },
};
[Test]
[TestCaseSource(nameof(length_query_examples))]
public void TestApplyLengthQueries(string lengthQuery, TimeSpan expectedLength, TimeSpan scale)
{
string query = $"length={lengthQuery} time";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("time", filterCriteria.SearchText.Trim());
Assert.AreEqual(1, filterCriteria.SearchTerms.Length);
Assert.AreEqual(expectedLength.TotalMilliseconds - scale.TotalMilliseconds / 2.0, filterCriteria.Length.Min);
Assert.AreEqual(expectedLength.TotalMilliseconds + scale.TotalMilliseconds / 2.0, filterCriteria.Length.Max);
}
[Test]
public void TestApplyDivisorQueries()
{
const string query = "that's a time signature alright! divisor:12";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("that's a time signature alright!", filterCriteria.SearchText.Trim());
Assert.AreEqual(5, filterCriteria.SearchTerms.Length);
Assert.AreEqual(12, filterCriteria.BeatDivisor.Min);
Assert.IsTrue(filterCriteria.BeatDivisor.IsLowerInclusive);
Assert.AreEqual(12, filterCriteria.BeatDivisor.Max);
Assert.IsTrue(filterCriteria.BeatDivisor.IsUpperInclusive);
}
[Test]
public void TestApplyStatusQueries()
{
const string query = "I want the pp status=ranked";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("I want the pp", filterCriteria.SearchText.Trim());
Assert.AreEqual(4, filterCriteria.SearchTerms.Length);
Assert.AreEqual(BeatmapSetOnlineStatus.Ranked, filterCriteria.OnlineStatus.Min);
Assert.IsTrue(filterCriteria.OnlineStatus.IsLowerInclusive);
Assert.AreEqual(BeatmapSetOnlineStatus.Ranked, filterCriteria.OnlineStatus.Max);
Assert.IsTrue(filterCriteria.OnlineStatus.IsUpperInclusive);
}
[Test]
public void TestApplyCreatorQueries()
{
const string query = "beatmap specifically by creator=my_fav";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("beatmap specifically by", filterCriteria.SearchText.Trim());
Assert.AreEqual(3, filterCriteria.SearchTerms.Length);
Assert.AreEqual("my_fav", filterCriteria.Creator.SearchTerm);
}
[Test]
public void TestApplyArtistQueries()
{
const string query = "find me songs by artist=singer please";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("find me songs by please", filterCriteria.SearchText.Trim());
Assert.AreEqual(5, filterCriteria.SearchTerms.Length);
Assert.AreEqual("singer", filterCriteria.Artist.SearchTerm);
}
[Test]
public void TestApplyArtistQueriesWithSpaces()
{
const string query = "really like artist=\"name with space\" yes";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("really like yes", filterCriteria.SearchText.Trim());
Assert.AreEqual(3, filterCriteria.SearchTerms.Length);
Assert.AreEqual("name with space", filterCriteria.Artist.SearchTerm);
}
[Test]
public void TestApplyArtistQueriesOneDoubleQuote()
{
const string query = "weird artist=double\"quote";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("weird", filterCriteria.SearchText.Trim());
Assert.AreEqual(1, filterCriteria.SearchTerms.Length);
Assert.AreEqual("double\"quote", filterCriteria.Artist.SearchTerm);
}
[Test]
public void TestOperatorParsing()
{
const string query = "artist=><something";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("><something", filterCriteria.Artist.SearchTerm);
}
[Test]
public void TestUnrecognisedKeywordIsIgnored()
{
const string query = "unrecognised=keyword";
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("unrecognised=keyword", filterCriteria.SearchText);
}
[TestCase("cs=nope")]
[TestCase("bpm>=bad")]
[TestCase("divisor<nah")]
[TestCase("status=noidea")]
public void TestInvalidKeywordValueIsIgnored(string query)
{
var filterCriteria = new FilterCriteria();
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual(query, filterCriteria.SearchText);
}
[Test]
public void TestCustomKeywordIsParsed()
{
var customCriteria = new CustomFilterCriteria();
const string query = "custom=readme unrecognised=keyword";
var filterCriteria = new FilterCriteria { RulesetCriteria = customCriteria };
FilterQueryParser.ApplyQueries(filterCriteria, query);
Assert.AreEqual("readme", customCriteria.CustomValue);
Assert.AreEqual("unrecognised=keyword", filterCriteria.SearchText.Trim());
}
private class CustomFilterCriteria : IRulesetFilterCriteria
{
public string CustomValue { get; set; }
public bool Matches(BeatmapInfo beatmap) => true;
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
if (key == "custom" && op == Operator.Equal)
{
CustomValue = value;
return true;
}
return false;
}
}
}
}
| 45.760618 | 122 | 0.622933 | [
"MIT"
] | Aleeeesz/osu | osu.Game.Tests/NonVisual/Filtering/FilterQueryParserTest.cs | 11,596 | C# |
/*
* Original author: Max Horowitz-Gelb <maxhg .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2016 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Threading;
using pwiz.Common.DataAnalysis;
namespace pwiz.Skyline.Model.RetentionTimes
{
public class LoessAligner : Aligner
{
private double _maxX;
private double _minX;
private double _maxY;
private double _minY;
private double _rmsd;
private double[] _xArr;
private double[] _yArrSmoothed;
private double[] _yArrOrig;
private double[] _reverseXArr;
private double[] _reverseYArr;
private readonly double _bandwidth;
private readonly int _robustIters;
public LoessAligner(int origXFileIndex, int origYFileIndex,
double bandwidth = LoessInterpolator.DEFAULT_BANDWIDTH, int robustIters = LoessInterpolator.DEFAULT_ROBUSTNESS_ITERS)
: base(origXFileIndex, origYFileIndex)
{
_bandwidth = bandwidth;
_robustIters = robustIters;
}
public LoessAligner(double bandwidth = LoessInterpolator.DEFAULT_BANDWIDTH, int robustIters = LoessInterpolator.DEFAULT_ROBUSTNESS_ITERS)
{
_bandwidth = bandwidth;
_robustIters = robustIters;
}
public override void Train(double[] xArr, double[] yArr, CancellationToken token)
{
//Calculate lowess
Array.Sort(xArr, yArr);
double[] lowessArr;
if (xArr.Length > 2)
{
LoessInterpolator interpolator = new LoessInterpolator(Math.Max(_bandwidth, 2.0 / xArr.Length), _robustIters);
lowessArr = interpolator.Smooth(xArr, yArr, token);
}
else
{
lowessArr = yArr;
}
_minX = xArr[0];
_maxX = xArr[xArr.Length - 1];
_minY = lowessArr.Min();
_maxY = lowessArr.Max();
_xArr = xArr;
_yArrOrig = yArr;
_yArrSmoothed = lowessArr;
var sum = 0.0;
for (int i = 0; i < _yArrOrig.Length; i++)
{
var e = _yArrOrig[i] - lowessArr[i];
sum += (e * e)/_yArrOrig.Length;
}
_rmsd = Math.Sqrt(sum);
if (CanCalculateReverseRegression)
{
//We must copy arrays and sort twice since
//X and Y arrays are not necessarily monotonically increasing
_reverseXArr = new double[_xArr.Length];
_reverseYArr = new double[_yArrSmoothed.Length];
Array.Copy(_xArr, _reverseYArr, _xArr.Length);
Array.Copy(_yArrSmoothed, _reverseXArr, _yArrSmoothed.Length);
Array.Sort(_reverseXArr, _reverseYArr);
}
}
public override double GetValue(double x)
{
return GetValueFor(_xArr, _yArrSmoothed, x, _minX, _maxX);
}
public override double GetValueReversed(double y)
{
return GetValueFor(_reverseXArr, _reverseYArr, y, _minY, _maxY);
}
private double GetValueFor(double[] indArr, double[] depArr, double value, double min, double max)
{
if (value < min)
{
return GetValueForExtremeLeft(indArr, depArr, value, min);
}
else if (value > max)
{
return GetValueForExtremeRight(indArr, depArr, value, max);
}
else
{
var adjacent = GetAdjacentIndex(value, indArr, 0, indArr.Length);
if (value == indArr[adjacent])
{
return depArr[adjacent];
}
else if (value < indArr[adjacent])
{
var left = adjacent - 1;
while (indArr[adjacent] == indArr[left])
{
left--;
if (left < 0)
{
break;
}
}
if (left < 0)
{
return GetValueForExtremeLeft(indArr, depArr, value, min);
}
return interpolate(indArr[left], depArr[left], indArr[adjacent], depArr[adjacent],
value);
}
else
{
var right = adjacent + 1;
while (indArr[adjacent] == indArr[right])
{
right++;
if (right >= indArr.Length)
break;
}
if (right >= indArr.Length)
{
return GetValueForExtremeRight(indArr,depArr,value,max);
}
return interpolate(indArr[adjacent], depArr[adjacent], indArr[right], depArr[right],
value);
}
}
}
private static double GetValueForExtremeLeft(double[] indArr, double[] depArr, double value, double min)
{
var slope = -1.0;
for (var i = 1; i < indArr.Length && slope < 0; i ++)
{
if (indArr[i] == min)
{
continue;
}
slope = (depArr[i] - depArr[0])/(indArr[i] - min);
}
return depArr[0] - slope*(min - value);
}
private static double GetValueForExtremeRight(double[] indArr, double[] depArr, double value, double max)
{
var slope = -1.0;
for (int i = indArr.Length - 2; i >= 0 && slope < 0; i --)
{
if (indArr[i] == max)
{
continue;
}
slope = (depArr[depArr.Length - 1] - depArr[i])/(max - indArr[i]);
}
return depArr[depArr.Length - 1] + slope*(value - max);
}
private double interpolate(double lx, double ly, double rx, double ry, double x)
{
return ly + (x - lx)*(ry - ly)/(rx - lx);
}
private int GetAdjacentIndex(double value, double[] arr, int start, int length)
{
if (length <= 2)
{
return start;
}
else
{
int mid = start + length/2;
if (value == arr[mid])
{
return mid;
}
else if (value > arr[mid])
{
return GetAdjacentIndex(value, arr, mid + 1, length - length/2 - 1);
}
else
{
return GetAdjacentIndex(value, arr, start, length/2);
}
}
}
public override double GetRmsd()
{
return _rmsd;
}
public override void GetSmoothedValues(out double[] xArr, out double[] yArr)
{
xArr = _xArr;
yArr = _yArrSmoothed;
}
}
} | 34.133333 | 146 | 0.476318 | [
"Apache-2.0"
] | vagisha/pwiz | pwiz_tools/Skyline/Model/RetentionTimes/LoessAligner.cs | 8,194 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// This class represents the Ole Automation binder.
// #define DISPLAY_DEBUG_INFO
namespace System {
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using CultureInfo = System.Globalization.CultureInfo;
// Made serializable in anticipation of this class eventually having state.
[Serializable]
internal class OleAutBinder : DefaultBinder
{
// ChangeType
// This binder uses OLEAUT to change the type of the variant.
[System.Security.SecuritySafeCritical] // overrides transparent member
public override Object ChangeType(Object value, Type type, CultureInfo cultureInfo)
{
Variant myValue = new Variant(value);
if (cultureInfo == null)
cultureInfo = CultureInfo.CurrentCulture;
#if DISPLAY_DEBUG_INFO
Console.WriteLine("In OleAutBinder::ChangeType converting variant of type: {0} to type: {1}", myValue.VariantType, type.Name);
#endif
if (type.IsByRef)
{
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Stripping byref from the type to convert to.");
#endif
type = type.GetElementType();
}
// If we are trying to convert from an object to another type then we don't
// need the OLEAUT change type, we can just use the normal COM+ mechanisms.
if (!type.IsPrimitive && type.IsInstanceOfType(value))
{
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Source variant can be assigned to destination type");
#endif
return value;
}
Type srcType = value.GetType();
// Handle converting primitives to enums.
if (type.IsEnum && srcType.IsPrimitive)
{
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Converting primitive to enum");
#endif
return Enum.Parse(type, value.ToString());
}
#if !FEATURE_CORECLR
// Special case the convertion from DBNull.
if (srcType == typeof(DBNull))
{
// The requested type is a DBNull so no convertion is required.
if (type == typeof(DBNull))
return value;
// Visual J++ supported converting from DBNull to null so customers
// have requested (via a CDCR) that DBNull be convertible to null.
// We don't however allow this when converting to a value class, since null
// doesn't make sense for these, or to object since this would change existing
// semantics.
if ((type.IsClass && type != typeof(Object)) || type.IsInterface)
return null;
}
#endif //!FEATURE_CORECLR
// Use the OA variant lib to convert primitive types.
try
{
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Using OAVariantLib.ChangeType() to do the conversion");
#endif
// Specify the LocalBool flag to have BOOL values converted to local language rather
// than 0 or -1.
Object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject();
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Object returned from ChangeType is of type: " + RetObj.GetType().Name);
#endif
return RetObj;
}
#if DISPLAY_DEBUG_INFO
catch(NotSupportedException e)
#else
catch(NotSupportedException)
#endif
{
#if DISPLAY_DEBUG_INFO
Console.Write("Exception thrown: ");
Console.WriteLine(e);
#endif
throw new COMException(Environment.GetResourceString("Interop.COM_TypeMismatch"), unchecked((int)0x80020005));
}
}
}
}
| 36.269565 | 138 | 0.576361 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/clr/src/BCL/system/oleautbinder.cs | 4,171 | C# |
using MVCProject.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MVCProject.View
{
public partial class frmPrincipal : Form
{
public frmPrincipal()
{
InitializeComponent();
if (Session.user == null)
throw new Exception("O computador vai se auto-destruir em 5 segundos.");
}
private void UsuáriosToolStripMenuItem_Click(object sender, EventArgs e)
{
frmUsuarios formUsuarios = new frmUsuarios();
formUsuarios.ShowDialog();
}
private void AutorToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAutores formAutores = new frmAutores();
formAutores.ShowDialog();
}
private void GeneroToolStripMenuItem_Click(object sender, EventArgs e)
{
frmGeneros formGeneros = new frmGeneros();
formGeneros.ShowDialog();
}
private void LivrosToolStripMenuItem_Click(object sender, EventArgs e)
{
frmLivros formLivros = new frmLivros();
formLivros.ShowDialog();
}
private void LocaçõesToolStripMenuItem_Click(object sender, EventArgs e)
{
frmLocacoes formLocacoes = new frmLocacoes();
formLocacoes.ShowDialog();
}
private void EditorasToolStripMenuItem_Click(object sender, EventArgs e)
{
frmEditoras formEditoras = new frmEditoras();
formEditoras.ShowDialog();
}
}
}
| 28.04918 | 88 | 0.630041 | [
"MIT"
] | DrGabenator/GitC | 29-07_02-08/MVCProject/MVCProject/View/frmPrincipal.cs | 1,716 | C# |
using Autofac;
using AutofacContrib.NSubstitute;
using AutoFixture;
using NSubstitute;
using NSubstitute.Extensions;
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using WWTWebservices;
using Xunit;
namespace WWT.Providers.Tests
{
public class DSSTests
{
private readonly Fixture _fixture;
public DSSTests()
{
_fixture = new Fixture();
}
[Theory]
[InlineData(13)]
public void TooLarge(int level)
{
// Arrange
using var container = AutoSubstitute.Configure()
.InitializeHttpWrappers()
.ConfigureParameters(a => a.Add("Q", $"{level},2,3"))
.Build();
// Act
container.Resolve<DSSProvider>().Run(container.Resolve<IWwtContext>());
// Assert
container.Resolve<HttpResponseBase>().Received(1).Write("No image");
}
[Theory]
[InlineData(7)]
[InlineData(0)]
public void LowLevels(int level)
{
// Arrange
var x = _fixture.Create<int>();
var y = _fixture.Create<int>();
var options = _fixture.Create<DSSOptions>();
using var container = AutoSubstitute.Configure()
.InitializeHttpWrappers()
.Provide(options)
.ConfigureParameters(a => a.Add("Q", $"{level},{x},{y}"))
.Build();
var data = _fixture.CreateMany<byte>(10);
var result = new MemoryStream(data.ToArray());
var outputStream = new MemoryStream();
container.Resolve<HttpResponseBase>().Configure().OutputStream.Returns(outputStream);
container.Resolve<IPlateTilePyramid>().GetStream(options.WwtTilesDir, "dssterrapixel.plate", level, x, y).Returns(result);
// Act
container.Resolve<DSSProvider>().Run(container.Resolve<IWwtContext>());
// Assert
Assert.Equal("image/png", container.Resolve<HttpResponseBase>().ContentType);
Assert.Equal(data, outputStream.ToArray());
}
[Theory]
[InlineData(8, 1, 2, 0, 0, 3, 1, 2)]
[InlineData(9, 3, 3, 0, 0, 4, 3, 3)]
[InlineData(10, 6, 3, 0, 0, 5, 6, 3)]
[InlineData(11, 1, 3, 0, 0, 6, 1, 3)]
public void HighLevels(int level, int x, int y, int fileX, int fileY, int level2, int x2, int y2)
{
// Arrange
var options = _fixture.Create<DSSOptions>();
using var container = AutoSubstitute.Configure()
.InitializeHttpWrappers()
.Provide(options)
.ConfigureParameters(a => a.Add("Q", $"{level},{x},{y}"))
.Build();
var data = _fixture.CreateMany<byte>(10);
var result = new MemoryStream(data.ToArray());
var outputStream = new MemoryStream();
var filename = $"DSSpngL5to12_x{fileX}_y{fileY}.plate";
container.Resolve<HttpResponseBase>().Configure().OutputStream.Returns(outputStream);
container.Resolve<IPlateTilePyramid>().GetStream(options.DssTerapixelDir, filename, level2, x2, y2).Returns(result);
// Act
container.Resolve<DSSProvider>().Run(container.Resolve<IWwtContext>());
// Assert
//Assert.Equal("image/png", container.Resolve<HttpResponseBase>().ContentType);
Assert.Equal(data, outputStream.ToArray());
}
}
}
| 33.700935 | 134 | 0.573211 | [
"MIT"
] | twsouthwick/wwt-website | tests/WWT.Providers.Tests/DSSTests.cs | 3,606 | C# |
using Machine.Specifications;
namespace Elders.Cronus.Tests.MessageStreaming
{
[Subject("")]
public class When__MessageStream__has_subscription_which_fails_to_handle_a_message
{
//Establish context = () =>
// {
// handlerFacotry = new CalculatorHandlerFactory();
// var messageHandlerMiddleware = new MessageHandlerMiddleware(handlerFacotry);
// messageHandlerMiddleware.ActualHandle = new DynamicMessageHandle();
// var messageSubscriptionMiddleware = new MessageSubscriptionsMiddleware();
// messageStream = new CronusMessageProcessorMiddleware("test", messageSubscriptionMiddleware);
// var subscription1 = new TestSubscriber(typeof(CalculatorNumber2), typeof(StandardCalculatorSubstractHandler), messageHandlerMiddleware);
// var subscription2 = new TestSubscriber(typeof(CalculatorNumber2), typeof(CalculatorHandler_ThrowsException), messageHandlerMiddleware);
// messages = new List<CronusMessage>();
// for (int i = 1; i < numberOfMessages + 1; i++)
// {
// messages.Add(new CronusMessage(new Message(new CalculatorNumber2(i))));
// }
// messageSubscriptionMiddleware.Subscribe(subscription1);
// messageSubscriptionMiddleware.Subscribe(subscription2);
// };
//Because of = () =>
// {
// feedResult = messageStream.Run(messages);
// };
It should_feed_interested_handlers; //= () => handlerFacotry.State.Total.ShouldEqual(Enumerable.Range(1, numberOfMessages).Sum() * -1);
It should_report_about_all_errors;//= () => feedResult.FailedMessages.ToList().ForEach(x => x.Errors.ForEach(e => e.Origin.Type.ShouldEqual("handler")));
//static IFeedResult feedResult;
//static int numberOfMessages = 3;
//static CronusMessageProcessorMiddleware messageStream;
//static List<CronusMessage> messages;
//static CalculatorHandlerFactory handlerFacotry;
}
}
| 47.111111 | 161 | 0.650472 | [
"Apache-2.0"
] | mynkow/Cronus | src/Elders.Cronus.Tests/MessageStreaming/When__MessageStream__has_subscription_which_fails_to_handle_a_message.cs | 2,120 | C# |
using Sandbox.Game.Entities;
using System;
using VRage.Game.Entity;
using VRageMath;
using WeaponCore.Support;
using System.Collections.Generic;
using static WeaponCore.Support.WeaponComponent.Start;
using static WeaponCore.Support.WeaponComponent.BlockType;
using static WeaponCore.Platform.Weapon;
namespace WeaponCore.Platform
{
public class MyWeaponPlatform
{
internal readonly RecursiveSubparts Parts = new RecursiveSubparts();
internal readonly MySoundPair RotationSound = new MySoundPair();
internal Weapon[] Weapons = new Weapon[1];
internal WeaponStructure Structure;
internal WeaponComponent Comp;
internal PlatformState State;
internal enum PlatformState
{
Fresh,
Invalid,
Delay,
Valid,
Inited,
Ready,
}
internal void Setup(WeaponComponent comp)
{
if (!comp.Session.WeaponPlatforms.ContainsKey(comp.SubtypeHash))
{
Log.Line($"Your block subTypeId ({comp.MyCube.BlockDefinition.Id.SubtypeId.String}) was not found in platform setup, I am crashing now Dave.");
return;
}
Structure = comp.Session.WeaponPlatforms[comp.SubtypeHash];
Comp = comp;
if (Weapons.Length != Structure.MuzzlePartNames.Length)
Array.Resize(ref Weapons, Structure.MuzzlePartNames.Length);
}
internal void Clean()
{
for (int i = 0; i < Weapons.Length; i++) Weapons[i] = null;
Parts.Clean(Comp.MyCube);
Structure = null;
State = PlatformState.Fresh;
Comp = null;
}
internal PlatformState Init(WeaponComponent comp)
{
if (comp.MyCube.MarkedForClose || comp.MyCube.CubeGrid.MarkedForClose)
{
State = PlatformState.Invalid;
Log.Line("closed, init platform invalid, I am crashing now Dave.");
return State;
}
if (!comp.MyCube.IsFunctional)
{
State = PlatformState.Delay;
return State;
}
var wCounter = comp.Ai.WeaponCounter[comp.SubtypeHash];
wCounter.Max = Structure.GridWeaponCap;
if (wCounter.Max > 0)
{
if (wCounter.Current + 1 <= wCounter.Max)
{
wCounter.Current++;
State = PlatformState.Valid;
}
else
{
State = PlatformState.Invalid;
Log.Line("init platform invalid, I am crashing now Dave.");
return State;
}
}
else
State = PlatformState.Valid;
Parts.Entity = comp.Entity as MyEntity;
return GetParts(comp);
}
private PlatformState GetParts(WeaponComponent comp)
{
Parts.CheckSubparts();
for (int i = 0; i < Structure.MuzzlePartNames.Length; i++)
{
var muzzlePartHash = Structure.MuzzlePartNames[i];
var barrelCount = Structure.WeaponSystems[muzzlePartHash].Barrels.Length;
WeaponSystem system;
if (!Structure.WeaponSystems.TryGetValue(muzzlePartHash, out system))
{
Log.Line($"Invalid weapon system, I am crashing now Dave.");
State = PlatformState.Invalid;
return State;
}
var wepAnimationSet = comp.Session.CreateWeaponAnimationSet(system, Parts);
var muzzlePartName = muzzlePartHash.String != "Designator" ? muzzlePartHash.String : system.ElevationPartName.String;
MyEntity muzzlePartEntity;
if (!Parts.NameToEntity.TryGetValue(muzzlePartName, out muzzlePartEntity))
{
Log.Line($"Invalid barrelPart, I am crashing now Dave.");
State = PlatformState.Invalid;
return State;
}
foreach (var part in Parts.NameToEntity)
{
part.Value.OnClose += comp.SubpartClosed;
break;
}
//compatability with old configs of converted turrets
var azimuthPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(system.AzimuthPartName.String) ? "MissileTurretBase1" : system.AzimuthPartName.String : system.AzimuthPartName.String;
var elevationPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(system.ElevationPartName.String) ? "MissileTurretBarrels" : system.ElevationPartName.String : system.ElevationPartName.String;
MyEntity azimuthPart = null;
if (!Parts.NameToEntity.TryGetValue(azimuthPartName, out azimuthPart))
{
Log.Line($"Invalid azimuthPart, I am crashing now Dave.");
State = PlatformState.Invalid;
return State;
}
MyEntity elevationPart = null;
if (!Parts.NameToEntity.TryGetValue(elevationPartName, out elevationPart))
{
Log.Line($"Invalid elevationPart, I am crashing now Dave.");
State = PlatformState.Invalid;
return State;
}
foreach (var triggerSet in wepAnimationSet)
for(int j = 0; j < triggerSet.Value.Length; j++)
comp.AllAnimations.Add(triggerSet.Value[j]);
Weapons[i] = new Weapon(muzzlePartEntity, system, i, comp, wepAnimationSet)
{
Muzzles = new Muzzle[barrelCount],
Dummies = new Dummy[barrelCount],
AzimuthPart = new PartInfo { Entity = azimuthPart },
ElevationPart = new PartInfo { Entity = elevationPart },
AzimuthOnBase = azimuthPart.Parent == comp.MyCube,
AiOnlyWeapon = comp.BaseType != Turret || (azimuthPartName != "MissileTurretBase1" && elevationPartName != "MissileTurretBarrels" && azimuthPartName != "InteriorTurretBase1" && elevationPartName != "InteriorTurretBase2" && azimuthPartName != "GatlingTurretBase1" && elevationPartName != "GatlingTurretBase2")
};
var weapon = Weapons[i];
SetupUi(weapon);
if (!comp.Debug && weapon.System.Values.HardPoint.Other.Debug)
comp.Debug = true;
if (weapon.System.Values.HardPoint.Ai.TurretController)
{
if (weapon.System.Values.HardPoint.Ai.PrimaryTracking && comp.TrackingWeapon == null)
comp.TrackingWeapon = weapon;
if (weapon.AvCapable && weapon.System.HardPointRotationSound)
RotationSound.Init(weapon.System.Values.HardPoint.Audio.HardPointRotationSound, false);
}
}
CompileTurret(comp);
State = PlatformState.Inited;
return State;
}
private void CompileTurret(WeaponComponent comp, bool reset = false)
{
var c = 0;
foreach (var m in Structure.WeaponSystems)
{
MyEntity muzzlePart = null;
if (Parts.NameToEntity.TryGetValue(m.Key.String, out muzzlePart) || m.Value.DesignatorWeapon)
{
var azimuthPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(m.Value.AzimuthPartName.String) ? "MissileTurretBase1" : m.Value.AzimuthPartName.String : m.Value.AzimuthPartName.String;
var elevationPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(m.Value.ElevationPartName.String) ? "MissileTurretBarrels" : m.Value.ElevationPartName.String : m.Value.ElevationPartName.String;
var weapon = Weapons[c];
var muzzlePartName = m.Key.String;
if (m.Value.DesignatorWeapon)
{
muzzlePart = weapon.ElevationPart.Entity;
muzzlePartName = elevationPartName;
}
weapon.MuzzlePart.Entity = muzzlePart;
weapon.HeatingParts = new List<MyEntity> {weapon.MuzzlePart.Entity};
if (muzzlePartName != "None")
{
var muzzlePartLocation = comp.Session.GetPartLocation("subpart_" + muzzlePartName, muzzlePart.Parent.Model);
var muzzlePartPosTo = Matrix.CreateTranslation(-muzzlePartLocation);
var muzzlePartPosFrom = Matrix.CreateTranslation(muzzlePartLocation);
weapon.MuzzlePart.ToTransformation = muzzlePartPosTo;
weapon.MuzzlePart.FromTransformation = muzzlePartPosFrom;
weapon.MuzzlePart.PartLocalLocation = muzzlePartLocation;
}
if (weapon.AiOnlyWeapon)
{
var azimuthPart = weapon.AzimuthPart.Entity;
var elevationPart = weapon.ElevationPart.Entity;
if (azimuthPart != null && azimuthPartName != "None" && weapon.System.TurretMovement != WeaponSystem.TurretType.ElevationOnly)
{
var azimuthPartLocation = comp.Session.GetPartLocation("subpart_" + azimuthPartName, azimuthPart.Parent.Model);
var partDummy = comp.Session.GetPartDummy("subpart_" + azimuthPartName, azimuthPart.Parent.Model);
var azPartPosTo = Matrix.CreateTranslation(-azimuthPartLocation);
var azPrtPosFrom = Matrix.CreateTranslation(azimuthPartLocation);
var fullStepAzRotation = azPartPosTo * MatrixD.CreateFromAxisAngle(partDummy.Matrix.Up, - m.Value.AzStep) * azPrtPosFrom;
var rFullStepAzRotation = Matrix.Invert(fullStepAzRotation);
weapon.AzimuthPart.RotationAxis = partDummy.Matrix.Up;
weapon.AzimuthPart.ToTransformation = azPartPosTo;
weapon.AzimuthPart.FromTransformation = azPrtPosFrom;
weapon.AzimuthPart.FullRotationStep = fullStepAzRotation;
weapon.AzimuthPart.RevFullRotationStep = rFullStepAzRotation;
weapon.AzimuthPart.PartLocalLocation = azimuthPartLocation;
}
else
{
weapon.AzimuthPart.RotationAxis = Vector3.Zero;
weapon.AzimuthPart.ToTransformation = Matrix.Zero;
weapon.AzimuthPart.FromTransformation = Matrix.Zero;
weapon.AzimuthPart.FullRotationStep = Matrix.Zero;
weapon.AzimuthPart.RevFullRotationStep = Matrix.Zero;
weapon.AzimuthPart.PartLocalLocation = Vector3.Zero;
}
if (elevationPart != null && elevationPartName != "None" && weapon.System.TurretMovement != WeaponSystem.TurretType.AzimuthOnly)
{
var elevationPartLocation = comp.Session.GetPartLocation("subpart_" + elevationPartName, elevationPart.Parent.Model);
var partDummy = comp.Session.GetPartDummy("subpart_" + elevationPartName, elevationPart.Parent.Model);
var elPartPosTo = Matrix.CreateTranslation(-elevationPartLocation);
var elPartPosFrom = Matrix.CreateTranslation(elevationPartLocation);
var fullStepElRotation = elPartPosTo * MatrixD.CreateFromAxisAngle(partDummy.Matrix.Left, m.Value.ElStep) * elPartPosFrom;
var rFullStepElRotation = Matrix.Invert(fullStepElRotation);
weapon.ElevationPart.RotationAxis = partDummy.Matrix.Left;
weapon.ElevationPart.ToTransformation = elPartPosTo;
weapon.ElevationPart.FromTransformation = elPartPosFrom;
weapon.ElevationPart.FullRotationStep = fullStepElRotation;
weapon.ElevationPart.RevFullRotationStep = rFullStepElRotation;
weapon.ElevationPart.PartLocalLocation = elevationPartLocation;
}
else if (elevationPartName == "None")
{
weapon.ElevationPart.RotationAxis = Vector3.Zero;
weapon.ElevationPart.ToTransformation = Matrix.Zero;
weapon.ElevationPart.FromTransformation = Matrix.Zero;
weapon.ElevationPart.FullRotationStep = Matrix.Zero;
weapon.ElevationPart.RevFullRotationStep = Matrix.Zero;
weapon.ElevationPart.PartLocalLocation = Vector3.Zero;
}
}
var barrelCount = m.Value.Barrels.Length;
if (m.Key.String != "Designator")
{
weapon.MuzzlePart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.MuzzlePart.Entity.OnMarkForClose += weapon.EntPartClose;
if (comp.Session.VanillaSubpartNames.Contains(weapon.System.AzimuthPartName.String) && comp.Session.VanillaSubpartNames.Contains(weapon.System.ElevationPartName.String))
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.UpdateParts;
}
else
{
if(weapon.ElevationPart.Entity != null)
{
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.ElevationPart.Entity.OnMarkForClose += weapon.EntPartClose;
if (comp.Session.VanillaSubpartNames.Contains(weapon.System.AzimuthPartName.String) && comp.Session.VanillaSubpartNames.Contains(weapon.System.ElevationPartName.String))
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.UpdateParts;
}
else
{
weapon.AzimuthPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.AzimuthPart.Entity.OnMarkForClose += weapon.EntPartClose;
}
}
for (int i = 0; i < barrelCount; i++)
{
var barrel = m.Value.Barrels[i];
weapon.MuzzleIdToName.Add(i, barrel);
if (weapon.Muzzles[i] == null)
{
weapon.Dummies[i] = new Dummy(weapon.MuzzlePart.Entity, barrel);
weapon.Muzzles[i] = new Muzzle(i);
}
else
weapon.Dummies[i].Entity = weapon.MuzzlePart.Entity;
}
for(int i = 0; i < m.Value.HeatingSubparts.Length; i++)
{
var partName = m.Value.HeatingSubparts[i];
MyEntity ent;
if (Parts.NameToEntity.TryGetValue(partName, out ent))
{
weapon.HeatingParts.Add(ent);
try
{
ent.SetEmissiveParts("Heating", Color.Transparent, 0);
}
catch (Exception ex) { Log.Line($"Exception no emmissive Found: {ex}"); }
}
}
//was run only on weapon first build, needs to run every reset as well
try
{
foreach (var emissive in weapon.System.WeaponEmissiveSet)
{
if (emissive.Value.EmissiveParts == null) continue;
foreach (var part in emissive.Value.EmissiveParts)
{
Parts.SetEmissiveParts(part, Color.Transparent, 0);
}
}
}
catch (Exception e)
{
//cant check for emissives so may be null ref
}
c++;
}
}
}
internal void ResetTurret(WeaponComponent comp)
{
var c = 0;
var registered = false;
foreach (var m in Structure.WeaponSystems)
{
MyEntity muzzlePart = null;
if (Parts.NameToEntity.TryGetValue(m.Key.String, out muzzlePart) || m.Value.DesignatorWeapon)
{
if (!registered)
{
Parts.NameToEntity.FirstPair().Value.OnClose += Comp.SubpartClosed;
registered = true;
}
var azimuthPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(m.Value.AzimuthPartName.String) ? "MissileTurretBase1" : m.Value.AzimuthPartName.String : m.Value.AzimuthPartName.String;
var elevationPartName = comp.BaseType == Turret ? string.IsNullOrEmpty(m.Value.ElevationPartName.String) ? "MissileTurretBarrels" : m.Value.ElevationPartName.String : m.Value.ElevationPartName.String;
var weapon = Weapons[c];
MyEntity azimuthPartEntity;
if (Parts.NameToEntity.TryGetValue(azimuthPartName, out azimuthPartEntity))
weapon.AzimuthPart.Entity = azimuthPartEntity;
MyEntity elevationPartEntity;
if (Parts.NameToEntity.TryGetValue(elevationPartName, out elevationPartEntity))
weapon.ElevationPart.Entity = elevationPartEntity;
if (m.Value.DesignatorWeapon)
muzzlePart = weapon.ElevationPart.Entity;
weapon.MuzzlePart.Entity = muzzlePart;
weapon.HeatingParts.Clear();
weapon.HeatingParts.Add(weapon.MuzzlePart.Entity);
foreach (var animationSet in weapon.AnimationsSet)
{
foreach (var animation in animationSet.Value)
{
MyEntity part;
if (Parts.NameToEntity.TryGetValue(animation.SubpartId, out part))
{
animation.Part = (MyEntitySubpart)part;
//if (animation.Running)
// animation.Paused = true;
animation.Reset();
}
}
}
if (m.Key.String != "Designator")
{
weapon.MuzzlePart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.MuzzlePart.Entity.OnMarkForClose += weapon.EntPartClose;
if(comp.Session.VanillaSubpartNames.Contains(weapon.System.AzimuthPartName.String) && comp.Session.VanillaSubpartNames.Contains(weapon.System.ElevationPartName.String))
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.UpdateParts;
}
else
{
if (weapon.ElevationPart.Entity != null)
{
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.ElevationPart.Entity.OnMarkForClose += weapon.EntPartClose;
if (comp.Session.VanillaSubpartNames.Contains(weapon.System.AzimuthPartName.String) && comp.Session.VanillaSubpartNames.Contains(weapon.System.ElevationPartName.String))
weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.UpdateParts;
}
else
{
weapon.AzimuthPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
weapon.AzimuthPart.Entity.OnMarkForClose += weapon.EntPartClose;
}
}
for (int i = 0; i < m.Value.Barrels.Length; i++)
weapon.Dummies[i].Entity = weapon.MuzzlePart.Entity;
for (int i = 0; i < m.Value.HeatingSubparts.Length; i++)
{
var partName = m.Value.HeatingSubparts[i];
MyEntity ent;
if (Parts.NameToEntity.TryGetValue(partName, out ent))
{
weapon.HeatingParts.Add(ent);
try
{
ent.SetEmissiveParts("Heating", Color.Transparent, 0);
}
catch (Exception ex) { Log.Line($"Exception no emmissive Found: {ex}"); }
}
}
//was run only on weapon first build, needs to run every reset as well
try
{
foreach (var emissive in weapon.System.WeaponEmissiveSet)
{
if (emissive.Value.EmissiveParts == null) continue;
foreach (var part in emissive.Value.EmissiveParts)
{
Parts.SetEmissiveParts(part, Color.Transparent, 0);
}
}
}
catch (Exception e)
{
//cant check for emissives so may be null ref
}
}
c++;
}
}
internal void ResetParts(WeaponComponent comp)
{
Parts.Clean(comp.Entity as MyEntity);
Parts.CheckSubparts();
ResetTurret(comp);
comp.Status = Started;
}
internal void RemoveParts(WeaponComponent comp)
{
foreach (var w in comp.Platform.Weapons)
{
if (w.MuzzlePart.Entity == null) continue;
w.MuzzlePart.Entity.PositionComp.OnPositionChanged -= w.PositionChanged;
}
Parts.Clean(comp.Entity as MyEntity);
comp.Status = Stopped;
}
internal void SetupUi(Weapon w)
{
//UI elements
w.Comp.HasGuidanceToggle = w.Comp.HasGuidanceToggle || w.System.Values.HardPoint.Ui.ToggleGuidance;
w.Comp.HasDamageSlider = w.Comp.HasDamageSlider || (!w.CanUseChargeAmmo && w.System.Values.HardPoint.Ui.DamageModifier && w.CanUseEnergyAmmo || w.CanUseHybridAmmo);
w.Comp.HasRofSlider = w.Comp.HasRofSlider || (w.System.Values.HardPoint.Ui.RateOfFire && !w.CanUseChargeAmmo);
w.Comp.CanOverload = w.Comp.CanOverload || (w.System.Values.HardPoint.Ui.EnableOverload && w.CanUseBeams && !w.CanUseChargeAmmo);
w.Comp.HasTurret = w.Comp.HasTurret || (w.System.Values.HardPoint.Ai.TurretAttached);
w.Comp.HasChargeWeapon = w.Comp.HasChargeWeapon || w.CanUseChargeAmmo;
}
}
}
| 47.8125 | 328 | 0.524632 | [
"MIT"
] | B4Rme/WeaponCore | Data/Scripts/WeaponCore/WeaponComp/PlatformInit.cs | 24,482 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Models
{
public class Sale
{
public Sale() { }
public Sale(short productId, string playerId)
{
ProductId = productId;
PlayerId = playerId;
}
public int SaleId { get; set; }
public short ProductId { get; set; }
public string PlayerId { get; set; }
public string TransactionId { get; set; }
public string TransactionType { get; set; }
public string PayerEmail { get; set; }
public string PaymentType { get; set; }
public string PaymentStatus { get; set; }
public decimal Price { get; set; }
public string Currency { get; set; }
public DateTime CreateDate { get; set; }
public virtual Product Product { get; set; }
public virtual Player Player { get; set; }
}
}
| 28.6875 | 53 | 0.588235 | [
"MIT"
] | RestoreMonarchy/Servers | Core/Models/Sale.cs | 920 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Luaan.Yggmire.OrleansInterfaces.Structures;
using Luaan.Yggmire.OrleansServer.Actors;
namespace Luaan.Yggmire.OrleansServer.Behaviours
{
[Serializable]
public class ItemStorageBehaviour : IItemBehaviour<ItemStorageBehaviourState>, IItemBehaviourWithActions
{
/// <summary>
/// Id used to pair the configured prototypes of the item with the actual stored state for that behaviour.
/// </summary>
public string Id { get; set; }
public bool IsContainer { get; set; }
public ItemAction[] GetAvailableActions(WorldItem parent)
{
if (IsContainer)
{
return new ItemAction[] { new ItemAction { Id = "open", Name = "Open" } };
}
return new ItemAction[] { };
}
public void ExecuteAction(/*WorldItem parentItem, /* ISessionGrain session, */string actionId)
{
if (IsContainer)
{
switch (actionId)
{
case "open":
{
// TODO: Hmm... what should this do and how? :D
break;
}
}
}
}
}
[Serializable]
public class ItemStorageBehaviourState : IItemBehaviourState
{
public string BehaviourId { get; set; }
public List<InventoryItem> Items { get; set; }
}
}
| 28.125 | 114 | 0.555556 | [
"MIT"
] | Luaancz/Yggmire | Server/Luaan.Yggmire.OrleansServer/Behaviours/ItemStorageBehaviour.cs | 1,577 | C# |
using System;
using System.Windows.Media;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using TARY_Library;
namespace hero
{
//說明:直線行走 使用身體撞擊當作攻擊
public class MONSTER1_A : MONSTER1
{
public MONSTER1_A(Vector2 loc)
: base(loc)
{
this.V = new TARY_VIMG(GamePage.picMONSTER1_A, loc);
V.CenterPoint = true;
}
public override void info()
{
//**父類別基礎屬性****
SCORE = 141;//擊倒分數
HP = 300;//怪物血量
ADD_X = 0;//物件位移
ADD_Y = 4;//物件位移
//*************
V.H.Radius -= 3;//縮減感應範圍
R_ADD = 0.5f;//選轉速度
}
public override void Event_Dead()
{
//當怪物要死之前..
base.Event_Dead();
this.firedRn(3);
}
}
}
| 19.652174 | 64 | 0.497788 | [
"MIT"
] | TaryHuang/FINAL-FIGHTER | hero/hero/hero/monster/MONSTER1_A.cs | 1,058 | C# |
// -------------------------------------------------------------------------
// Copyright © 2021 Province of British Columbia
//
// 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
//
// 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.
// -------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.Serialization;
using System.Security.Claims;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using AutoMapper;
using EMBC.ESS.Shared.Contracts.Submissions;
using EMBC.Registrants.API.Services;
using EMBC.Registrants.API.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace EMBC.Registrants.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class EvacuationsController : ControllerBase
{
private readonly IMessagingClient messagingClient;
private readonly IMapper mapper;
private readonly IEvacuationSearchService evacuationSearchService;
private string currentUserId => User.FindFirstValue(JwtRegisteredClaimNames.Sub);
public EvacuationsController(IMessagingClient messagingClient, IMapper mapper, IEvacuationSearchService evacuationSearchService)
{
this.messagingClient = messagingClient;
this.mapper = mapper;
this.evacuationSearchService = evacuationSearchService;
}
/// <summary>
/// Anonymously Create a Registrant Profile and Evacuation File
/// </summary>
/// <param name="registration">Anonymous registration form</param>
/// <returns>ESS number</returns>
[HttpPost("create-registration-anonymous")]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status200OK)]
[AllowAnonymous]
public async Task<ActionResult<RegistrationResult>> Create(AnonymousRegistration registration)
{
if (registration == null) return BadRequest();
var profile = mapper.Map<RegistrantProfile>(registration.RegistrationDetails);
//anonymous profiles are unverified and not authenticated
profile.AuthenticatedUser = false;
profile.VerifiedUser = false;
var file = mapper.Map<ESS.Shared.Contracts.Submissions.EvacuationFile>(registration.PreliminaryNeedsAssessment);
var id = await messagingClient.Send(new SubmitAnonymousEvacuationFileCommand
{
File = file,
SubmitterProfile = profile
});
return Ok(new RegistrationResult { ReferenceNumber = id });
}
/// <summary>
/// Get the currently logged in user's current list of evacuations
/// </summary>
/// <returns>List of EvacuationFile</returns>
[HttpGet("current")]
[ProducesResponseType(StatusCodes.Status200OK)]
[Authorize]
public async Task<ActionResult<IEnumerable<EvacuationFile>>> GetCurrentEvacuations()
{
var userId = currentUserId;
var files = await evacuationSearchService.GetFiles(userId,
new[] { ESS.Shared.Contracts.Submissions.EvacuationFileStatus.Active, ESS.Shared.Contracts.Submissions.EvacuationFileStatus.Pending, ESS.Shared.Contracts.Submissions.EvacuationFileStatus.Expired });
return Ok(mapper.Map<IEnumerable<EvacuationFile>>(files));
}
/// <summary>
/// Get the currently logged in user's past list of evacuations
/// </summary>
/// <returns>List of EvacuationFile</returns>
[HttpGet("past")]
[ProducesResponseType(StatusCodes.Status200OK)]
[Authorize]
public async Task<ActionResult<IEnumerable<EvacuationFile>>> GetPastEvacuations()
{
var userId = currentUserId;
var files = await evacuationSearchService.GetFiles(userId,
new[] { ESS.Shared.Contracts.Submissions.EvacuationFileStatus.Archived, ESS.Shared.Contracts.Submissions.EvacuationFileStatus.Completed });
return Ok(mapper.Map<IEnumerable<EvacuationFile>>(files));
}
/// <summary>
/// Create or update a verified Evacuation file
/// </summary>
/// <param name="evacuationFile">Evacuation data</param>
/// <returns>ESS number</returns>
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[Authorize]
public async Task<ActionResult<RegistrationResult>> UpsertEvacuationFile(EvacuationFile evacuationFile)
{
if (evacuationFile == null)
return BadRequest();
var userId = currentUserId;
var file = mapper.Map<ESS.Shared.Contracts.Submissions.EvacuationFile>(evacuationFile);
file.PrimaryRegistrantId = userId;
var fileId = await messagingClient.Send(new SubmitEvacuationFileCommand { File = file });
return Ok(new RegistrationResult { ReferenceNumber = fileId });
}
}
/// <summary>
/// Evacuation File
/// </summary>
public class EvacuationFile
{
public string FileId { get; set; }
public EvacuationFileStatus Status { get; set; }
public string EvacuationFileDate { get; set; }
public bool IsRestricted { get; set; }
[Required]
public Address EvacuatedFromAddress { get; set; }
[Required]
public NeedsAssessment NeedsAssessment { get; set; }
public string SecretPhrase { get; set; }
public bool SecretPhraseEdited { get; set; }
public DateTime LastModified { get; set; }
public IEnumerable<Support> Supports { get; set; } = Array.Empty<Support>();
public string PaperFileNumber { get; set; }
}
/// <summary>
/// Needs assessment form
/// </summary>
public class NeedsAssessment
{
public string Id { get; set; }
[Required]
public InsuranceOption Insurance { get; set; }
public bool? CanEvacueeProvideFood { get; set; }
public bool? CanEvacueeProvideLodging { get; set; }
public bool? CanEvacueeProvideClothing { get; set; }
public bool? CanEvacueeProvideTransportation { get; set; }
public bool? CanEvacueeProvideIncidentals { get; set; }
public bool HaveSpecialDiet { get; set; }
public string SpecialDietDetails { get; set; }
public bool HaveMedication { get; set; }
public IEnumerable<HouseholdMember> HouseholdMembers { get; set; } = Array.Empty<HouseholdMember>();
public IEnumerable<Pet> Pets { get; set; } = Array.Empty<Pet>();
public bool? HasPetsFood { get; set; }
public NeedsAssessmentType Type { get; set; }
}
/// <summary>
/// A member of the household in needs assessment
/// </summary>
public class HouseholdMember
{
public string Id { get; set; }
public bool IsPrimaryRegistrant { get; set; }
public PersonDetails Details { get; set; }
public bool IsUnder19 { get; set; }
}
/// <summary>
/// A pet in needs assessment
/// </summary>
public class Pet
{
public string Type { get; set; }
public string Quantity { get; set; }
}
/// <summary>
/// Registration form for anonymous registrants
/// </summary>
public class AnonymousRegistration
{
[Required]
public Profile RegistrationDetails { get; set; }
[Required]
public EvacuationFile PreliminaryNeedsAssessment { get; set; }
[Required]
public bool InformationCollectionConsent { get; set; }
[Required]
public string Captcha { get; set; }
}
/// <summary>
/// Reference number of a new registration submission
/// </summary>
public class RegistrationResult
{
public string ReferenceNumber { get; set; }
}
public enum EvacuationFileStatus
{
[EnumMember(Value = "Pending")]
Pending,
[EnumMember(Value = "Active")]
Active,
[EnumMember(Value = "Expired")]
Expired,
[EnumMember(Value = "Completed")]
Completed,
[EnumMember(Value = "Archived")]
Archived
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum InsuranceOption
{
[EnumMember(Value = "No")]
No,
[EnumMember(Value = "Yes")]
Yes,
[EnumMember(Value = "Unsure")]
Unsure,
[EnumMember(Value = "Unknown")]
Unknown
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NeedsAssessmentType
{
Preliminary,
Assessed
}
[KnownType(typeof(Referral))]
public abstract class Support
{
public string Id { get; set; }
public DateTime IssuedOn { get; set; }
public string IssuingMemberTeamName { get; set; }
public DateTime From { get; set; }
public DateTime To { get; set; }
public SupportStatus Status { get; set; }
public abstract SupportMethod Method { get; }
public abstract SupportCategory Category { get; }
public abstract SupportSubCategory SubCategory { get; }
public IEnumerable<string> IncludedHouseholdMembers { get; set; } = Array.Empty<string>();
}
[KnownType(typeof(ClothingReferral))]
[KnownType(typeof(IncidentalsReferral))]
[KnownType(typeof(FoodGroceriesReferral))]
[KnownType(typeof(FoodRestaurantReferral))]
[KnownType(typeof(FoodRestaurantReferral))]
[KnownType(typeof(LodgingBilletingReferral))]
[KnownType(typeof(LodgingGroupReferral))]
[KnownType(typeof(LodgingHotelReferral))]
[KnownType(typeof(TransportationOtherReferral))]
[KnownType(typeof(TransportationTaxiReferral))]
public abstract class Referral : Support
{
public override SupportMethod Method => SupportMethod.Referral;
public string SupplierId { get; set; }
public string SupplierName { get; set; }
public Address SupplierAddress { get; set; }
public string IssuedToPersonName { get; set; }
}
public class ClothingReferral : Referral
{
public bool ExtremeWinterConditions { get; set; }
public override SupportCategory Category => SupportCategory.Clothing;
public override SupportSubCategory SubCategory => SupportSubCategory.None;
[Range(0, double.MaxValue)]
public double TotalAmount { get; set; }
}
public class IncidentalsReferral : Referral
{
public override SupportCategory Category => SupportCategory.Incidentals;
public override SupportSubCategory SubCategory => SupportSubCategory.None;
public string ApprovedItems { get; set; }
[Range(0, double.MaxValue)]
public double TotalAmount { get; set; }
}
public class FoodGroceriesReferral : Referral
{
public override SupportCategory Category => SupportCategory.Food;
public override SupportSubCategory SubCategory => SupportSubCategory.Food_Groceries;
[Range(0, int.MaxValue)]
public int NumberOfDays { get; set; }
[Range(0, double.MaxValue)]
public double TotalAmount { get; set; }
}
public class FoodRestaurantReferral : Referral
{
public override SupportCategory Category => SupportCategory.Food;
public override SupportSubCategory SubCategory => SupportSubCategory.Food_Restaurant;
[Range(0, int.MaxValue)]
public int NumberOfBreakfastsPerPerson { get; set; }
[Range(0, int.MaxValue)]
public int NumberOfLunchesPerPerson { get; set; }
[Range(0, int.MaxValue)]
public int NumberOfDinnersPerPerson { get; set; }
[Range(0, double.MaxValue)]
public double TotalAmount { get; set; }
}
public class LodgingHotelReferral : Referral
{
public override SupportCategory Category => SupportCategory.Lodging;
public override SupportSubCategory SubCategory => SupportSubCategory.Lodging_Hotel;
[Range(0, int.MaxValue)]
public int NumberOfNights { get; set; }
[Range(0, int.MaxValue)]
public int NumberOfRooms { get; set; }
}
public class LodgingBilletingReferral : Referral
{
public override SupportCategory Category => SupportCategory.Lodging;
public override SupportSubCategory SubCategory => SupportSubCategory.Lodging_Billeting;
[Range(0, int.MaxValue)]
public int NumberOfNights { get; set; }
public string HostName { get; set; }
public string HostAddress { get; set; }
public string HostCity { get; set; }
public string HostEmail { get; set; }
public string HostPhone { get; set; }
}
public class LodgingGroupReferral : Referral
{
public override SupportCategory Category => SupportCategory.Lodging;
public override SupportSubCategory SubCategory => SupportSubCategory.Lodging_Group;
[Range(0, int.MaxValue)]
public int NumberOfNights { get; set; }
public string FacilityName { get; set; }
public string FacilityAddress { get; set; }
public string FacilityCity { get; set; }
public string FacilityCommunityCode { get; set; }
public string FacilityContactPhone { get; set; }
}
public class TransportationTaxiReferral : Referral
{
public override SupportCategory Category => SupportCategory.Transportation;
public override SupportSubCategory SubCategory => SupportSubCategory.Transportation_Taxi;
public string FromAddress { get; set; }
public string ToAddress { get; set; }
}
public class TransportationOtherReferral : Referral
{
public override SupportCategory Category => SupportCategory.Transportation;
public override SupportSubCategory SubCategory => SupportSubCategory.Transportation_Other;
[Range(0, double.MaxValue)]
public double TotalAmount { get; set; }
public string TransportMode { get; set; }
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportStatus
{
[Description("Draft")]
Draft,
[Description("Active")]
Active,
[Description("Expired")]
Expired,
[Description("Void")]
Void
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportMethod
{
Unknown,
[Description("Referral")]
Referral
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportCategory
{
Unknown,
[Description("Clothing")]
Clothing,
[Description("Food")]
Food,
[Description("Incidentals")]
Incidentals,
[Description("Lodging")]
Lodging,
[Description("Transportation")]
Transportation
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportSubCategory
{
None,
[Description("Hotel/Motel")]
Lodging_Hotel,
[Description("Billeting")]
Lodging_Billeting,
[Description("Group Lodging")]
Lodging_Group,
[Description("Groceries")]
Food_Groceries,
[Description("Restaurant Meals")]
Food_Restaurant,
[Description("Taxi")]
Transportation_Taxi,
[Description("Other")]
Transportation_Other
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportVoidReason
{
[Description("Error On Printed Referral")]
ErrorOnPrintedReferral,
[Description("New Supplier Required")]
NewSupplierRequired,
[Description("Supplier Could Not Meet Need")]
SupplierCouldNotMeetNeed
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SupportReprintReason
{
[Description("Error On Printed Referral")]
ErrorOnPrintedReferral,
[Description("Printed Error")]
PrintedError,
[Description("Evacuee Lost Referral")]
EvacueeLostReferral
}
}
| 31.681564 | 214 | 0.646212 | [
"Apache-2.0"
] | josephweinkam/embc-ess-mod | registrants/src/API/EMBC.Registrants.API/Controllers/EvacuationsController.cs | 17,016 | C# |
using System.Web.Mvc;
using JetBrains.Annotations;
namespace essentialMix.Web.Mvc.Annotations
{
/// <summary>
/// Register this in Global.asax Application_Start()
/// GlobalFilters.Filters.Add(new SaveModelStateAttribute());
/// or in App_Start/FilterConfig.cs RegisterGlobalFilters
/// filters.Add(new SaveModelStateAttribute());
/// </summary>
public class SaveModelStateAttribute : ActionFilterAttribute
{
public SaveModelStateAttribute()
{
}
public override void OnActionExecuted([NotNull] ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
filterContext.Controller.TempData["ModelState"] = filterContext.Controller.ViewData.ModelState;
}
}
} | 29.25 | 98 | 0.77208 | [
"MIT"
] | asm2025/asm | Framework/essentialMix.Web.Mvc/Annotations/SaveModelStateAttribute.cs | 704 | 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 kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.KinesisAnalyticsV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KinesisAnalyticsV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for RunConfigurationDescription Object
/// </summary>
public class RunConfigurationDescriptionUnmarshaller : IUnmarshaller<RunConfigurationDescription, XmlUnmarshallerContext>, IUnmarshaller<RunConfigurationDescription, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
RunConfigurationDescription IUnmarshaller<RunConfigurationDescription, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public RunConfigurationDescription Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
RunConfigurationDescription unmarshalledObject = new RunConfigurationDescription();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("ApplicationRestoreConfigurationDescription", targetDepth))
{
var unmarshaller = ApplicationRestoreConfigurationUnmarshaller.Instance;
unmarshalledObject.ApplicationRestoreConfigurationDescription = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static RunConfigurationDescriptionUnmarshaller _instance = new RunConfigurationDescriptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static RunConfigurationDescriptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.423913 | 194 | 0.669651 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/src/Services/KinesisAnalyticsV2/Generated/Model/Internal/MarshallTransformations/RunConfigurationDescriptionUnmarshaller.cs | 3,351 | C# |
using System;
using Twainsoft.FHDO.Compiler.Scanner;
namespace Twainsoft.FHDO.Compiler.App
{
static class Program
{
static void Main()
{
string[] inputs = {"() \n349 )4.1E1(", "\t-349 ) ( +598", "() \n+555 )+-222", ") \n-566 287)<",
"( \n5.66 M)287)", "( \n \t-256.77E-12) "};
string[] meineINputs = { "(", "((", "()", "(())", "()()", " (", " ) " };
foreach (var strBuffer in meineINputs)
{
Console.WriteLine("Neuer Input:");
var scanner = new TestScanner(strBuffer);
var tokenList = scanner.GetTokenList();
foreach (var token in tokenList)
{
PrintToken(token);
}
}
Console.ReadLine();
}
public static void PrintToken(int token)
{
switch (token)
{
case TestScanner.OPEN:
Console.WriteLine(" ( ");
break;
case TestScanner.CLOSE:
Console.WriteLine(" ) ");
break;
case TestScanner.INTEGER:
Console.WriteLine(" INTEGER ");
break;
case TestScanner.REAL:
Console.WriteLine(" REAL ");
break;
default:
Console.WriteLine("Unbekannter Token " + token);
break;
}
}
}
}
| 28.4 | 111 | 0.404609 | [
"MIT"
] | fdeitelhoff/Twainsoft.FHDO.Compiler | src/Twainsoft.FHDO.Compiler.App/Program.cs | 1,564 | C# |
namespace StudentsLearning.Data.Repositories
{
#region
using System;
using System.Data.Entity;
using System.Linq;
#endregion
public class EfGenericRepository<T> : IRepository<T>
where T : class
{
public EfGenericRepository(IStudentsLearningDbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is required to use this repository.", "context");
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
protected IDbSet<T> DbSet { get; set; }
protected IStudentsLearningDbContext Context { get; set; }
public virtual IQueryable<T> All()
{
return this.DbSet.AsQueryable();
}
public virtual T GetById(object id)
{
return this.DbSet.Find(id);
}
public virtual void Add(T entity)
{
var entry = this.Context.Entry(entity);
if (entry.State != EntityState.Detached)
{
entry.State = EntityState.Added;
}
else
{
this.DbSet.Add(entity);
}
}
public virtual void Update(T entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
var entry = this.Context.Entry(entity);
if (entry.State != EntityState.Deleted)
{
entry.State = EntityState.Deleted;
}
else
{
this.DbSet.Attach(entity);
this.DbSet.Remove(entity);
}
}
public virtual void Delete(object id)
{
var entity = this.GetById(id);
if (entity != null)
{
this.Delete(entity);
}
}
public virtual T Attach(T entity)
{
return this.Context.Set<T>().Attach(entity);
}
public virtual void Detach(T entity)
{
var entry = this.Context.Entry(entity);
entry.State = EntityState.Detached;
}
public int SaveChanges()
{
return this.Context.SaveChanges();
}
public void Dispose()
{
this.Context.Dispose();
}
}
} | 24.203704 | 119 | 0.491201 | [
"MIT"
] | Momus-Telerik-Academy/Student-Learning-System | Source/Data/StudentsLearningSystem.Data/Repositories/EfGenericRepository.cs | 2,616 | C# |
namespace UglyToad.PdfPig.Graphics.Operations.TextState
{
using System.IO;
/// <inheritdoc />
/// <summary>
/// Set the character spacing to a number expressed in unscaled text space units.
/// Initial value: 0.
/// </summary>
public class SetCharacterSpacing : IGraphicsStateOperation
{
/// <summary>
/// The symbol for this operation in a stream.
/// </summary>
public const string Symbol = "Tc";
/// <inheritdoc />
public string Operator => Symbol;
/// <summary>
/// The character spacing.
/// </summary>
public decimal Spacing { get; }
/// <summary>
/// Create a new <see cref="SetCharacterSpacing"/>.
/// </summary>
/// <param name="spacing">The character spacing.</param>
public SetCharacterSpacing(decimal spacing)
{
Spacing = spacing;
}
/// <inheritdoc />
public void Run(IOperationContext operationContext)
{
var currentState = operationContext.GetCurrentState();
currentState.FontState.CharacterSpacing = Spacing;
}
/// <inheritdoc />
public void Write(Stream stream)
{
stream.WriteNumberText(Spacing, Symbol);
}
/// <inheritdoc />
public override string ToString()
{
return $"{Spacing} {Symbol}";
}
}
} | 26.87037 | 85 | 0.550655 | [
"Apache-2.0"
] | BenyErnest/PdfPig | src/UglyToad.PdfPig/Graphics/Operations/TextState/SetCharacterSpacing.cs | 1,453 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore.Query
{
public abstract class OwnedEntityQueryRelationalTestBase : OwnedEntityQueryTestBase
{
protected TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ListLoggerFactory;
protected void ClearLog() => TestSqlLoggerFactory.Clear();
protected void AssertSql(params string[] expected) => TestSqlLoggerFactory.AssertBaseline(expected);
}
}
| 36.944444 | 111 | 0.765414 | [
"Apache-2.0"
] | SergerGood/efcore | test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs | 667 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Target
{
public class CombinedTests
{
public string currentWriteCopier;
public bool LogAndEVentSource()
{
LogTo.Debug("Sent & finished " + currentWriteCopier.Length);
var a = DateTime.Now;
Console.WriteLine(a.Add(TimeSpan.FromDays(12)));
StaticEventSource.ConnectStop(currentWriteCopier);
return false;
}
public void SimpleLogFromTryCatch()
{
try
{
Console.WriteLine(1);
}
catch (InvalidCastException e1)
{
LogTo.Warn(e1);
}
catch (Exception e2)
{
Console.WriteLine(2);
LogTo.Error(e2);
}
}
public void ComplexLogFromTryCatch()
{
try
{
LogTo.Debug("a");
HellogTo.Debug("a");
LogTo.Debug("a");
HellogTo.Debug("a");
HellogTo.Hello("a");
}
catch { Console.WriteLine(1); }
try
{
LogTo.Info("a", 2);
throw new NotSupportedException("generic catch");
}
catch (InvalidCastException e1) { LogTo.Warn(e1); }
catch (Exception e2) { LogTo.Error(e2); }
try
{
HellogTo.Debug("0");
LogTo.Debug("5");
LogTo.Debug("6");
HellogTo.Debug("1");
HellogTo.Debug("2");
throw new InvalidCastException("no cast");
}
catch (InvalidCastException e1) { LogTo.Warn(e1); }
catch (Exception e2)
{
LogTo.Error(e2);
LogTo.Error(e2);
}
}
public async Task AsyncLogWithError()
{
await Task.Delay(1);
LogTo.Debug("aaaa");
try
{
await Task.Delay(1);
throw new InvalidOperationException("after delay");
}
catch (Exception e)
{
LogTo.Error(e);
}
}
}
}
#region [ License information ]
/* ************************************************************
*
* Copyright (c) Attila Kiskó, enyim.com
*
* 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.
*
* ************************************************************/
#endregion
| 21.186441 | 78 | 0.6112 | [
"Apache-2.0"
] | enyim/BuildTools | Tests/Target/CombinedTests.cs | 2,501 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace NSspi.Credentials
{
/// <summary>
/// Provides access to the pre-existing credentials of a security principle.
/// </summary>
public class Credential : IDisposable
{
/// <summary>
/// Whether the Credential has been disposed.
/// </summary>
private bool disposed;
/// <summary>
/// The name of the security package that controls the credential.
/// </summary>
private string securityPackage;
/// <summary>
/// A safe handle to the credential's handle.
/// </summary>
private SafeCredentialHandle safeCredHandle;
/// <summary>
/// The UTC time the credentials expire.
/// </summary>
private DateTime expiry;
/// <summary>
/// Initializes a new instance of the Credential class.
/// </summary>
/// <param name="package">The security package to acquire the credential from.</param>
public Credential( string package )
{
this.disposed = false;
this.securityPackage = package;
this.expiry = DateTime.MinValue;
this.PackageInfo = PackageSupport.GetPackageCapabilities( this.SecurityPackage );
}
/// <summary>
/// Gets metadata for the security package associated with the credential.
/// </summary>
public SecPkgInfo PackageInfo { get; private set; }
/// <summary>
/// Gets the name of the security package that owns the credential.
/// </summary>
public string SecurityPackage
{
get
{
CheckLifecycle();
return this.securityPackage;
}
}
/// <summary>
/// Returns the User Principle Name of the credential. Depending on the underlying security
/// package used by the credential, this may not be the same as the Down-Level Logon Name
/// for the user.
/// </summary>
public string PrincipleName
{
get
{
QueryNameAttribCarrier carrier;
SecurityStatus status;
string name = null;
bool gotRef = false;
CheckLifecycle();
status = SecurityStatus.InternalError;
carrier = new QueryNameAttribCarrier();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
this.safeCredHandle.DangerousAddRef( ref gotRef );
}
catch( Exception )
{
if( gotRef == true )
{
this.safeCredHandle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if( gotRef )
{
status = CredentialNativeMethods.QueryCredentialsAttribute_Name(
ref this.safeCredHandle.rawHandle,
CredentialQueryAttrib.Names,
ref carrier
);
this.safeCredHandle.DangerousRelease();
if( status == SecurityStatus.OK && carrier.Name != IntPtr.Zero )
{
try
{
name = Marshal.PtrToStringUni( carrier.Name );
}
finally
{
NativeMethods.FreeContextBuffer( carrier.Name );
}
}
}
}
if( status.IsError() )
{
throw new SSPIException( "Failed to query credential name", status );
}
return name;
}
}
/// <summary>
/// Gets the UTC time the credentials expire.
/// </summary>
public DateTime Expiry
{
get
{
CheckLifecycle();
return this.expiry;
}
protected set
{
CheckLifecycle();
this.expiry = value;
}
}
/// <summary>
/// Gets a handle to the credential.
/// </summary>
public SafeCredentialHandle Handle
{
get
{
CheckLifecycle();
return this.safeCredHandle;
}
protected set
{
CheckLifecycle();
this.safeCredHandle = value;
}
}
/// <summary>
/// Releases all resources associated with the credential.
/// </summary>
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if( this.disposed == false )
{
if( disposing )
{
this.safeCredHandle.Dispose();
}
this.disposed = true;
}
}
private void CheckLifecycle()
{
if( this.disposed )
{
throw new ObjectDisposedException( "Credential" );
}
}
}
} | 29.188119 | 100 | 0.43521 | [
"BSD-2-Clause"
] | yadavvineet/nsspi | NSspi/Credentials/Credential.cs | 5,898 | C# |
using HarmonyLib;
using RimWorld;
using Verse;
namespace ConvertThenRecruit;
[HarmonyPatch(typeof(Pawn_IdeoTracker), "IdeoConversionAttempt")]
public static class Pawn_IdeoTracker_IdeoConversionAttempt
{
public static void Postfix(bool __result, Pawn ___pawn)
{
if (!__result)
{
return;
}
if (___pawn.guest.interactionMode != ConvertThenRecruit.ConvertThenRecruitMode)
{
return;
}
if (___pawn.Ideo != Faction.OfPlayer.ideos.PrimaryIdeo)
{
return;
}
___pawn.guest.interactionMode = PrisonerInteractionModeDefOf.AttemptRecruit;
var text = "CTR.pawnconverted".Translate(___pawn.NameFullColored);
var messageType = MessageTypeDefOf.PositiveEvent;
var message = new Message(text, messageType, new LookTargets(___pawn));
Messages.Message(message);
}
} | 27.606061 | 87 | 0.665203 | [
"MIT"
] | Dipod/ConvertThenRecruit | Source/ConvertThenRecruit/Pawn_IdeoTracker_IdeoConversionAttempt.cs | 913 | C# |
namespace Crypton.AvChat.Gui {
partial class ChangeLogView {
/// <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.txtChangeLog = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtChangeLog
//
this.txtChangeLog.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtChangeLog.Location = new System.Drawing.Point(10, 10);
this.txtChangeLog.Multiline = true;
this.txtChangeLog.Name = "txtChangeLog";
this.txtChangeLog.ReadOnly = true;
this.txtChangeLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtChangeLog.Size = new System.Drawing.Size(494, 524);
this.txtChangeLog.TabIndex = 0;
this.txtChangeLog.WordWrap = false;
//
// ChangeLogView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(514, 544);
this.Controls.Add(this.txtChangeLog);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ChangeLogView";
this.Padding = new System.Windows.Forms.Padding(10);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Change Log";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtChangeLog;
}
} | 39.539683 | 107 | 0.588519 | [
"MIT"
] | CryptonZylog/ueravchatclient | Crypton.AvChat.Gui/ChangeLogView.Designer.cs | 2,493 | 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("Arebis .NET Extensions for Data")]
[assembly: AssemblyDescription(".NET library for using databases through ADO.NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Arebis")]
[assembly: AssemblyProduct("Arebis Library")]
[assembly: AssemblyCopyright("© Copyright 2008-2016 Arebis")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.0.0")] // Assembly version
[assembly: AssemblyInformationalVersion("1.4.0.0")] // Nuget version, must be X.Y.0.0
[assembly: System.CLSCompliant(true)]
| 42.205882 | 86 | 0.734495 | [
"MIT"
] | FingersCrossed/Arebis.Common | Arebis.Data/Properties/AssemblyInfo.cs | 1,438 | C# |
using ChakraCore.API;
namespace JavaScript.API.JSUnityEngine {
class JSYieldInstruction {
public static void Register(JavaScriptContext context) {
JavaScriptValue YieldInstructionPrototype;
JavaScriptValue YieldInstructionConstructor = Bridge.CreateConstructor(
typeof(UnityEngine.YieldInstruction),
(args) => { throw new System.NotImplementedException(); },
out YieldInstructionPrototype
);
JavaScriptValue
.GlobalObject
.GetProperty("UnityEngine")
.SetProperty("YieldInstruction", YieldInstructionConstructor);
// Static Fields
// Static Property Accessors
// Static Methods
// Instance Fields
// Instance Property Accessors
// Instance Methods
// YieldInstruction()
}
}
}
| 20.4 | 77 | 0.676471 | [
"MIT"
] | SpiralP/typescript-for-unity | Assets/Scripts/JavaScript/API/UnityEngine/YieldInstruction.cs | 816 | C# |
using FavourAPI.Data.Repositories;
using FavourAPI.GraphQL.Types;
using FavourAPI.Services;
using FavourAPI.Services.Contracts;
using GraphQL.Types;
using GraphQL.Authorization;
using System;
using FavourAPI.Data.Dtos.Offerings;
using System.Collections.Generic;
using FavourAPI.Dtos;
namespace FavourAPI.GraphQL
{
public class FavourQuery : ObjectGraphType
{
public FavourQuery(IUserRepository userRepo,
IOfferService offerService,
IFavourService favourService,
IOfferingService offeringService,
IProviderService providerService,
ICompanyConsumerRepository companyConsumerepository, // TODO: use service not reposiotry directly !!!!
IPersonConsumerService personConsumerService,
IExperienceRepository experienceRepository, // TODO: use service not reposiotry directly !!!!
IPositionRepository positionRepository, // TODO: use service not reposiotry directly !!!!
ISkillRepository skillRepository, // TODO: use service not reposiotry directly !!!!
IIndustryRepository industryRepository // TODO: use service not reposiotry directly !!!!
)
{
Field<UserType>(
"user",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "id" }),
resolve: context => userRepo.GetById(context.GetArgument<Guid>("id"))
);
FieldAsync<ProviderType>(
"provider",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "userId" }),
resolve: async context =>
{
var result = await providerService.GetById(context.GetArgument<string>("userId"), true);
return result;
}
);
FieldAsync<CompanyConsumerType>(
"companyConsumer",
arguments: new QueryArguments(new QueryArgument<StringGraphType>() { Name = "id" }),
resolve: async context =>
{
var providerId = context.GetArgument<string>("id");
return await companyConsumerepository.GetById(providerId);
});
FieldAsync<PersonConsumerType>(
"personConsumer",
arguments: new QueryArguments(new QueryArgument<StringGraphType>() { Name = "id" }),
resolve: async context =>
{
var consumerId = context.GetArgument<string>("id");
PersonConsumerDto consumer = await personConsumerService.GetById(consumerId);
return consumer;
});
Field<JobOfferType>(
"jobOffer",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "id" }),
resolve: context =>
{
var offerId = context.GetArgument<Guid>("id");
if (offerId == null)
{
return offerService.GetAllOffers();
}
return offerService.GetAllOffers();
}
);
Field<ListGraphType<FavourType>>(
"favours",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "id" }),
resolve: context =>
{
var favourId = context.GetArgument<Guid>("id");
if (favourId == null)
{
return favourService.GetAllFavours();
}
return favourService.GetAllFavours();
}
);
FieldAsync<ListGraphType<OfferingType>>(
"offerings",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "id" }),
resolve: async context =>
{
// TODO: add filters
var offeringId = context.GetArgument<Guid>("id");
if (offeringId == null)
{
return await offeringService.GetAllActiveOfferings();
}
return await offeringService.GetAllActiveOfferings();
}
);
FieldAsync<ListGraphType<ExperienceType>>(
"experiences",
resolve: async context =>
{
return await experienceRepository.GetAll();
});
FieldAsync<ListGraphType<PositionType>>(
"positions",
resolve: async context =>
{
return await positionRepository.GetAll();
});
FieldAsync<ListGraphType<SkillType>>(
"skills",
resolve: async context =>
{
this.AuthorizeWith("UserPolicy");
return await skillRepository.GetAll();
});
FieldAsync<ListGraphType<IndustryType>>(
"industries",
resolve: async context =>
{
var industriesWithPositions = await industryRepository.GetAll();
return industriesWithPositions;
});
FieldAsync<ListGraphType<ActiveOfferingType>>(
"myActiveOfferings",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "userId" }),
resolve: async context =>
{
var providerId = context.GetArgument<string>("userId");
List<ActiveOfferingDto> myActiveOfferings = await providerService.GetAllActiveOfferings(providerId);
return myActiveOfferings;
});
FieldAsync<ListGraphType<OfferingType>>(
"myOfferingApplications",
arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "userId" }),
resolve: async context =>
{
var consumerId = context.GetArgument<string>("userId");
var myActiveOfferings = personConsumerService.GetApplications(consumerId);
return myActiveOfferings;
});
//FieldAsync<ListGraphType<ApplicationType>>(
// "applicationsOfProvider",
// arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "userId" }),
// resolve: async context =>
// {
// var providerId = context.GetArgument<string>("userId");
// var providerApplications = await providerService.GetAllApplications();
// return providerApplications;
// });
}
}
}
| 40.248555 | 120 | 0.53138 | [
"MIT"
] | indeavr/favour-api | FavourAPI/GraphQL/FavourQuery.cs | 6,965 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the macie2-2020-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Macie2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Macie2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DomainDetails Object
/// </summary>
public class DomainDetailsUnmarshaller : IUnmarshaller<DomainDetails, XmlUnmarshallerContext>, IUnmarshaller<DomainDetails, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
DomainDetails IUnmarshaller<DomainDetails, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public DomainDetails Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
DomainDetails unmarshalledObject = new DomainDetails();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("domainName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DomainName = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static DomainDetailsUnmarshaller _instance = new DomainDetailsUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static DomainDetailsUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 33.347826 | 152 | 0.638527 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Macie2/Generated/Model/Internal/MarshallTransformations/DomainDetailsUnmarshaller.cs | 3,068 | C# |
using System;
namespace _03._On_Time_for_the_Exam
{
class Program
{
static void Main(string[] args)
{
int examHour = int.Parse(Console.ReadLine());
int examMin = int.Parse(Console.ReadLine());
int arriveHour = int.Parse(Console.ReadLine());
int arriveMin = int.Parse(Console.ReadLine());
int examTime = examHour * 60+examMin;
int arriveTime = arriveHour * 60 + arriveMin;
if (arriveTime>examTime)
{
Console.WriteLine($"Late");
if (arriveTime-examTime<60)
{
Console.WriteLine($"{(arriveTime - examTime)} minutes after the start");
}
else
{
Console.WriteLine($"{(arriveTime - examTime)/60}:{((arriveTime - examTime)%60):D2} hours after the start");
}
}
else if(arriveTime <= examTime && examTime-arriveTime<=30)
{
Console.WriteLine("On time");
if (arriveTime!=examTime)
{
Console.WriteLine($"{(examTime-arriveTime)} minutes before the start");
}
}
else
{
Console.WriteLine("Early");
if (examTime - arriveTime < 60)
{
Console.WriteLine($"{(examTime - arriveTime)} minutes before the start");
}
else
{
Console.WriteLine($"{(examTime - arriveTime)/60}:{((examTime - arriveTime) % 60):D2} hours before the start");
}
}
}
}
}
| 32.388889 | 130 | 0.457404 | [
"MIT"
] | theoners/Programing-Basics-Exams | Exam - 6 March 2016/03. On Time for the Exam/Program.cs | 1,751 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace VehicleTrakker
{
public class ValidGuidToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var id = (Guid)value;
return id == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| 27.08 | 99 | 0.682422 | [
"MIT"
] | NiclasBackman/VehicleTrakker | VehicleTrakker/Converters/ValidGuidToVisibilityConverter.cs | 679 | C# |
namespace Breeze.Core {
public enum OperatorType {
AnyAll = 1,
AndOr = 2,
Binary = 3,
Unary = 4
}
} | 12.1 | 28 | 0.553719 | [
"MIT"
] | Breeze/breeze.server.net | AspNetCore-v3/Breeze.Core/Query/OperatorType.cs | 121 | C# |
using static DncZeus.Api.Entities.Enums.CommonEnum;
namespace DncZeus.Api.RequestPayload.Base.Manager
{
/// <summary>
/// 图标请求参数实体
/// </summary>
public class ManagerSelectRequestPayload
{
public int HospitalId { get; set; }
}
}
| 20.230769 | 52 | 0.657795 | [
"MIT"
] | SkyGrass/ttxy | DncZeus.Api/RequestPayload/Base/Manager/ManagerSelectRequestPayload.cs | 281 | 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 translate-2017-07-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Translate.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Translate.Model.Internal.MarshallTransformations
{
/// <summary>
/// TranslateText Request Marshaller
/// </summary>
public class TranslateTextRequestMarshaller : IMarshaller<IRequest, TranslateTextRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((TranslateTextRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(TranslateTextRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Translate");
string target = "AWSShineFrontendService_20170701.TranslateText";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-01";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetSourceLanguageCode())
{
context.Writer.WritePropertyName("SourceLanguageCode");
context.Writer.Write(publicRequest.SourceLanguageCode);
}
if(publicRequest.IsSetTargetLanguageCode())
{
context.Writer.WritePropertyName("TargetLanguageCode");
context.Writer.Write(publicRequest.TargetLanguageCode);
}
if(publicRequest.IsSetTerminologyNames())
{
context.Writer.WritePropertyName("TerminologyNames");
context.Writer.WriteArrayStart();
foreach(var publicRequestTerminologyNamesListValue in publicRequest.TerminologyNames)
{
context.Writer.Write(publicRequestTerminologyNamesListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetText())
{
context.Writer.WritePropertyName("Text");
context.Writer.Write(publicRequest.Text);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static TranslateTextRequestMarshaller _instance = new TranslateTextRequestMarshaller();
internal static TranslateTextRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static TranslateTextRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.511811 | 141 | 0.607721 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Translate/Generated/Model/Internal/MarshallTransformations/TranslateTextRequestMarshaller.cs | 4,637 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
/// Structure specifying parameters of a newly created framebuffer.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct FramebufferCreateInfo
{
/// <summary>
/// Reserved for future use.
/// </summary>
public FramebufferCreateFlags? Flags
{
get;
set;
}
/// <summary>
/// A render pass that defines what render passes the framebuffer will
/// be compatible with.
/// </summary>
public RenderPass RenderPass
{
get;
set;
}
/// <summary>
/// An array of ImageView handles, each of which will be used as the
/// corresponding attachment in a render pass instance.
/// </summary>
public ImageView[] Attachments
{
get;
set;
}
/// <summary>
/// width, height and layers define the dimensions of the framebuffer.
/// If the render pass uses multiview, then layers must be one and each
/// attachment requires a number of layers that is greater than the
/// maximum bit index set in the view mask in the subpasses in which it
/// is used.
/// </summary>
public uint Width
{
get;
set;
}
/// <summary>
/// </summary>
public uint Height
{
get;
set;
}
/// <summary>
/// </summary>
public uint Layers
{
get;
set;
}
/// <summary>
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.FramebufferCreateInfo* pointer)
{
pointer->SType = StructureType.FramebufferCreateInfo;
pointer->Next = null;
if (Flags != null)
{
pointer->Flags = Flags.Value;
}
else
{
pointer->Flags = default;
}
pointer->RenderPass = RenderPass?.Handle ?? default;
pointer->AttachmentCount = (uint)(Interop.HeapUtil.GetLength(Attachments));
if (Attachments != null)
{
var fieldPointer = (SharpVk.Interop.ImageView*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.ImageView>(Attachments.Length).ToPointer());
for(int index = 0; index < (uint)(Attachments.Length); index++)
{
fieldPointer[index] = Attachments[index]?.Handle ?? default;
}
pointer->Attachments = fieldPointer;
}
else
{
pointer->Attachments = null;
}
pointer->Width = Width;
pointer->Height = Height;
pointer->Layers = Layers;
}
}
}
| 33.161538 | 158 | 0.568082 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk/FramebufferCreateInfo.gen.cs | 4,311 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generation date: 9/11/2020 3:24:26 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for ApplicantExamSingle in the schema.
/// </summary>
public partial class ApplicantExamSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<ApplicantExam>
{
/// <summary>
/// Initialize a new ApplicantExamSingle object.
/// </summary>
public ApplicantExamSingle(global::Microsoft.OData.Client.DataServiceContext context, string path)
: base(context, path) {}
/// <summary>
/// Initialize a new ApplicantExamSingle object.
/// </summary>
public ApplicantExamSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable)
: base(context, path, isComposable) {}
/// <summary>
/// Initialize a new ApplicantExamSingle object.
/// </summary>
public ApplicantExamSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<ApplicantExam> query)
: base(query) {}
}
/// <summary>
/// There are no comments for ApplicantExam in the schema.
/// </summary>
/// <KeyProperties>
/// ApplicantId
/// TestId
/// RequiredBy
/// </KeyProperties>
[global::Microsoft.OData.Client.Key("ApplicantId", "TestId", "RequiredBy")]
[global::Microsoft.OData.Client.EntitySet("ApplicantExams")]
public partial class ApplicantExam : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Create a new ApplicantExam object.
/// </summary>
/// <param name="applicantId">Initial value of ApplicantId.</param>
/// <param name="testId">Initial value of TestId.</param>
/// <param name="requiredBy">Initial value of RequiredBy.</param>
/// <param name="score">Initial value of Score.</param>
/// <param name="completedOn">Initial value of CompletedOn.</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public static ApplicantExam CreateApplicantExam(string applicantId, string testId, global::System.DateTimeOffset requiredBy, int score, global::System.DateTimeOffset completedOn)
{
ApplicantExam applicantExam = new ApplicantExam();
applicantExam.ApplicantId = applicantId;
applicantExam.TestId = testId;
applicantExam.RequiredBy = requiredBy;
applicantExam.Score = score;
applicantExam.CompletedOn = completedOn;
return applicantExam;
}
/// <summary>
/// There are no comments for Property ApplicantId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ApplicantId
{
get
{
return this._ApplicantId;
}
set
{
this.OnApplicantIdChanging(value);
this._ApplicantId = value;
this.OnApplicantIdChanged();
this.OnPropertyChanged("ApplicantId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ApplicantId;
partial void OnApplicantIdChanging(string value);
partial void OnApplicantIdChanged();
/// <summary>
/// There are no comments for Property TestId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string TestId
{
get
{
return this._TestId;
}
set
{
this.OnTestIdChanging(value);
this._TestId = value;
this.OnTestIdChanged();
this.OnPropertyChanged("TestId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _TestId;
partial void OnTestIdChanging(string value);
partial void OnTestIdChanged();
/// <summary>
/// There are no comments for Property RequiredBy in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.DateTimeOffset RequiredBy
{
get
{
return this._RequiredBy;
}
set
{
this.OnRequiredByChanging(value);
this._RequiredBy = value;
this.OnRequiredByChanged();
this.OnPropertyChanged("RequiredBy");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _RequiredBy;
partial void OnRequiredByChanging(global::System.DateTimeOffset value);
partial void OnRequiredByChanged();
/// <summary>
/// There are no comments for Property Score in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual int Score
{
get
{
return this._Score;
}
set
{
this.OnScoreChanging(value);
this._Score = value;
this.OnScoreChanged();
this.OnPropertyChanged("Score");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private int _Score;
partial void OnScoreChanging(int value);
partial void OnScoreChanged();
/// <summary>
/// There are no comments for Property CompletedOn in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.DateTimeOffset CompletedOn
{
get
{
return this._CompletedOn;
}
set
{
this.OnCompletedOnChanging(value);
this._CompletedOn = value;
this.OnCompletedOnChanged();
this.OnPropertyChanged("CompletedOn");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _CompletedOn;
partial void OnCompletedOnChanging(global::System.DateTimeOffset value);
partial void OnCompletedOnChanged();
/// <summary>
/// There are no comments for Property Status in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.HcmCompletionStatus> Status
{
get
{
return this._Status;
}
set
{
this.OnStatusChanging(value);
this._Status = value;
this.OnStatusChanged();
this.OnPropertyChanged("Status");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.HcmCompletionStatus> _Status;
partial void OnStatusChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.HcmCompletionStatus> value);
partial void OnStatusChanged();
/// <summary>
/// There are no comments for Property Notes in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string Notes
{
get
{
return this._Notes;
}
set
{
this.OnNotesChanging(value);
this._Notes = value;
this.OnNotesChanged();
this.OnPropertyChanged("Notes");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _Notes;
partial void OnNotesChanging(string value);
partial void OnNotesChanged();
/// <summary>
/// This event is raised when the value of the property is changed
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// The value of the property is changed
/// </summary>
/// <param name="property">property name</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
protected virtual void OnPropertyChanged(string property)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
}
| 42.619835 | 186 | 0.595792 | [
"MIT"
] | NathanClouseAX/AAXDataEntityPerfTest | Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/ApplicantExam.cs | 10,316 | C# |
#region License and information
/* * * * *
* A quick mesh serializer that allows to serialize a Mesh as byte array. It should
* support any kind of mesh including skinned meshes, multiple submeshes, different
* mesh topologies as well as blendshapes. I tried my best to avoid unnecessary data
* by only serializing information that is present. It supports Vector4 UVs. The index
* data may be stored as bytes, ushorts or ints depending on the actual highest used
* vertex index within a submesh. It uses a tagging system for optional "chunks". The
* base information only includes the vertex position array and the submesh count.
* Everything else is handled through optional chunks.
*
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Markus Göbel (Bunny83)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* * * * */
#endregion License and information
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GcodeToMesh.MeshDecimator;
using GcodeToMesh.MeshDecimator.Math;
namespace GcodeToMesh.MeshClasses
{
[System.Serializable]
public class MeshData
{
private byte[] m_Data;
private Mesh m_Mesh;
public byte[] Data { get{ return m_Data; } }
public void SetMesh(Mesh aMesh)
{
m_Mesh = aMesh;
if (aMesh == null)
m_Data = null;
else
m_Data = MeshSerializer.SerializeMesh(m_Mesh);
}
}
public static class MeshSerializer
{
/*
* Structure:
* - Magic string "Mesh" (4 bytes)
* - vertex count [int] (4 bytes)
* - submesh count [int] (4 bytes)
* - vertices [array of Vector3]
*
* - additional chunks:
* [vertex attributes]
* - Name (name of the Mesh object)
* - Normals [array of Vector3]
* - Tangents [array of Vector4]
* - Colors [array of Color32]
* - UV0-4 [
* - component count[byte](2/3/4)
* - array of Vector2/3/4
* ]
* - BoneWeights [array of 4x int+float pair]
*
* [other data]
* - Submesh [
* - topology[byte]
* - count[int]
* - component size[byte](1/2/4)
* - array of byte/ushort/int
* ]
* - Bindposes [
* - count[int]
* - array of Matrix4x4
* ]
* - BlendShape [
* - Name [string]
* - frameCount [int]
* - frames [ array of:
* - frameWeight [float]
* - array of [
* - position delta [Vector3]
* - normal delta [Vector3]
* - tangent delta [Vector3]
* ]
* ]
* ]
*/
private enum EChunkID : byte
{
End,
Name,
Normals,
Tangents,
Colors,
BoneWeights,
UV0, UV1, UV2, UV3,
Submesh,
Bindposes,
BlendShape,
}
const uint m_Magic = 0x6873654D; // "Mesh"
public static byte[] SerializeMesh(Mesh aMesh)
{
using (var stream = new MemoryStream())
{
SerializeMesh(stream, aMesh);
return stream.ToArray();
}
}
public static void SerializeMesh(MemoryStream aStream, Mesh aMesh)
{
using (var writer = new BinaryWriter(aStream))
SerializeMesh(writer, aMesh);
}
public static void SerializeMesh(BinaryWriter aWriter, Mesh aMesh)
{
aWriter.Write(m_Magic);
var vertices = aMesh.Vertices;
int count = vertices.Length;
int subMeshCount = 1;
aWriter.Write(count);
aWriter.Write(subMeshCount);
foreach (var v in vertices)
aWriter.WriteVector3((Vector3)v);
// start of tagged chunks
if (!string.IsNullOrEmpty(aMesh.name))
{
aWriter.Write((byte)EChunkID.Name);
aWriter.Write(aMesh.name);
}
var normals = aMesh.Normals;
if (normals != null && normals.Length == count)
{
aWriter.Write((byte)EChunkID.Normals);
foreach (var v in normals)
aWriter.WriteVector3(v);
normals = null;
}
var tangents = aMesh.Tangents;
if (tangents != null && tangents.Length == count)
{
aWriter.Write((byte)EChunkID.Tangents);
foreach (var v in tangents)
aWriter.WriteVector4(v);
tangents = null;
}
List<int> indices = new List<int>(count * 3);
for (int i = 0; i < subMeshCount; i++)
{
indices.Clear();
aMesh.GetIndices(i, indices);
if (indices.Count > 0)
{
aWriter.Write((byte)EChunkID.Submesh);
//aWriter.Write((byte)aMesh.GetTopology(i));
aWriter.Write((byte)0);
aWriter.Write(indices.Count);
var max = indices.Max();
if (max < 256)
{
aWriter.Write((byte)1);
foreach (var index in indices)
aWriter.Write((byte)index);
}
else if (max < 65536)
{
aWriter.Write((byte)2);
foreach (var index in indices)
aWriter.Write((ushort)index);
}
else
{
aWriter.Write((byte)4);
foreach (var index in indices)
aWriter.Write(index);
}
}
}
aWriter.Write((byte)EChunkID.End);
}
}
public static class BinaryReaderWriterUnityExt
{
public static void WriteVector2(this BinaryWriter aWriter, Vector2 aVec)
{
aWriter.Write(aVec.x); aWriter.Write(aVec.y);
}
public static Vector2 ReadVector2(this BinaryReader aReader)
{
return new Vector2(aReader.ReadSingle(), aReader.ReadSingle());
}
public static void WriteVector3(this BinaryWriter aWriter, Vector3 aVec)
{
aWriter.Write(aVec.x); aWriter.Write(aVec.y); aWriter.Write(aVec.z);
}
public static Vector3 ReadVector3(this BinaryReader aReader)
{
return new Vector3(aReader.ReadSingle(), aReader.ReadSingle(), aReader.ReadSingle());
}
public static void WriteVector4(this BinaryWriter aWriter, Vector4 aVec)
{
aWriter.Write(aVec.x); aWriter.Write(aVec.y); aWriter.Write(aVec.z); aWriter.Write(aVec.w);
}
public static Vector4 ReadVector4(this BinaryReader aReader)
{
return new Vector4(aReader.ReadSingle(), aReader.ReadSingle(), aReader.ReadSingle(), aReader.ReadSingle());
}
}
} | 35.435146 | 119 | 0.531822 | [
"MIT"
] | Alaa-elgreatly/SlicerConnector | GcodeToMesh/MeshClasses/meshserializer.cs | 8,470 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using AspNet.Metrics.Infrastructure;
using Microsoft.AspNetCore.Http;
namespace AspNet.Metrics
{
public class MetricsOptions
{
public MetricsOptions()
{
IgnoredRequestPatterns = new List<Regex>();
RouteNameResolver = new DefaultRouteTemplateResolver();
HealthEndpoint = new PathString("/health");
MetricsEndpoint = new PathString("/json");
MetricsVisualizationEndpoint = new PathString("/metrics-visual");
MetricsTextEndpoint = new PathString("/metrics-text");
PingEndpoint = new PathString("/ping");
HealthEnabled = true;
MetricsEnabled = true;
MetricsTextEnabled = true;
MetricsVisualisationEnabled = true;
PingEnabled = true;
IgnoredRequestPatterns.Add(new Regex(@"\.(jpg|gif|css|js|png|woff|ttf|txt|eot|svg)$"));
IgnoredRequestPatterns.Add(new Regex("(?i)^swagger"));
IgnoredRequestPatterns.Add(new Regex("(?i)^metrics"));
IgnoredRequestPatterns.Add(new Regex("(?i)^metrics-text"));
IgnoredRequestPatterns.Add(new Regex("(?i)^metrics-visual"));
IgnoredRequestPatterns.Add(new Regex("(?i)^health"));
IgnoredRequestPatterns.Add(new Regex("(?i)^ping"));
IgnoredRequestPatterns.Add(new Regex("(?i)^favicon.ico"));
}
public bool HealthEnabled { get; set; }
public PathString HealthEndpoint { get; set; }
public IList<Regex> IgnoredRequestPatterns { get; }
public bool MetricsEnabled { get; set; }
public PathString MetricsEndpoint { get; set; }
public bool MetricsTextEnabled { get; set; }
public PathString MetricsTextEndpoint { get; set; }
public bool MetricsVisualisationEnabled { get; set; }
public PathString MetricsVisualizationEndpoint { get; set; }
public bool PingEnabled { get; set; }
public PathString PingEndpoint { get; set; }
public IRouteNameResolver RouteNameResolver { get; set; }
}
} | 35.409836 | 99 | 0.635648 | [
"Apache-2.0"
] | alhardy/aspnet-metrics | src/AspNet.Metrics/MetricsOptions.cs | 2,160 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using mad3.Models;
namespace mad3.Controllers
{
public class CountriesController : Controller
{
private readonly madContext _context;
public CountriesController(madContext context)
{
_context = context;
}
// GET: Countries
public async Task<IActionResult> Index()
{
return View(await _context.Countries.ToListAsync());
}
// GET: Countries/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var countries = await _context.Countries
.FirstOrDefaultAsync(m => m.Id == id);
if (countries == null)
{
return NotFound();
}
return View(countries);
}
// GET: Countries/Create
public IActionResult Create()
{
return View();
}
// POST: Countries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,UpdatedAt,CountryId,CountryA,CountryE,NationalityA,NationalityE,PhoneCode,NationalityAF,Code,CreatedAt")] Countries countries)
{
if (ModelState.IsValid)
{
_context.Add(countries);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(countries);
}
// GET: Countries/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var countries = await _context.Countries.FindAsync(id);
if (countries == null)
{
return NotFound();
}
return View(countries);
}
// POST: Countries/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,UpdatedAt,CountryId,CountryA,CountryE,NationalityA,NationalityE,PhoneCode,NationalityAF,Code,CreatedAt")] Countries countries)
{
if (id != countries.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(countries);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CountriesExists(countries.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(countries);
}
// GET: Countries/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var countries = await _context.Countries
.FirstOrDefaultAsync(m => m.Id == id);
if (countries == null)
{
return NotFound();
}
return View(countries);
}
// POST: Countries/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var countries = await _context.Countries.FindAsync(id);
_context.Countries.Remove(countries);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool CountriesExists(int id)
{
return _context.Countries.Any(e => e.Id == id);
}
}
}
| 29.803922 | 190 | 0.521491 | [
"MIT"
] | alrazyreturn/core_project | Controllers/CountriesController.cs | 4,560 | C# |
using System;
namespace _03.Play_Card
{
class Program
{
static void Main()
{
string switchCase = Console.ReadLine();
switch (switchCase)
{
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "10":
case "J":
case "Q":
case "K":
case "A":
Console.WriteLine("yes " + switchCase); break;
default:
Console.WriteLine("no " + switchCase);
break;
}
}
}
}
| 21.485714 | 66 | 0.325798 | [
"MIT"
] | tpulkov/CSharp-Part1 | homework/05.Conditional-Statements-Solution/03.Play Card/Program.cs | 754 | C# |
using System;
using System.Threading.Tasks;
using HipChat.Net.Http;
using HipChat.Net.Models.Request;
using HipChat.Net.Models.Response;
namespace HipChat.Net.Clients
{
public interface IRoomsClient
{
/// <summary>
/// Creates the asynchronous.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="owner">The owner.</param>
/// <param name="privacy">The privacy.</param>
/// <param name="guestAccess">if set to <c>true</c> [guest access].</param>
/// <returns>Task<IResponse<Entity>>.</returns>
Task<IResponse<bool>> CreateAsync(string name, string owner, RoomPrivacy privacy = RoomPrivacy.Public, bool guestAccess = false);
/// <summary>
/// Updates the asynchronous.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="privacy">The privacy.</param>
/// <param name="isArchived">if set to <c>true</c> [is archived].</param>
/// <param name="guestAccess">if set to <c>true</c> [guest access].</param>
/// <param name="owner">The owner.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> UpdateAsync(string name, RoomPrivacy privacy = RoomPrivacy.Public, bool isArchived = false, bool guestAccess = false, string owner = null);
/// <summary>
/// Deletes the asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> DeleteAsync(string room);
/// <summary>
/// Gets all asynchronous.
/// </summary>
/// <returns>Task<IResponse<RoomItems<Entity>>>.</returns>
Task<IResponse<RoomItems<Entity>>> GetAllAsync();
/// <summary>
/// Gets the asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <returns>Task<IResponse<Room>>.</returns>
Task<IResponse<Room>> GetAsync(string room);
/// <summary>
/// Gets the members asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <returns>Task<IResponse<RoomItems<Mention>>>.</returns>
Task<IResponse<RoomItems<Mention>>> GetMembersAsync(string room);
/// <summary>
/// Sends the notification asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="message">The message.</param>
/// <param name="notifyRoom">if set to <c>true</c> [notify room].</param>
/// <param name="format">The format.</param>
/// <param name="color">The color.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> SendNotificationAsync(string room, string message, bool notifyRoom = true, MessageFormat format = MessageFormat.Html, MessageColor color = MessageColor.Gray);
/// <summary>
/// Sends the notification asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="notification">The notification.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> SendNotificationAsync(string room, SendNotification notification);
/// <summary>
/// Creates the webhook.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="url">The URL.</param>
/// <param name="webhookEvent">The webhook event.</param>
/// <param name="name">The name.</param>
/// <param name="pattern">The pattern.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> CreateWebhookAsync(string room, Uri url, WebhookEvent webhookEvent, string name = null, string pattern = null);
/// <summary>
/// Creates the webhook asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="hook">The hook.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> CreateWebhookAsync(string room, CreateWebhook hook);
/// <summary>
/// Gets the webhooks.
/// </summary>
/// <param name="room">The room.</param>
/// <returns>Task<IResponse<Room>>.</returns>
Task<IResponse<RoomItems<Webhook>>> GetWebhooks(string room);
/// <summary>
/// Deletes the webhook.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="id">The identifier.</param>
/// <returns>Task<IResponse<System.Boolean>>.</returns>
Task<IResponse<bool>> DeleteWebhook(string room, string id);
/// <summary>
/// Gets the history asynchronous.
/// </summary>
/// <param name="room">The room.</param>
/// <returns>Task<IResponse<RoomItems<Message>>>.</returns>
Task<IResponse<RoomItems<Message>>> GetHistoryAsync(string room);
}
}
| 40.658333 | 184 | 0.638451 | [
"MIT"
] | sirkirby/hipchat.net | src/HipChat.Net/Clients/IRoomsClient.cs | 4,881 | C# |
// <copyright>
// Copyright Southeast Christian Church
//
// Licensed under the Southeast Christian Church License (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License shoud be included with this file.
//
// 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.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalanche.CustomControls;
using Avalanche.Models;
using FFImageLoading.Forms;
using FFImageLoading.Svg.Forms;
using Xam.Forms.Markdown;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Avalanche.Components.ListView
{
[XamlCompilation( XamlCompilationOptions.Compile )]
public partial class CardListView : ContentView, IListViewComponent
{
private double _columns = 2;
public double Columns
{
get
{
return _columns;
}
set
{
_columns = value;
gGrid.ColumnDefinitions.Clear();
for ( var i = 0; i < Columns; i++ )
{
gGrid.ColumnDefinitions.Add( new ColumnDefinition() { Width = new GridLength( 1, GridUnitType.Star ) } );
}
}
}
private bool _isRefreshing;
public bool IsRefreshing
{
get
{
return _isRefreshing;
}
set
{
_isRefreshing = value;
aiLoading.IsRunning = value;
}
}
public List<ListElement> ItemsSource { get; set; }
public object SelectedItem { get; set; }
public bool CanRefresh { get; set; }
public event EventHandler Refreshing;
public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;
public event EventHandler<ItemVisibilityEventArgs> ItemAppearing;
public CardListView()
{
InitializeComponent();
ItemsSource = new List<ListElement>();
for ( var i = 0; i < Columns; i++ )
{
gGrid.ColumnDefinitions.Add( new ColumnDefinition() { Width = new GridLength( 1, GridUnitType.Star ) } );
}
svScrollView.Scrolled += SvScrollView_Scrolled;
}
private void SvScrollView_Scrolled( object sender, ScrolledEventArgs e )
{
double scrollingSpace = svScrollView.ContentSize.Height - svScrollView.Height - 20;
if ( scrollingSpace <= e.ScrollY && !IsRefreshing )
{
if ( ItemsSource.Any() )
{
ItemAppearing?.Invoke( this, new ItemVisibilityEventArgs( ItemsSource[ItemsSource.Count - 1] ) );
}
}
}
public void Draw()
{
gGrid.Children.Clear();
gGrid.RowDefinitions.Clear();
gGrid.ColumnDefinitions.Clear();
for ( var i = 0; i < Columns; i++ )
{
gGrid.ColumnDefinitions.Add( new ColumnDefinition() { Width = new GridLength( 1, GridUnitType.Star ) } );
}
gGrid.RowDefinitions.Add( new RowDefinition() { Height = new GridLength( 1, GridUnitType.Auto ) } );
while ( gGrid.RowDefinitions.Count < ItemsSource.Count / Columns )
{
gGrid.RowDefinitions.Add( new RowDefinition() { Height = new GridLength( 1, GridUnitType.Auto ) } );
}
int itemNumber = 0;
foreach ( ListElement item in ItemsSource )
{
AddCell( item,
( itemNumber ) % Convert.ToInt32( Columns ),
Convert.ToInt32( Math.Floor( ( itemNumber ) / Columns ) ) );
itemNumber++;
}
}
private void AddItems( NotifyCollectionChangedEventArgs e )
{
while ( gGrid.RowDefinitions.Count < ItemsSource.Count / Columns )
{
gGrid.RowDefinitions.Add( new RowDefinition() { Height = new GridLength( 1, GridUnitType.Auto ) } );
}
foreach ( ListElement item in e.NewItems )
{
AddCell( item,
( ItemsSource.Count - 1 ) % Convert.ToInt32( Columns ),
Convert.ToInt32( Math.Floor( ( ItemsSource.Count - 1 ) / Columns ) ) );
}
}
private void AddCell( ListElement item, int x, int y )
{
var frame = new Frame()
{
Margin = new Thickness( 10, 10, 10, 10 ),
Padding = new Thickness( 0, 0, 0, 10 ),
HasShadow = true
};
StackLayout sl = new StackLayout()
{
HorizontalOptions = LayoutOptions.Center,
WidthRequest = ( App.Current.MainPage.Width / Columns ) - 10
};
frame.Content = sl;
if ( !string.IsNullOrWhiteSpace( item.Image ) )
{
if ( item.Image.Contains( ".svg" ) )
{
SvgCachedImage img = new SvgCachedImage()
{
Source = item.Image,
Aspect = Aspect.AspectFit,
WidthRequest = App.Current.MainPage.Width / Columns,
InputTransparent = true
};
sl.Children.Add( img );
}
else
{
CachedImage img = new CachedImage()
{
Source = item.Image,
Aspect = Aspect.AspectFit,
WidthRequest = App.Current.MainPage.Width / Columns,
InputTransparent = true
};
sl.Children.Add( img );
}
}
else if ( !string.IsNullOrWhiteSpace( item.Icon ) )
{
IconLabel icon = new IconLabel()
{
Text = item.Icon,
HorizontalOptions = LayoutOptions.Center,
FontSize = item.IconFontSize,
Margin = new Thickness( 0, 15, 0, 0 ),
TextColor = item.IconTextColor
};
sl.Children.Add( icon );
}
if ( !string.IsNullOrWhiteSpace( item.Title ) )
{
Label title = new Label()
{
Text = item.Title,
HorizontalOptions = LayoutOptions.Center,
FontSize = item.FontSize,
TextColor = item.TextColor,
Margin = new Thickness( 10, 0 )
};
sl.Children.Add( title );
}
if ( !string.IsNullOrWhiteSpace( item.Description ) )
{
MarkdownView description = new MarkdownView()
{
Markdown = item.Description,
Margin = new Thickness( 10, 0 )
};
sl.Children.Add( description );
}
TapGestureRecognizer tgr = new TapGestureRecognizer()
{
NumberOfTapsRequired = 1
};
tgr.Tapped += ( s, ee ) =>
{
SelectedItem = item;
ItemSelected?.Invoke( sl, new SelectedItemChangedEventArgs( item ) );
};
sl.GestureRecognizers.Add( tgr );
gGrid.Children.Add( frame, x, y );
}
}
} | 33.983051 | 125 | 0.500125 | [
"ECL-2.0"
] | KingdomFirst/Avalanche | App/Avalanche/Avalanche/Components/ListView/CardListView.xaml.cs | 8,022 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Microsoft.AzureIntegrationMigration.Tool.Plugins
{
/// <summary>
/// Defines an interface to host plugins.
/// </summary>
public interface IPluginHost<TPlugin>
{
/// <summary>
/// Resolves the assembly from an already used plugin assembly load context, if possible.
/// </summary>
/// <param name="assemblyName">The assembly to resolve.</param>
/// <returns>The assembly it has resolved to, or null if none found.</returns>
Assembly ResolveAssembly(AssemblyName assemblyName);
/// <summary>
/// Get the loaded plugins.
/// </summary>
/// <returns>A list of loaded plugins.</returns>
IEnumerable<TPlugin> GetPlugins();
/// <summary>
/// Finds the assembly locations for all assemblies containing a plugin interface.
/// </summary>
/// <param name="assemblyPaths">A list of assembly paths containing plugins.</param>
/// <param name="sharedTypes">A list of shared types to be used when loading plugins into custom assembly contexts.</param>
void LoadPlugins(IEnumerable<string> assemblyPaths, Type[] sharedTypes);
}
}
| 37.666667 | 131 | 0.659292 | [
"MIT"
] | 345James/aimtool | src/Microsoft.AzureIntegrationMigration.Tool/Plugins/IPluginHost.cs | 1,356 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Nucleus.WPF
{
/// <summary>
/// Interaction logic for TextComboDialog.xaml
/// </summary>
public partial class TextComboDialog : Window
{
#region Properties
/// <summary>
/// Private backing field for Text property
/// </summary>
private string _Text;
/// <summary>
/// The text entered into the dialog
/// </summary>
public string Text
{
get { return _Text; }
set { _Text = value; }
}
/// <summary>
/// Private backing field for Suggestions property
/// </summary>
private IList<string> _Suggestions = null;
/// <summary>
/// The suggested text values that the user can select via the combobox
/// </summary>
public IList<string> Suggestions
{
get { return _Suggestions; }
set { _Suggestions = value; }
}
#endregion
#region Constructors
public TextComboDialog()
{
InitializeComponent();
LayoutRoot.DataContext = this;
Loaded += (sender, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
public TextComboDialog(IList<string> suggestions) : this()
{
Suggestions = suggestions;
}
public TextComboDialog(string title, IList<string> suggestions) : this(suggestions)
{
Title = title;
}
#endregion
#region Event Handlers
private void OK_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
#endregion
#region Static Methods
/// <summary>
/// Show a TextComboDialog
/// </summary>
/// <param name="title"></param>
/// <param name="text"></param>
/// <param name="suggestions"></param>
/// <returns></returns>
public static bool? Show(string title, ref string text, IList<string> suggestions = null)
{
var dialog = new TextComboDialog(title, suggestions);
dialog.Text = text;
var result = dialog.ShowDialog();
text = dialog.Text;
return result;
}
#endregion
private void Combo_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
DialogResult = true;
Close();
}
}
}
}
| 24.408 | 100 | 0.550311 | [
"MIT"
] | escooo/Nucleus | Nucleus/Nucleus.WPF/TextComboDialog.xaml.cs | 3,053 | C# |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Net;
using DotNetNuke.Application;
using DotNetNuke.Common;
namespace DotNetNuke.Services.Upgrade.Internals
{
public class UpdateService
{
private static String ApplicationVersion
{
get
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
return Globals.FormatVersion(version, "00", 3, "");
}
}
private static String ApplicationName
{
get
{
return DotNetNukeContext.Current.Application.Name;
}
}
public static StreamReader GetLanguageList()
{
String url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx";
url += "?core=" + ApplicationVersion;
url += "&type=Framework";
url += "&name=" + ApplicationName;
StreamReader myResponseReader = GetResponseAsStream(url);
return myResponseReader;
}
public static String GetLanguageDownloadUrl(String cultureCode)
{
String url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx";
url += "?core=" + ApplicationVersion;
url += "&type=Framework";
url += "&name=" + ApplicationName;
url += "&culture=" + cultureCode;
StreamReader myResponseReader = GetResponseAsStream(url);
string downloadUrl = myResponseReader.ReadToEnd();
return downloadUrl;
}
private static StreamReader GetResponseAsStream(string url)
{
//creating the proxy for the service call using the HttpWebRequest class
var webReq = (HttpWebRequest) WebRequest.Create(url);
//Set the method/action type
webReq.Method = "GET";
//We use form contentType
webReq.ContentType = "text/xml; charset=utf-8";
//Get the response handle, we have no true response yet!
var webResp = (HttpWebResponse) webReq.GetResponse();
//Now, we read the response (the string), and output it.
Stream myResponse = webResp.GetResponseStream();
//read the stream into streamreader
var myResponseReader = new StreamReader(myResponse);
return myResponseReader;
}
}
} | 36.868687 | 116 | 0.647671 | [
"MIT"
] | Abrahamberg/Dnn.Platform | DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs | 3,653 | C# |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Eneter.Messaging.Diagnostic;
namespace Eneter.Messaging.DataProcessing.Serializing
{
/// <summary>
/// Serializer digitaly signing data.
/// </summary>
/// <remarks>
/// Serialization:
/// <ol>
/// <li>Incoming data is serialized by underlying serializer (e.g. XmlStringSerializer)</li>
/// <li>SHA1 hash is calculated from the serialized data.</li>
/// <li>The hash is encrypted with RSA using the private key.</li>
/// <li>The serialized data consists of serialized data, encoded hash (signature) and public certificate of the signer.</li>
/// </ol>
/// Deserialization:
/// <ol>
/// <li>The public certificate is taken from serialized data and verified. (you can provide your own verification)</li>
/// <li>SHA1 hash is calculated from serialized data.</li>
/// <li>Encrypted hash (signature) is decrypted by public key taken from the certificate.</li>
/// <li>If the decrypted hash is same as calculated one the data is ok.</li>
/// <li>Data is deserialized by the underlying serializer and returned.</li>
/// </ol>
/// <example>
/// Example shows how to serialize/deserialize data using digital signature.
/// <code>
/// // Get the certificate containing public and private keys. E.g. from the file.
/// X509Certificate2 aSignerCertificate = new X509Certificate2("c:/MyCertificate.pfx", "mypassword");
///
/// // Create the serializer.
/// RsaDigitalSignatureSerializer aSerializer = new RsaDigitalSignatureSerializer(aSignerCertificate);
///
/// // Serialize data.
/// // (serialized data will contain digital signature and signer's public certificate)
/// object aSerializedData = aSerializer.Serialize<string>("Hello world.");
///
/// // Deserialize data.
/// string aDeserializedData = aSerializer.Deserialize<string>(aSerializedData);
/// </code>
/// </example>
/// </remarks>
public class RsaDigitalSignatureSerializer : ISerializer
{
const string OID_RSA = "1.2.840.113549.1.1.1";
const string OID_DSA = "1.2.840.10040.4.1";
const string OID_ECC = "1.2.840.10045.2.1";
private ISerializer myUnderlyingSerializer;
private EncoderDecoder myEncoderDecoder = new EncoderDecoder();
private byte[] myPublicCertificate;
private X509Certificate2 mySignerCertificate;
private Func<X509Certificate2, bool> myVerifySignerCertificate;
/// <summary>
/// Constructs the serializer with default parameters.
/// </summary>
/// <remarks>
/// It uses XmlStringSerializer as the underlying serializer and it uses default X509Certificate2.Verify() method to verify
/// the public certificate.
/// </remarks>
/// <param name="signerCertificate">signer certificate containing public and also private part.
/// The key from the private part is used to sign data during the serialization.<br/>
/// The public certificate is attached to serialized data.<br/>
/// If the parameter signerCertificate is null then the serializer can be used only for deserialization.
/// </param>
public RsaDigitalSignatureSerializer(X509Certificate2 signerCertificate)
: this(signerCertificate, null, new XmlStringSerializer())
{
}
/// <summary>
/// Constructs the serializer with custom parameters.
/// </summary>
/// <param name="signerCertificate">signer certificate containing public and also private part.
/// The key from the private part is used to sign data during the serialization.<br/>
/// The public certificate is attached to serialized data.<br/>
/// If the parameter certificate is null then the serializer can be used only for deserialization.
/// </param>
/// <param name="verifySignerCertificate">callback to verify the certificate. If null then default X509Certificate2.Verify() is used.</param>
/// <param name="underlyingSerializer">underlying serializer that will be used to serialize/deserialize data</param>
public RsaDigitalSignatureSerializer(X509Certificate2 signerCertificate, Func<X509Certificate2, bool> verifySignerCertificate, ISerializer underlyingSerializer)
{
using (EneterTrace.Entering())
{
mySignerCertificate = signerCertificate;
myPublicCertificate = signerCertificate.Export(X509ContentType.Cert);
myVerifySignerCertificate = verifySignerCertificate ?? VerifySignerCertificate;
myUnderlyingSerializer = underlyingSerializer;
}
}
/// <summary>
/// Serializes data.
/// </summary>
/// <typeparam name="_T">data type to be serialized</typeparam>
/// <param name="dataToSerialize">data to be serialized</param>
/// <returns>serialized data</returns>
public object Serialize<_T>(_T dataToSerialize)
{
using (EneterTrace.Entering())
{
if (mySignerCertificate == null)
{
throw new InvalidOperationException(TracedObject + "failed to serialize data. The signer certificate is null and thus the serializer can be used only for deserialization.");
}
byte[][] aSignedData = new byte[3][];
using (MemoryStream aSerializedDataStream = new MemoryStream())
{
// Serialize incoming data using underlying serializer.
object aSerializedData = myUnderlyingSerializer.Serialize<_T>(dataToSerialize);
myEncoderDecoder.Encode(aSerializedDataStream, aSerializedData);
aSignedData[0] = aSerializedDataStream.ToArray();
}
// Calculate hash from serialized data.
SHA1Managed aSha1 = new SHA1Managed();
byte[] aHash = aSha1.ComputeHash(aSignedData[0]);
// Sign the hash.
// Note: The signature is the hash encrypted with the private key.
#if NET35 || NET40
RSACryptoServiceProvider aPrivateKey = (RSACryptoServiceProvider)mySignerCertificate.PrivateKey;
aSignedData[2] = aPrivateKey.SignHash(aHash, CryptoConfig.MapNameToOID("SHA1"));
#else
switch (mySignerCertificate.PublicKey.Oid.Value)
{
case OID_RSA:
{
var privateKey = mySignerCertificate.GetRSAPrivateKey();
aSignedData[2] = privateKey.SignHash(aHash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
break;
}
#if !NETSTANDARD2_0
case OID_DSA:
{
var privateKey = mySignerCertificate.GetDSAPrivateKey();
aSignedData[2] = privateKey.SignData(aHash, HashAlgorithmName.SHA1);
break;
}
#endif
case OID_ECC:
{
var privateKey = mySignerCertificate.GetECDsaPrivateKey();
aSignedData[2] = privateKey.SignHash(aHash);
break;
}
}
#endif
// Store the public certificate.
aSignedData[1] = myPublicCertificate;
// Serialize data together with the signature.
object aSerializedSignedData = myUnderlyingSerializer.Serialize<byte[][]>(aSignedData);
return aSerializedSignedData;
}
}
/// <summary>
/// Deserializes data.
/// </summary>
/// <typeparam name="_T">data type to be deserialized</typeparam>
/// <param name="serializedData">serialized data</param>
/// <returns>deserialized data type</returns>
public _T Deserialize<_T>(object serializedData)
{
using (EneterTrace.Entering())
{
// Deserialize data containing the signature.
byte[][] aSignedData = myUnderlyingSerializer.Deserialize<byte[][]>(serializedData);
// Verify the signer certificate. If we trust the certificate.
X509Certificate2 aCertificate = new X509Certificate2(aSignedData[1]);
if (!myVerifySignerCertificate(aCertificate))
{
throw new InvalidOperationException(TracedObject + "failed to deserialize data because the verification of signer certificate failed.");
}
// Calculate the hash.
SHA1Managed aSha1 = new SHA1Managed();
byte[] aHash = aSha1.ComputeHash(aSignedData[0]);
// Verify the signature.
#if NET35 || NET40
RSACryptoServiceProvider aCryptoServiceProvider = (RSACryptoServiceProvider)aCertificate.PublicKey.Key;
if (!aCryptoServiceProvider.VerifyHash(aHash, CryptoConfig.MapNameToOID("SHA1"), aSignedData[2]))
{
throw new InvalidOperationException(TracedObject + "failed to deserialize data because the signature verification failed.");
}
#else
bool isVerified = false;
switch (mySignerCertificate.PublicKey.Oid.Value)
{
case OID_RSA:
{
var publicKey = mySignerCertificate.GetRSAPublicKey();
isVerified = publicKey.VerifyHash(aHash, aSignedData[2], HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
break;
}
#if !NETSTANDARD2_0
case OID_DSA:
{
var publicKey = mySignerCertificate.GetDSAPublicKey();
isVerified = publicKey.VerifyData(aHash, aSignedData[2], HashAlgorithmName.SHA1);
break;
}
#endif
case OID_ECC:
{
var publicKey = mySignerCertificate.GetECDsaPublicKey();
isVerified = publicKey.VerifyHash(aHash, aSignedData[2]);
break;
}
}
if (!isVerified)
{
throw new InvalidOperationException(TracedObject + "failed to deserialize data because the signature verification failed.");
}
#endif
using (MemoryStream aDeserializedDataStream = new MemoryStream(aSignedData[0], 0, aSignedData[0].Length))
{
object aDecodedData = myEncoderDecoder.Decode(aDeserializedDataStream);
_T aDeserializedData = myUnderlyingSerializer.Deserialize<_T>(aDecodedData);
return aDeserializedData;
}
}
}
private bool VerifySignerCertificate(X509Certificate2 signerCertificate)
{
return signerCertificate.Verify();
}
private string TracedObject { get { return GetType().Name + ' '; } }
}
} | 47.196 | 194 | 0.581151 | [
"MIT"
] | ng-eneter/eneter-net | EneterMessaging/EneterMessagingFramework/DataProcessing/Serializing/RsaDigitalSignatureSerializer.cs | 11,801 | C# |
using System;
namespace UrbanBlimp.Apple
{
public class GetRegistrationService
{
public IRequestBuilder RequestBuilder;
public void Execute(GetRegistrationRequest request, Action<GetRegistrationResponse> responseCallback, Action<Exception> exceptionCallback)
{
var webRequest = RequestBuilder.Build("https://go.urbanairship.com/api/device_tokens/" + request.DeviceToken);
webRequest.Method = "Get";
webRequest.ContentType = "application/json";
var asyncRequest = new AsyncRequest
{
ReadFromResponse = stream => responseCallback(GetRegistrationResponseDeSerializer.DeSerialize(stream)),
Request = webRequest,
ExceptionCallback = exceptionCallback,
};
asyncRequest.Execute();
}
}
} | 33.68 | 146 | 0.663895 | [
"MIT"
] | farhadbheekoo/UrbanBlimp | UrbanBlimp/Apple/Registration/GetRegistrationService.cs | 842 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddInt32()
{
var test = new SimpleBinaryOpTest__AddInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static SimpleBinaryOpTest__AddInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AddInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Add(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Add(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Add(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddInt32();
var result = Sse2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| 41.625378 | 146 | 0.569531 | [
"MIT"
] | ruben-ayrapetyan/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse2/Add.Int32.cs | 13,778 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin;
using NSwag.SwaggerGeneration;
namespace NSwag.AspNet.Owin.Middlewares
{
internal class SwaggerUiIndexMiddleware<T> : OwinMiddleware
where T : SwaggerGeneratorSettings, new()
{
private readonly string _indexPath;
private readonly SwaggerUiSettingsBase<T> _settings;
private readonly string _resourcePath;
public SwaggerUiIndexMiddleware(OwinMiddleware next, string indexPath, SwaggerUiSettingsBase<T> settings, string resourcePath)
: base(next)
{
_indexPath = indexPath;
_settings = settings;
_resourcePath = resourcePath;
}
public override async Task Invoke(IOwinContext context)
{
if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _indexPath.Trim('/'), StringComparison.OrdinalIgnoreCase))
{
var stream = typeof(SwaggerUiIndexMiddleware<T>).Assembly.GetManifestResourceStream(_resourcePath);
using (var reader = new StreamReader(stream))
{
context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
context.Response.Write(_settings.TransformHtml(reader.ReadToEnd()));
}
}
else
await Next.Invoke(context);
}
}
} | 37.8 | 159 | 0.628968 | [
"MIT"
] | Inzanit/NSwag | src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs | 1,512 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPattern.Observer2
{
public class Son : IObserver
{
private readonly IList<IObserver> _observers = new List<IObserver>();
public void AddObserver(IObserver observer)
{
_observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
_observers.Remove(observer);
}
public void Update()
{
Wakeup();
}
public void Wakeup()
{
Console.WriteLine("既而儿醒,大啼");
foreach (var observer in _observers)
{
observer.Update();
}
}
}
}
| 20.388889 | 77 | 0.53406 | [
"MIT"
] | ZShijun/DesignPattern | src/Patterns/17. Observer/DesignPattern.Observer2/Son.cs | 750 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Threading.Tasks;
using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.Log;
namespace Squidex.Domain.Apps.Entities.Backup.Helpers
{
public static class Safe
{
public static async Task DeleteAsync(IBackupArchiveLocation backupArchiveLocation, string id, ISemanticLog log)
{
try
{
await backupArchiveLocation.DeleteArchiveAsync(id);
}
catch (Exception ex)
{
log.LogError(ex, id, (logOperationId, w) => w
.WriteProperty("action", "deleteArchive")
.WriteProperty("status", "failed")
.WriteProperty("operationId", logOperationId));
}
}
public static async Task DeleteAsync(IAssetStore assetStore, string id, ISemanticLog log)
{
try
{
await assetStore.DeleteAsync(id, 0, null);
}
catch (Exception ex)
{
log.LogError(ex, id, (logOperationId, w) => w
.WriteProperty("action", "deleteBackup")
.WriteProperty("status", "failed")
.WriteProperty("operationId", logOperationId));
}
}
public static async Task CleanupRestoreErrorAsync(BackupHandler handler, Guid appId, Guid id, ISemanticLog log)
{
try
{
await handler.CleanupRestoreErrorAsync(appId);
}
catch (Exception ex)
{
log.LogError(ex, id.ToString(), (logOperationId, w) => w
.WriteProperty("action", "cleanupRestore")
.WriteProperty("status", "failed")
.WriteProperty("operationId", logOperationId));
}
}
}
}
| 35.571429 | 119 | 0.489067 | [
"MIT"
] | Avd6977/squidex | src/Squidex.Domain.Apps.Entities/Backup/Helpers/Safe.cs | 2,243 | C# |
using Mapster;
using Meiam.System.Hostd.Authorization;
using Meiam.System.Hostd.Extensions;
using Meiam.System.Interfaces;
using Meiam.System.Model;
using Meiam.System.Model.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Meiam.System.Hostd.Controllers.Basic
{
/// <summary>
/// 工厂定义
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class FactoryController : BaseController
{
/// <summary>
/// 日志管理接口
/// </summary>
private readonly ILogger<FactoryController> _logger;
/// <summary>
/// 会话管理接口
/// </summary>
private readonly TokenManager _tokenManager;
/// <summary>
/// 工厂定义接口
/// </summary>
private readonly IBaseFactoryService _factoryService;
/// <summary>
/// 数据关系接口
/// </summary>
private readonly ISysDataRelationService _dataRelationService;
public FactoryController(ILogger<FactoryController> logger, TokenManager tokenManager, IBaseFactoryService factoryService, ISysDataRelationService dataRelationService)
{
_logger = logger;
_tokenManager = tokenManager;
_factoryService = factoryService;
_dataRelationService = dataRelationService;
}
/// <summary>
/// 查询工厂定义列表
/// </summary>
/// <returns></returns>
[HttpPost]
[Authorization]
public IActionResult Query([FromBody] FactoryQueryDto parm)
{
var response = _factoryService.QueryFactoryPages(parm);
return toResponse(response);
}
/// <summary>
/// 根据 Id 查询工厂定义
/// </summary>
/// <param name="id">编码</param>
/// <returns></returns>
[HttpGet]
[Authorization]
public IActionResult Get(string id = null)
{
if (string.IsNullOrEmpty(id))
{
return toResponse(StatusCodeType.Error, "工厂 Id 不能为空");
}
return toResponse(_factoryService.GetFactory(id));
}
/// <summary>
/// 查询所有工厂定义
/// </summary>
/// <param name="enable">是否启用(不传返回所有)</param>
/// <returns></returns>
[HttpGet]
[Authorization]
public IActionResult GetAll(bool? enable = null)
{
return toResponse(_factoryService.GetAllFactory(enable));
}
/// <summary>
/// 添加工厂定义
/// </summary>
/// <returns></returns>
[HttpPost]
[Authorization(Power = "PRIV_FACTORY_CREATE")]
public IActionResult Create([FromBody] FactoryCreateDto parm)
{
try
{
var factory = parm.Adapt<Base_Factory>().ToCreate(_tokenManager.GetSessionInfo());
if (_factoryService.Any(m => m.FactoryNo == parm.FactoryNo))
{
return toResponse(StatusCodeType.Error, $"添加工厂编码 {parm.FactoryNo} 已存在,不能重复!");
}
//从 Dto 映射到 实体
_dataRelationService.BeginTran();
var response = _factoryService.Add(factory);
//插入关系表
_dataRelationService.Add(new Sys_DataRelation
{
ID = GetGUID,
Form = factory.ID,
To = parm.CompanyUID,
Type = DataRelationType.Factory_To_Company.ToString()
});
_dataRelationService.CommitTran();
return toResponse(response);
}
catch (Exception)
{
_dataRelationService.RollbackTran();
throw;
}
}
/// <summary>
/// 更新工厂定义
/// </summary>
/// <returns></returns>
[HttpPost]
[Authorization(Power = "PRIV_FACTORY_UPDATE")]
public IActionResult Update([FromBody] FactoryUpdateDto parm)
{
if (_factoryService.Any(m => m.FactoryNo == parm.FactoryNo && m.ID != parm.ID))
{
return toResponse(StatusCodeType.Error, $"更新工厂编码 {parm.FactoryNo} 已存在,不能重复!");
}
try
{
_dataRelationService.BeginTran();
var userSession = _tokenManager.GetSessionInfo();
var response = _factoryService.Update(m => m.ID == parm.ID, m => new Base_Factory()
{
FactoryNo = parm.FactoryNo,
FactoryName = parm.FactoryName,
Enable = parm.Enable,
Remark = parm.Remark,
UpdateID = userSession.UserID,
UpdateName = userSession.UserName,
UpdateTime = DateTime.Now
});
//删除关系表
_dataRelationService.Delete(m => m.Form == parm.ID && m.Type == DataRelationType.Factory_To_Company.ToString());
//插入关系表
_dataRelationService.Add(new Sys_DataRelation
{
ID = GetGUID,
Form = parm.ID,
To = parm.CompanyUID,
Type = DataRelationType.Factory_To_Company.ToString()
});
_dataRelationService.CommitTran();
return toResponse(response);
}
catch (Exception)
{
_dataRelationService.RollbackTran();
throw;
}
}
/// <summary>
/// 删除工厂定义
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorization(Power = "PRIV_FACTORY_DELETE")]
public IActionResult Delete(string id)
{
if (string.IsNullOrEmpty(id))
{
return toResponse(StatusCodeType.Error, "删除工厂 Id 不能为空");
}
if (_dataRelationService.Any(m => m.To == id))
{
return toResponse(StatusCodeType.Error, "该工厂已被关联,无法删除,若要请先删除关联");
}
try
{
_dataRelationService.BeginTran();
_dataRelationService.Delete(m => m.Form == id && m.Type == DataRelationType.Factory_To_Company.ToString());
var response = _factoryService.Delete(id);
_dataRelationService.CommitTran();
return toResponse(response);
}
catch (Exception)
{
_dataRelationService.RollbackTran();
throw;
}
}
}
}
| 30.138393 | 175 | 0.518294 | [
"Apache-2.0"
] | HaiLinWang/Meiam.System | Meiam.System.Hostd/Controllers/Basic/FactoryController.cs | 7,093 | 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("Perspective")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Perspective")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.321429 | 98 | 0.709283 | [
"MIT"
] | Macrotitech/WPF-3d-source | Ch04/Perspective/Properties/AssemblyInfo.cs | 2,373 | C# |
namespace GooglePlayGames.BasicApi.Events
{
internal class Event : IEvent
{
private string mId;
private string mName;
private string mDescription;
private string mImageUrl;
private ulong mCurrentCount;
private EventVisibility mVisibility;
internal Event(string id, string name, string description, string imageUrl,
ulong currentCount, EventVisibility visibility)
{
mId = id;
mName = name;
mDescription = description;
mImageUrl = imageUrl;
mCurrentCount = currentCount;
mVisibility = visibility;
}
public string Id
{
get { return mId; }
}
public string Name
{
get { return mName; }
}
public string Description
{
get { return mDescription; }
}
public string ImageUrl
{
get { return mImageUrl; }
}
public ulong CurrentCount
{
get { return mCurrentCount; }
}
public EventVisibility Visibility
{
get { return mVisibility; }
}
}
}
| 22.537037 | 83 | 0.525062 | [
"Apache-2.0"
] | ToufuSekka/play-games-plugin-for-unity | Assets/Public/GooglePlayGames/com.google.play.games/Runtime/Scripts/BasicApi/Events/Event.cs | 1,219 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Views;
using Android.Widget;
using Xamarin.RisePlugin.Droid.Floatingactionbutton;
using Xamarin.RisePlugin.Floatingactionbutton;
using Xamarin.RisePlugin.Floatingactionbutton.Enums;
using Orientation = Android.Widget.Orientation;
[assembly: Xamarin.Forms.DependencyAttribute(
typeof(Xamarin.RisePlugin.Droid.Floatingactionbutton.COAFloatingactionbutton))]
namespace Xamarin.RisePlugin.Droid.Floatingactionbutton
{
public class COAFloatingactionbutton : IFloatActionButton
{
Context context;
FloatingActionButton fltbutton;
StackActionOrientation _stackActionOrientation;
public StackActionOrientation ActionOrientation
{
get { return _stackActionOrientation; }
set
{
if (_stackActionOrientation == value)
return;
_stackActionOrientation = value;
if (linearLayout != null)
{
RelativeLayout.LayoutParams lrparam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
lrparam.AddRule(LayoutRules.AlignParentBottom);
if (ActionOrientation == StackActionOrientation.Right)
lrparam.AddRule(LayoutRules.AlignParentEnd);
else if (ActionOrientation == StackActionOrientation.Center)
lrparam.AddRule(LayoutRules.CenterHorizontal);
else if (ActionOrientation == StackActionOrientation.Left)
lrparam.AddRule(LayoutRules.AlignParentStart);
lrparam.SetMargins(0, (int)MainButtonView.Margin.Top, 0, (int)MainButtonView.Margin.Bottom);
linearLayout.LayoutParameters = lrparam;
HideSubView(0);
ShowSubView(0);
}
}
}
ActionOpeningType _openingType;
public ActionOpeningType OpeningType
{
get
{
return _openingType;
}
set
{
_openingType = value;
if (linearLayout != null)
{
if (value == ActionOpeningType.VerticalTop || value == ActionOpeningType.VerticalBottom)
linearLayout.Orientation = Orientation.Vertical;
else
linearLayout.Orientation = Orientation.Horizontal;
}
}
}
public ActionButtonView MainButtonView { get; set; }
public IList<ActionButtonView> SubViews { get; set; }
public bool IsSubShowing { get; set; }
bool isShowing;
bool isProgress;
public bool IsShowing
{
get
{
return isShowing;
}
set
{
if (value)
{
context = Application.Context;
context.SetTheme(Resource.Style.MainTheme);
linearLayout = new LinearLayout(context);
if (OpeningType == ActionOpeningType.VerticalTop || OpeningType == ActionOpeningType.VerticalBottom)
linearLayout.Orientation = Orientation.Vertical;
else
linearLayout.Orientation = Orientation.Horizontal;
fltbutton = new CustomFloatingactionbutton(context, MainButtonView, SubViewSpacing);
MainButtonView.PropertyChanged += MainButtonView_PropertyChanged;
linearLayout.AddView(fltbutton);
linearLayout.LayoutParameters = SetMainButtonLayout();
RootView.View.AddView(linearLayout);
fltbutton.Click += Fltbutton_Click;
}
else
{
HideSubView(10);
for (int i = 0; i < linearLayout.ChildCount; i++)
{
linearLayout.RemoveViewAt(0);
}
((RelativeLayout)linearLayout.Parent).RemoveView(linearLayout);
fltbutton = null;
linearLayout = null;
context = null;
//SubViews = null;
}
isShowing = value;
}
}
private void Fltbutton_Click(object sender, EventArgs e)
{
MainButtonView.ClickAction();
}
public int CircleAngle { get; set; }
public int SubViewSpacing { get; set; }
public COAFloatingactionbutton()
{
if (SubViews == null)
SubViews = new List<ActionButtonView>();
CircleAngle = 300;
SubViewSpacing = 10;
}
public async Task<bool> ShowSubView(int Duration = 150)
{
try
{
if (SubViews.Count > 0)
{
if (!IsSubShowing && IsShowing && !isProgress)
{
isProgress = true;
if (OpeningType != ActionOpeningType.Circle)
foreach (var item in SubViews)
{
var Btnn = new CustomFloatingactionbutton(context, item, SubViewSpacing);
if (OpeningType == ActionOpeningType.VerticalTop || OpeningType == ActionOpeningType.HorizontalLeft)
linearLayout.AddView(Btnn, 0);
else
linearLayout.AddView(Btnn);
//Animation animate = AnimationUtils.LoadAnimation(context, Resource.Animation.EnterFromLeft);
//Btnn.StartAnimation(animate);
switch (OpeningType)
{
case ActionOpeningType.HorizontalLeft:
Btnn.Animate().TranslationX(-SubViewSpacing).SetDuration(Duration);
break;
case ActionOpeningType.HorizontalRight:
Btnn.Animate().TranslationX(+SubViewSpacing).SetDuration(Duration);
break;
case ActionOpeningType.VerticalTop:
Btnn.Animate().TranslationY(-SubViewSpacing).SetDuration(Duration);
break;
case ActionOpeningType.VerticalBottom:
Btnn.Animate().TranslationY(+SubViewSpacing).SetDuration(Duration);
break;
default:
break;
}
await Task.Delay(Duration);
if (OpeningType == ActionOpeningType.HorizontalLeft || OpeningType == ActionOpeningType.HorizontalRight)
Btnn.Animate().TranslationX(0).SetDuration(Duration);
else
Btnn.Animate().TranslationY(0).SetDuration(Duration);
Btnn.Click += (sender, e) => { item.ClickAction(); };
}
else
{
var RL = new FrameLayout(context);
var metrics = Resources.System.DisplayMetrics;
var ly = new RelativeLayout.LayoutParams(metrics.WidthPixels, metrics.HeightPixels);
ly.AddRule(LayoutRules.AlignParentBottom);
if (ActionOrientation == StackActionOrientation.Right)
ly.AddRule(LayoutRules.AlignParentEnd);
else if (ActionOrientation == StackActionOrientation.Center)
{
ly.AddRule(LayoutRules.CenterHorizontal);
ly.Width *= 2;
}
else if (ActionOrientation == StackActionOrientation.Right)
ly.AddRule(LayoutRules.AlignParentStart);
RL.LayoutParameters = ly;
RootView.View.AddView(RL, 1);
float AndroidCircle = (float)(CircleAngle * 2.5);
if (ActionOrientation == StackActionOrientation.Center)
{
if (SubViews.Count == 5)
SetAngel(SubViews, AndroidCircle, RL, 225, Duration);
else if (SubViews.Count == 4)
SetAngel(SubViews, AndroidCircle, RL, 240, Duration);
else if (SubViews.Count == 6)
SetAngel(SubViews, AndroidCircle, RL, 220, Duration);
else if (SubViews.Count == 3)
SetAngel(SubViews, AndroidCircle, RL, 270, Duration);
else if (SubViews.Count == 2)
SetAngel(SubViews, AndroidCircle, RL, 360, Duration);
else if (SubViews.Count >= 7)
SetAngel(SubViews, AndroidCircle, RL, 215, Duration);
}
else
SetAngel(SubViews, AndroidCircle, RL, 110, Duration);
}
isProgress = false;
IsSubShowing = true;
lastOpeningType = OpeningType;
}
}
return true;
}
catch (Exception ex)
{
throw new FileNotFoundException("SubViews Null", ex);
}
}
public void SetAngel(IList<ActionButtonView> Lst, float radius, FrameLayout rl, int Degress, int Duration)
{
var degrees = Degress / Lst.Count;
int i = 0;
foreach (var item in Lst)
{
var hOffset = radius * Math.Cos(i * degrees * 3.14 / 180);
var vOffset = radius * Math.Sin(i * degrees * 3.14 / 180);
var btn = new CustomFloatingactionbutton(context, item, SubViewSpacing);
btn.Alpha = 0;
var ly = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
btn.CustomSize = (int)(item.HeightRequest * 2.5);
if (ActionOrientation == StackActionOrientation.Right)
ly.Gravity = GravityFlags.Right | GravityFlags.Bottom;
else if (ActionOrientation == StackActionOrientation.Center)
ly.Gravity = GravityFlags.Center | GravityFlags.Bottom;
else if (ActionOrientation == StackActionOrientation.Left)
ly.Gravity = GravityFlags.Left | GravityFlags.Bottom;
var mainbuttonmargins = (LinearLayout.LayoutParams)linearLayout.GetChildAt(0).LayoutParameters;
var LinearLayoutprm = (RelativeLayout.LayoutParams)linearLayout.LayoutParameters;
ly.SetMargins(mainbuttonmargins.LeftMargin, 0, mainbuttonmargins.RightMargin, LinearLayoutprm.BottomMargin == 0 ? 30 : LinearLayoutprm.BottomMargin);
//ly.AddRule(LayoutRules.AlignParentBottom);
btn.LayoutParameters = ly;
if (ActionOrientation == StackActionOrientation.Left)
btn.Animate().TranslationX(-(float)(-1 * hOffset)).SetDuration(Duration);
else
btn.Animate().TranslationX((float)(-1 * hOffset)).SetDuration(Duration);
btn.Animate().TranslationY(((float)(-1 * vOffset))).SetDuration(Duration);
btn.Animate().Alpha(1).SetDuration(Duration);
btn.Click += (sender, e) =>
{
item.ClickAction();
};
//btn.SetIcon(item.Icon);
rl.AddView(btn);
i++;
}
}
ActionOpeningType lastOpeningType;
public async Task<bool> HideSubView(int Duration = 150)
{
try
{
if (IsSubShowing && IsShowing && !isProgress)
{
isProgress = true;
var count = linearLayout.ChildCount - 1;
for (int i = 0; i < count; i++)
{
if (lastOpeningType == ActionOpeningType.VerticalTop || lastOpeningType == ActionOpeningType.HorizontalLeft)
{
linearLayout.GetChildAt(0).Animate().Alpha(0).SetDuration(Duration);
await Task.Delay(Duration);
linearLayout.RemoveViewAt(0);
}
else
{
linearLayout.GetChildAt(1).Animate().Alpha(0).SetDuration(Duration);
await Task.Delay(Duration);
linearLayout.RemoveViewAt(1);
}
IsSubShowing = false;
}
if (count == 0 && lastOpeningType == ActionOpeningType.Circle)
{
var RL = (FrameLayout)RootView.View.GetChildAt(1);
for (int i = 0; i < RL.ChildCount; i++)
{
var btn = (FloatingActionButton)RL.GetChildAt(i);
btn.Animate().TranslationX(0).SetDuration(Duration);
btn.Animate().TranslationY(0).SetDuration(Duration);
btn.Animate().Alpha(0).SetDuration(Duration);
}
await Task.Delay(Duration);
for (int i = 1; i < RootView.View.ChildCount; i++)
{
if (RootView.View.GetChildAt(i) is FrameLayout)
RootView.View.RemoveViewAt(i);
}
IsSubShowing = false;
}
isProgress = false;
}
return true;
}
catch (Exception ex)
{
throw new FileNotFoundException("Some wrong prog.", ex);
}
}
LinearLayout linearLayout;
public void Open()
{
if (!IsShowing)
IsShowing = true;
}
public void Close()
{
if (IsShowing)
IsShowing = false;
}
RelativeLayout.LayoutParams SetMainButtonLayout()
{
RelativeLayout.LayoutParams lrparam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
lrparam.AddRule(LayoutRules.AlignParentBottom);
if (ActionOrientation == StackActionOrientation.Right)
lrparam.AddRule(LayoutRules.AlignParentEnd);
else if (ActionOrientation == StackActionOrientation.Center)
lrparam.AddRule(LayoutRules.CenterHorizontal);
else if (ActionOrientation == StackActionOrientation.Left)
lrparam.AddRule(LayoutRules.AlignParentStart);
lrparam.SetMargins(0, (int)MainButtonView.Margin.Top, 0, (int)MainButtonView.Margin.Bottom);
return lrparam;
}
private void MainButtonView_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MainButtonView.Margin))
{
linearLayout.LayoutParameters = SetMainButtonLayout();
HideSubView(0);
ShowSubView(0);
}
}
}
} | 44.038363 | 166 | 0.481851 | [
"MIT"
] | Druffl3/Xamarin.RisePlugin.Floatingactionbutton | Xamarin.RisePlugin.Droid.Floatingactionbutton/COAFloatingactionbutton.cs | 17,221 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PacketCapturesOperations operations.
/// </summary>
internal partial class PacketCapturesOperations : IServiceOperations<NetworkManagementClient>, IPacketCapturesOperations
{
/// <summary>
/// Initializes a new instance of the PacketCapturesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PacketCapturesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PacketCaptureResult>> CreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<PacketCaptureResult> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a packet capture session by name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureResult>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> GetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<PacketCaptureQueryStatusResult> _response = await BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists all packet capture sessions within the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<PacketCaptureResult>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<PacketCaptureResult>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PacketCaptureResult>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureResult>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> BeginGetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2019-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginGetStatus", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureQueryStatusResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 47.66867 | 329 | 0.580201 | [
"MIT"
] | AzureMentor/azure-sdk-for-net | sdk/network/Microsoft.Azure.Management.Network/src/Generated/PacketCapturesOperations.cs | 63,447 | C# |
using Android.App;
using Android.Content;
using AndroidX.AppCompat.App;
namespace TemploBelen.Prism.Droid
{
[Activity(Theme = "@style/MainTheme.Splash",
MainLauncher = true,
NoHistory = true)]
public class SplashActivity : AppCompatActivity
{
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
}
| 25.15 | 81 | 0.624254 | [
"MIT"
] | rubberydev/templobelenApp | TemploBelen.Prism/TemploBelen.Prism/TemploBelen.Prism.Android/SplashActivity.cs | 503 | C# |
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using DockerSdk.Containers.Events;
using DockerSdk.Networks;
namespace DockerSdk.Containers
{
/// <summary>
/// Represents a Docker container.
/// </summary>
internal class Container : IContainer
{
internal Container(DockerClient client, ContainerFullId id)
{
_client = client;
Id = id;
}
/// <inheritdoc/>
public ContainerFullId Id { get; }
private readonly DockerClient _client;
/// <inheritdoc/>
public Task AttachNetwork(string network, CancellationToken ct = default)
=> AttachNetwork(NetworkReference.Parse(network), new(), ct);
/// <inheritdoc/>
public Task AttachNetwork(NetworkReference network, CancellationToken ct = default)
=> AttachNetwork(network, new(), ct);
/// <inheritdoc/>
public Task AttachNetwork(string network, AttachNetworkOptions options, CancellationToken ct = default)
=> AttachNetwork(NetworkReference.Parse(network), options, ct);
/// <inheritdoc/>
public async Task AttachNetwork(NetworkReference network, AttachNetworkOptions options, CancellationToken ct = default)
{
if (network is null)
throw new ArgumentNullException(nameof(network));
if (options is null)
throw new ArgumentNullException(nameof(options));
await Network.AttachInnerAsync(_client, Id, network, options, ct).ConfigureAwait(false);
}
/// <inheritdoc/>
public Task<IContainerInfo> GetDetailsAsync(CancellationToken ct)
=> GetDetailsAsync(ct);
/// <inheritdoc/>
public Task StartAsync(CancellationToken ct = default)
=> _client.Containers.StartAsync(Id, ct);
/// <summary>
/// Subscribes to events from this container.
/// </summary>
/// <param name="observer">An object to observe the events.</param>
/// <returns>
/// An <see cref="IDisposable"/> representing the subscription. Disposing this unsubscribes and releases
/// resources.
/// </returns>
public IDisposable Subscribe(IObserver<ContainerEvent> observer)
=> _client.Containers.Where(ev => ev.ContainerId == Id).Subscribe(observer);
}
}
| 34.885714 | 127 | 0.633497 | [
"MIT"
] | Emdot/DockerSdk | DockerSdk/Containers/Container.cs | 2,444 | 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("Phun.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Phun.Tests")]
[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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6fb4a314-f882-4141-adda-e1ab6bbf2bce")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | noogen/phuncms | src/Phun.Tests/Properties/AssemblyInfo.cs | 1,396 | C# |
using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
[CorpseName( "a dryad corpse" )]
public class DryadA : BaseCreature
{
public override bool InitialInnocent{ get{ return true; } }
[Constructable]
public DryadA() : base( AIType.AI_Mage, FightMode.Evil, 10, 1, 0.2, 0.4 )
{
Name = "a Dryad";
Body = 266;
BaseSoundID = 0x467;
SetStr( 135, 150 );
SetDex( 153, 166 );
SetInt( 253, 281 );
SetHits( 302, 314 );
SetStam( 153, 166 );
SetMana( 253, 281 );
SetDamage( 11, 20 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 41, 50 );
SetResistance( ResistanceType.Fire, 15, 24 );
SetResistance( ResistanceType.Cold, 40, 45 );
SetResistance( ResistanceType.Poison, 30, 40 );
SetResistance( ResistanceType.Energy, 25, 32 );
SetSkill( SkillName.Wrestling, 71.5, 77.8 );
SetSkill( SkillName.Tactics, 70.1, 77.3 );
SetSkill( SkillName.MagicResist, 100.7, 118.8 );
SetSkill( SkillName.Magery, 72.1, 77.3 );
SetSkill( SkillName.EvalInt, 71.0, 79.5 );
SetSkill( SkillName.Meditation, 80.1, 89.7 );
}
public override void GenerateLoot()
{
AddLoot( LootPack.AosRich, 3 );
}
public override double WeaponAbilityChance{ get{ return 0.05; } }
public override int Meat{ get{ return 1; } }
/*
public override WeaponAbility GetWeaponAbility()
{
AreaPeace();
return null;
}
public virtual int PeaceRange{ get{ return 5; } }
public virtual TimeSpan PeaceDuration{ get{ return TimeSpan.FromMinutes( 1 ); } }
public virtual void AreaPeace()
{
IPooledEnumerable eable = Map.GetClientsInRange( Location, PeaceRange );
foreach( Server.Network.NetState state in eable )
{
if ( state.Mobile is PlayerMobile && state.Mobile.CanSee( this ) )
{
PlayerMobile player = (PlayerMobile) state.Mobile;
if ( player.PeacedUntil < DateTime.Now )
{
player.PeacedUntil = DateTime.Now + PeaceDuration;
player.SendLocalizedMessage( 1072065 ); // You gaze upon the dryad's beauty, and forget to continue battling!
}
}
}
}
*/
public override int GetDeathSound() { return 0x57A; }
public override int GetAttackSound() { return 0x57B; }
public override int GetIdleSound() { return 0x57C; }
public override int GetAngerSound() { return 0x57D; }
public override int GetHurtSound() { return 0x57E; }
public DryadA( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
| 25.859813 | 115 | 0.663535 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Customs/Nerun's Distro/ML/Mobiles/Twisted Weald/DryadA.cs | 2,767 | C# |
#region License
/*
* HttpDigestIdentity.cs
*
* The MIT License
*
* Copyright (c) 2014-2017 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Security.Principal;
namespace WebSocketCore.Net
{
/// <summary>
/// Holds the username and other parameters from
/// an HTTP Digest authentication attempt.
/// </summary>
public class HttpDigestIdentity : GenericIdentity
{
#region Private Fields
private NameValueCollection _parameters;
#endregion
#region Internal Constructors
internal HttpDigestIdentity (NameValueCollection parameters)
: base (parameters["username"], "Digest")
{
_parameters = parameters;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the algorithm parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the algorithm parameter.
/// </value>
public string Algorithm {
get {
return _parameters["algorithm"];
}
}
/// <summary>
/// Gets the cnonce parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the cnonce parameter.
/// </value>
public string Cnonce {
get {
return _parameters["cnonce"];
}
}
/// <summary>
/// Gets the nc parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the nc parameter.
/// </value>
public string Nc {
get {
return _parameters["nc"];
}
}
/// <summary>
/// Gets the nonce parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the nonce parameter.
/// </value>
public string Nonce {
get {
return _parameters["nonce"];
}
}
/// <summary>
/// Gets the opaque parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the opaque parameter.
/// </value>
public string Opaque {
get {
return _parameters["opaque"];
}
}
/// <summary>
/// Gets the qop parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the qop parameter.
/// </value>
public string Qop {
get {
return _parameters["qop"];
}
}
/// <summary>
/// Gets the realm parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the realm parameter.
/// </value>
public string Realm {
get {
return _parameters["realm"];
}
}
/// <summary>
/// Gets the response parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the response parameter.
/// </value>
public string Response {
get {
return _parameters["response"];
}
}
/// <summary>
/// Gets the uri parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the uri parameter.
/// </value>
public string Uri {
get {
return _parameters["uri"];
}
}
#endregion
#region Internal Methods
internal bool IsValid (
string password, string realm, string method, string entity
)
{
var copied = new NameValueCollection (_parameters);
copied["password"] = password;
copied["realm"] = realm;
copied["method"] = method;
copied["entity"] = entity;
var expected = AuthenticationResponse.CreateRequestDigest (copied);
return _parameters["response"] == expected;
}
#endregion
}
}
| 26.744681 | 80 | 0.628679 | [
"MIT"
] | 16it/surging | src/WebSocket/WebSocketCore/Net/HttpDigestIdentity.cs | 5,028 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace PizzaBox.Storing.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Crusts",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Pricing = table.Column<decimal>(type: "decimal(18,2)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Crusts", x => x.EntityId);
});
migrationBuilder.CreateTable(
name: "MenuItems",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Item = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_MenuItems", x => x.EntityId);
});
migrationBuilder.CreateTable(
name: "Sizes",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Pricing = table.Column<decimal>(type: "decimal(18,2)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sizes", x => x.EntityId);
});
migrationBuilder.CreateTable(
name: "Stores",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Stores", x => x.EntityId);
});
migrationBuilder.CreateTable(
name: "Toppings",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Pricing = table.Column<decimal>(type: "decimal(18,2)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Toppings", x => x.EntityId);
});
migrationBuilder.CreateTable(
name: "MenuStore",
columns: table => new
{
MenusEntityId = table.Column<long>(type: "bigint", nullable: false),
StoresEntityId = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MenuStore", x => new { x.MenusEntityId, x.StoresEntityId });
table.ForeignKey(
name: "FK_MenuStore_MenuItems_MenusEntityId",
column: x => x.MenusEntityId,
principalTable: "MenuItems",
principalColumn: "EntityId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_MenuStore_Stores_StoresEntityId",
column: x => x.StoresEntityId,
principalTable: "Stores",
principalColumn: "EntityId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SelectedStoreEntityId = table.Column<long>(type: "bigint", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.EntityId);
table.ForeignKey(
name: "FK_Users_Stores_SelectedStoreEntityId",
column: x => x.SelectedStoreEntityId,
principalTable: "Stores",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "ToppingLists",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Topping1EntityId = table.Column<long>(type: "bigint", nullable: true),
Topping2EntityId = table.Column<long>(type: "bigint", nullable: true),
Topping3EntityId = table.Column<long>(type: "bigint", nullable: true),
Topping4EntityId = table.Column<long>(type: "bigint", nullable: true),
Topping5EntityId = table.Column<long>(type: "bigint", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ToppingLists", x => x.EntityId);
table.ForeignKey(
name: "FK_ToppingLists_Toppings_Topping1EntityId",
column: x => x.Topping1EntityId,
principalTable: "Toppings",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ToppingLists_Toppings_Topping2EntityId",
column: x => x.Topping2EntityId,
principalTable: "Toppings",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ToppingLists_Toppings_Topping3EntityId",
column: x => x.Topping3EntityId,
principalTable: "Toppings",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ToppingLists_Toppings_Topping4EntityId",
column: x => x.Topping4EntityId,
principalTable: "Toppings",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ToppingLists_Toppings_Topping5EntityId",
column: x => x.Topping5EntityId,
principalTable: "Toppings",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Order",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
OrderTime = table.Column<DateTime>(type: "datetime2", nullable: false),
StoreEntityId = table.Column<long>(type: "bigint", nullable: true),
UserEntityId = table.Column<long>(type: "bigint", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Order", x => x.EntityId);
table.ForeignKey(
name: "FK_Order_Stores_StoreEntityId",
column: x => x.StoreEntityId,
principalTable: "Stores",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Order_Users_UserEntityId",
column: x => x.UserEntityId,
principalTable: "Users",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Pizzas",
columns: table => new
{
EntityId = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SizeEntityId = table.Column<long>(type: "bigint", nullable: true),
CrustEntityId = table.Column<long>(type: "bigint", nullable: true),
AToppingListEntityId = table.Column<long>(type: "bigint", nullable: true),
OrderEntityId = table.Column<long>(type: "bigint", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Pizzas", x => x.EntityId);
table.ForeignKey(
name: "FK_Pizzas_Crusts_CrustEntityId",
column: x => x.CrustEntityId,
principalTable: "Crusts",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Pizzas_Order_OrderEntityId",
column: x => x.OrderEntityId,
principalTable: "Order",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Pizzas_Sizes_SizeEntityId",
column: x => x.SizeEntityId,
principalTable: "Sizes",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Pizzas_ToppingLists_AToppingListEntityId",
column: x => x.AToppingListEntityId,
principalTable: "ToppingLists",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.InsertData(
table: "Crusts",
columns: new[] { "EntityId", "Name", "Pricing" },
values: new object[,]
{
{ 1L, "Thin", 1.00m },
{ 2L, "Regular", 1.50m },
{ 3L, "Thick", 2.00m }
});
migrationBuilder.InsertData(
table: "MenuItems",
columns: new[] { "EntityId", "Item" },
values: new object[,]
{
{ 1L, "MeatEaters Pizza" },
{ 2L, "Vegan Pizza" },
{ 3L, "Supreme Pizza" }
});
migrationBuilder.InsertData(
table: "Sizes",
columns: new[] { "EntityId", "Name", "Pricing" },
values: new object[,]
{
{ 2L, "Medium", 3.50m },
{ 3L, "Large", 4.00m },
{ 1L, "Small", 3.00m }
});
migrationBuilder.InsertData(
table: "Stores",
columns: new[] { "EntityId", "Name" },
values: new object[,]
{
{ 1L, "PizzaHut" },
{ 2L, "Dominos" }
});
migrationBuilder.InsertData(
table: "Toppings",
columns: new[] { "EntityId", "Name", "Pricing" },
values: new object[,]
{
{ 6L, "Black Olives", 1.50m },
{ 1L, "Pepperoni", 2.00m },
{ 2L, "Italian Sausage", 2.00m },
{ 3L, "Meatball", 2.00m },
{ 4L, "Mushroom", 1.50m },
{ 5L, "Red Onions", 1.50m },
{ 7L, "Green Bell Peppers", 1.50m }
});
migrationBuilder.InsertData(
table: "MenuStore",
columns: new[] { "MenusEntityId", "StoresEntityId" },
values: new object[] { 1L, 1L });
migrationBuilder.InsertData(
table: "MenuStore",
columns: new[] { "MenusEntityId", "StoresEntityId" },
values: new object[] { 2L, 1L });
migrationBuilder.InsertData(
table: "MenuStore",
columns: new[] { "MenusEntityId", "StoresEntityId" },
values: new object[] { 3L, 2L });
migrationBuilder.CreateIndex(
name: "IX_MenuStore_StoresEntityId",
table: "MenuStore",
column: "StoresEntityId");
migrationBuilder.CreateIndex(
name: "IX_Order_StoreEntityId",
table: "Order",
column: "StoreEntityId");
migrationBuilder.CreateIndex(
name: "IX_Order_UserEntityId",
table: "Order",
column: "UserEntityId");
migrationBuilder.CreateIndex(
name: "IX_Pizzas_AToppingListEntityId",
table: "Pizzas",
column: "AToppingListEntityId");
migrationBuilder.CreateIndex(
name: "IX_Pizzas_CrustEntityId",
table: "Pizzas",
column: "CrustEntityId");
migrationBuilder.CreateIndex(
name: "IX_Pizzas_OrderEntityId",
table: "Pizzas",
column: "OrderEntityId");
migrationBuilder.CreateIndex(
name: "IX_Pizzas_SizeEntityId",
table: "Pizzas",
column: "SizeEntityId");
migrationBuilder.CreateIndex(
name: "IX_ToppingLists_Topping1EntityId",
table: "ToppingLists",
column: "Topping1EntityId");
migrationBuilder.CreateIndex(
name: "IX_ToppingLists_Topping2EntityId",
table: "ToppingLists",
column: "Topping2EntityId");
migrationBuilder.CreateIndex(
name: "IX_ToppingLists_Topping3EntityId",
table: "ToppingLists",
column: "Topping3EntityId");
migrationBuilder.CreateIndex(
name: "IX_ToppingLists_Topping4EntityId",
table: "ToppingLists",
column: "Topping4EntityId");
migrationBuilder.CreateIndex(
name: "IX_ToppingLists_Topping5EntityId",
table: "ToppingLists",
column: "Topping5EntityId");
migrationBuilder.CreateIndex(
name: "IX_Users_SelectedStoreEntityId",
table: "Users",
column: "SelectedStoreEntityId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MenuStore");
migrationBuilder.DropTable(
name: "Pizzas");
migrationBuilder.DropTable(
name: "MenuItems");
migrationBuilder.DropTable(
name: "Crusts");
migrationBuilder.DropTable(
name: "Order");
migrationBuilder.DropTable(
name: "Sizes");
migrationBuilder.DropTable(
name: "ToppingLists");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "Toppings");
migrationBuilder.DropTable(
name: "Stores");
}
}
}
| 41.975186 | 101 | 0.462698 | [
"MIT"
] | KevinTouch/PizzaBox | aspnet/PizzaBox.Storing/Migrations/20210117100614_InitialCreate.cs | 16,918 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnitTests.Host.WorkspaceServices.Caching;
using Microsoft.CodeAnalysis.UnitTests.Persistence;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host.UnitTests
{
internal static class TestHost
{
private static HostServices testServices;
public static HostServices Services
{
get
{
if (testServices == null)
{
var tmp = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(new[] { typeof(TestHost).Assembly }));
System.Threading.Interlocked.CompareExchange(ref testServices, tmp, null);
}
return testServices;
}
}
}
}
| 32.636364 | 184 | 0.669452 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Workspaces/CoreTest/Host/TestHost.cs | 1,079 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.Test.Utility;
using System.IO;
using Xunit;
using System.Diagnostics;
namespace NuGet.Common.Test
{
public class DirectoryUtilityTests
{
[Fact]
public void DirectoryUtility_CreateSharedDirectory_BasicSuccess()
{
using (var testDirectory = TestDirectory.Create())
{
// Arrange
var parentDir = Path.Combine(testDirectory, "parent");
var childDir = Path.Combine(parentDir, "child");
// Act
DirectoryUtility.CreateSharedDirectory(childDir);
// Assert
Assert.True(Directory.Exists(parentDir));
Assert.True(Directory.Exists(childDir));
if (!RuntimeEnvironmentHelper.IsWindows)
{
Assert.Equal("777", StatPermissions(parentDir));
Assert.Equal("777", StatPermissions(childDir));
}
}
}
[Fact]
public void DirectoryUtility_CreateSharedDirectory_Idempotent()
{
using (var testDirectory = TestDirectory.Create())
{
// Arrange
var parentDir = Path.Combine(testDirectory, "parent");
var childDir = Path.Combine(parentDir, "child");
DirectoryUtility.CreateSharedDirectory(childDir);
// Act
DirectoryUtility.CreateSharedDirectory(childDir);
// Assert
Assert.True(Directory.Exists(parentDir));
Assert.True(Directory.Exists(childDir));
}
}
private string StatPermissions(string path)
{
string permissions;
ProcessStartInfo startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
FileName = "stat"
};
if (RuntimeEnvironmentHelper.IsLinux)
{
startInfo.Arguments = "-c %a " + path;
}
else
{
startInfo.Arguments = "-f %A " + path;
}
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
permissions = process.StandardOutput.ReadLine();
process.WaitForExit();
}
return permissions;
}
}
}
| 30.622222 | 111 | 0.526488 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | test/NuGet.Core.Tests/NuGet.Common.Test/DirectoryUtilityTests.cs | 2,756 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.